Skip to main content

ant_node/storage/
lmdb.rs

1//! Content-addressed LMDB storage for chunks.
2//!
3//! Provides persistent storage for chunks using LMDB (via heed) for
4//! memory-mapped, zero-copy reads with ACID transactions.
5//!
6//! ```text
7//! {root}/chunks.mdb/   -- LMDB environment directory
8//! ```
9
10use crate::ant_protocol::{XorName, MAX_CHUNK_SIZE};
11use crate::error::{Error, Result};
12use crate::logging::{debug, info, trace, warn};
13use heed::types::Bytes;
14use heed::{Database, Env, EnvOpenOptions, MdbError};
15use std::path::{Path, PathBuf};
16use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
17use std::sync::Arc;
18use std::time::Instant;
19use tokio::task::spawn_blocking;
20use tokio_util::task::TaskTracker;
21
22use crate::ant_protocol::XORNAME_LEN;
23use crate::storage::StorageStats;
24
25use crate::storage::{GIB, MIB};
26
27/// Default minimum free disk space to preserve on the storage partition.
28const DEFAULT_DISK_RESERVE: u64 = 500 * MIB;
29
30/// Convert a byte count to GiB for human-readable log messages.
31#[allow(clippy::cast_precision_loss)] // display only — sub-byte precision is irrelevant
32fn bytes_to_gib(bytes: u64) -> f64 {
33    bytes as f64 / GIB as f64
34}
35
36/// Absolute minimum LMDB map size.
37///
38/// Even on a nearly-full disk the database must be able to open.
39/// Set to 256 MiB — enough for millions of LMDB pages.
40const MIN_MAP_SIZE: usize = 256 * 1024 * 1024;
41
42/// Maximum head-room (beyond the current data footprint) to reserve for the
43/// LMDB map **on Windows**.
44///
45/// On Windows a node's committed / private memory scales with the *mapped*
46/// size rather than with the data actually stored. Measured on a live node:
47/// ~7.4 GB of extra commit for a ~3.7 TiB map, versus ~181 MB for a ~55 GiB
48/// map — roughly 0.2% of the mapped size, resident and attributed to *no*
49/// user-space allocation. That size-proportional cost is consistent with
50/// kernel page tables / section metadata for the mapping; the exact kernel
51/// structure was inferred from the scaling rather than measured directly, but
52/// the size-proportional *effect* is what this cap targets. Linux keeps the
53/// mapping sparse, so a disk-sized map is nearly free there — the overhead is
54/// Windows-specific, which is why it only surfaced in Windows reports.
55///
56/// Sizing the map to the whole disk therefore costs ~0.2% of *free disk* per
57/// node, multiplied by every node sharing the host (e.g. a 10 TiB partition ≈
58/// 20 GiB). We instead cap the head-room on Windows and lean on
59/// `LmdbStorage::try_resize` to extend the map on demand as data accumulates,
60/// keeping the overhead proportional to *stored data* rather than *disk
61/// capacity*. At 32 GiB the extra commit is ~100 MB, and a resize happens at
62/// most once per 32 GiB written.
63#[cfg(windows)]
64const WINDOWS_MAP_HEADROOM: u64 = 32 * GIB;
65
66/// How often to re-query available disk space (in seconds).
67///
68/// Between checks the cached result is trusted.  Disk space changes slowly
69/// relative to chunk-write throughput, so a multi-second window is safe.
70const DISK_CHECK_INTERVAL_SECS: u64 = 5;
71
72/// Ceiling raise offered to a single *delete* that cannot copy-on-write inside
73/// the pinned map.
74///
75/// A delete is itself a write: LMDB copies the B-tree path before it frees the
76/// leaf pages, and it may need a page for the free-list's own bookkeeping. On a
77/// map pinned exactly to the file size a delete therefore has nowhere to go,
78/// and the node could not prune its way back to health.
79///
80/// Granted **only** on the delete retry path and taken away again inside the
81/// same locked scope, so an ordinary store can never allocate from it. Leaving
82/// it permanently in the ceiling would hand every node a little more of the
83/// very reserve this mode exists to protect, multiplied by the nodes sharing
84/// the volume.
85const DELETE_COW_SLACK: u64 = 256 * 1024;
86
87/// Total permanent file growth deletes may cause per low-disk episode.
88///
89/// What actually needs bounding is *growth*, not grants. Most slack-assisted
90/// deletes reuse pages already inside `data.mdb` and grow it by nothing, and
91/// those must stay free: a node has to be able to prune indefinitely, and page
92/// reuse is not reliably available to the very next delete because LMDB cannot
93/// hand back pages a still-recent transaction freed. Charging per grant instead
94/// of per byte stops a node pruning after its first assisted delete.
95///
96/// Only bytes the file actually gained are charged here. Reset when the store
97/// leaves no-growth mode. A rounding error against [`DEFAULT_DISK_RESERVE`].
98const DELETE_COW_GROWTH_BUDGET: u64 = 1024 * 1024;
99
100/// Configuration for LMDB storage.
101#[derive(Debug, Clone)]
102pub struct LmdbStorageConfig {
103    /// Root directory for storage (LMDB env lives at `{root_dir}/chunks.mdb/`).
104    pub root_dir: PathBuf,
105    /// Whether to verify content on read (compares hash to address).
106    pub verify_on_read: bool,
107    /// Explicit LMDB map size cap in bytes.
108    ///
109    /// When 0 (default), the map size is computed automatically from available
110    /// disk space and grows on demand when more storage becomes available.
111    pub max_map_size: usize,
112    /// Minimum free disk space (in bytes) to preserve on the storage partition.
113    ///
114    /// Writes are refused when available space drops below this threshold.
115    pub disk_reserve: u64,
116}
117
118impl Default for LmdbStorageConfig {
119    fn default() -> Self {
120        Self {
121            root_dir: PathBuf::from(".ant/chunks"),
122            verify_on_read: true,
123            max_map_size: 0,
124            disk_reserve: DEFAULT_DISK_RESERVE,
125        }
126    }
127}
128
129impl LmdbStorageConfig {
130    /// A test-friendly default with `disk_reserve` set to 0 so unit tests
131    /// don't depend on the host having >= 1 GiB free disk space.
132    #[cfg(any(test, feature = "test-utils"))]
133    #[must_use]
134    pub fn test_default() -> Self {
135        Self {
136            disk_reserve: 0,
137            ..Self::default()
138        }
139    }
140}
141
142/// Content-addressed LMDB storage.
143///
144/// Uses heed (LMDB wrapper) for memory-mapped, transactional chunk storage.
145/// Keys are 32-byte `XorName` addresses, values are raw chunk bytes.
146pub struct LmdbStorage {
147    /// LMDB environment.
148    env: Env,
149    /// The unnamed default database (key=XorName bytes, value=chunk bytes).
150    db: Database<Bytes, Bytes>,
151    /// Storage configuration.
152    config: LmdbStorageConfig,
153    /// Path to the LMDB environment directory (for disk-space queries).
154    env_dir: PathBuf,
155    /// Operation statistics.
156    stats: parking_lot::RwLock<StorageStats>,
157    /// Serialises access to the LMDB environment during a map resize.
158    ///
159    /// Normal read/write operations acquire a **shared** lock.  The rare
160    /// resize path acquires an **exclusive** lock, ensuring no transactions
161    /// are active when `env.resize()` is called (an LMDB safety requirement).
162    env_lock: Arc<parking_lot::RwLock<()>>,
163    /// Timestamp of the last successful disk-space check.
164    ///
165    /// `None` means "never checked — check on next write".  Updated only
166    /// after a passing check, so a low-space result is always rechecked.
167    last_disk_ok: parking_lot::Mutex<Option<Instant>>,
168    /// Whether the map is currently pinned to the file's high-water mark.
169    ///
170    /// Set once available disk drops below the reserve. While pinned, LMDB can
171    /// still serve a write from its own free list but cannot extend
172    /// `data.mdb`, so the reserve is preserved by the allocator itself rather
173    /// than by refusing every write up front.
174    no_growth: Arc<AtomicBool>,
175    /// Keep the map pinned whatever the free space says.
176    ///
177    /// Set for the whole of the migration bridge. While both stores are open they each
178    /// measure the same free space and neither knows what the other is about to spend, so
179    /// a chunk written to both can be admitted twice against one lot of headroom and the
180    /// pair can cross the reserve together. Pinned, this environment cannot claim any new
181    /// disk at all: a write it cannot satisfy from its own free list is refused, and the
182    /// caller stores the chunk in files alone. That is the right answer anyway, because
183    /// this copy exists to make a rollback survivable, not to be the one that must
184    /// succeed.
185    growth_pinned: Arc<AtomicBool>,
186    /// Serialises entering and leaving no-growth mode.
187    ///
188    /// Setting `no_growth` and resizing the map is one compound transition
189    /// spanning an await. Without this, two callers straddling the threshold
190    /// can interleave so the flag ends up describing a map size that was never
191    /// applied, leaving the store unpinned while it believes it is pinned.
192    growth_mode_lock: tokio::sync::Mutex<()>,
193    /// Bytes `data.mdb` has permanently gained to slack-assisted deletes in
194    /// this low-disk episode.
195    ///
196    /// A delete's copy-on-write can extend the file, and LMDB never gives file
197    /// space back, so that growth is permanent. Bounding it stops repeated
198    /// fill-then-delete cycles walking the file into the reserve. Deletes that
199    /// find room inside the file cost nothing. Reset on leaving no-growth mode.
200    delete_growth_charged: Arc<AtomicU64>,
201    /// Tracks every LMDB blocking task spawned by this storage.
202    ///
203    /// A `spawn_blocking` closure owns a cloned [`Env`] and keeps running
204    /// even when its async awaiter is dropped (e.g. by a `select!` losing to
205    /// a shutdown token).  Tracking the blocking task itself — not the async
206    /// wrapper — lets [`Self::wait_idle`] wait for true quiescence before
207    /// the environment may be reopened.
208    blocking_tracker: TaskTracker,
209    /// Test-only gate read-acquired at the top of the put blocking closure.
210    ///
211    /// Tests hold the write half to deterministically park an in-flight put
212    /// on the blocking pool (e.g. to prove [`Self::wait_idle`] waits for a
213    /// detached write).
214    #[cfg(any(test, feature = "test-utils"))]
215    test_put_gate: Arc<parking_lot::RwLock<()>>,
216    /// Test-only gate read-acquired inside the raw-read blocking closures,
217    /// immediately after the shared `env_lock` guard is taken.
218    ///
219    /// Tests hold the write half to deterministically park an in-flight raw
220    /// read while it still holds the shared environment lock (e.g. to prove
221    /// [`Self::try_resize`] waits for active raw reads before calling
222    /// `env.resize()`).
223    #[cfg(any(test, feature = "test-utils"))]
224    test_read_gate: Arc<parking_lot::RwLock<()>>,
225}
226
227impl LmdbStorage {
228    /// Create a new LMDB storage instance.
229    ///
230    /// Opens (or creates) an LMDB environment at `{root_dir}/chunks.mdb/`.
231    ///
232    /// When `config.max_map_size` is 0 (the default) the map size is derived
233    /// from the available disk space on the partition that hosts the database,
234    /// minus `config.disk_reserve`.  This allows a node to use all available
235    /// storage without a fixed cap.  If the operator adds more storage later
236    /// the map is resized on demand (see [`Self::put`]).
237    ///
238    /// # Errors
239    ///
240    /// Returns an error if the LMDB environment cannot be opened.
241    #[allow(unsafe_code)]
242    pub async fn new(config: LmdbStorageConfig) -> Result<Self> {
243        let env_dir = config.root_dir.join("chunks.mdb");
244
245        // Create the directory synchronously before opening LMDB
246        std::fs::create_dir_all(&env_dir)
247            .map_err(|e| Error::Storage(format!("Failed to create LMDB directory: {e}")))?;
248
249        let map_size = if config.max_map_size > 0 {
250            // Operator provided an explicit cap.
251            config.max_map_size
252        } else {
253            // Auto-scale: current DB footprint + available space − reserve.
254            let computed = compute_map_size(&env_dir, config.disk_reserve)?;
255            info!(
256                "Auto-computed LMDB map size: {:.2} GiB (data + available disk minus {:.2} GiB \
257                 reserve, head-room capped on Windows to bound page-table overhead)",
258                bytes_to_gib(computed as u64),
259                bytes_to_gib(config.disk_reserve),
260            );
261            computed
262        };
263
264        let env_dir_clone = env_dir.clone();
265        // Constructor-only blocking task: it runs before `self` (and its
266        // `blocking_tracker`) exists, so it is deliberately untracked.  The
267        // constructor awaits it right here, so it cannot outlive this call.
268        let (env, db) = spawn_blocking(move || -> Result<(Env, Database<Bytes, Bytes>)> {
269            // SAFETY: `EnvOpenOptions::open()` is unsafe because LMDB uses memory-mapped
270            // I/O and relies on OS file-locking to prevent corruption from concurrent
271            // access by multiple processes. We satisfy this by giving each node instance
272            // a unique `root_dir` (typically a directory named by its full 64-hex peer
273            // ID), ensuring no two processes open the same LMDB environment. Callers
274            // who manually configure `--root-dir` must not point multiple nodes at the
275            // same directory.
276            let env = unsafe {
277                EnvOpenOptions::new()
278                    .map_size(map_size)
279                    .max_dbs(1)
280                    .open(&env_dir_clone)
281                    .map_err(|e| Error::Storage(format!("Failed to open LMDB env: {e}")))?
282            };
283
284            let mut wtxn = env
285                .write_txn()
286                .map_err(|e| Error::Storage(format!("Failed to create write txn: {e}")))?;
287            let db: Database<Bytes, Bytes> = env
288                .create_database(&mut wtxn, None)
289                .map_err(|e| Error::Storage(format!("Failed to create database: {e}")))?;
290            wtxn.commit()
291                .map_err(|e| Error::Storage(format!("Failed to commit db creation: {e}")))?;
292
293            Ok((env, db))
294        })
295        .await
296        .map_err(|e| Error::Storage(format!("LMDB init task failed: {e}")))??;
297
298        let storage = Self {
299            env,
300            db,
301            config,
302            env_dir,
303            stats: parking_lot::RwLock::new(StorageStats::default()),
304            env_lock: Arc::new(parking_lot::RwLock::new(())),
305            last_disk_ok: parking_lot::Mutex::new(None),
306            no_growth: Arc::new(AtomicBool::new(false)),
307            growth_pinned: Arc::new(AtomicBool::new(false)),
308            growth_mode_lock: tokio::sync::Mutex::new(()),
309            delete_growth_charged: Arc::new(AtomicU64::new(0)),
310            blocking_tracker: TaskTracker::new(),
311            #[cfg(any(test, feature = "test-utils"))]
312            test_put_gate: Arc::new(parking_lot::RwLock::new(())),
313            #[cfg(any(test, feature = "test-utils"))]
314            test_read_gate: Arc::new(parking_lot::RwLock::new(())),
315        };
316
317        debug!(
318            "Initialized LMDB storage at {:?} ({} existing chunks)",
319            storage.env_dir,
320            storage.current_chunks()?
321        );
322
323        Ok(storage)
324    }
325
326    /// Store a chunk.
327    ///
328    /// Before writing, verifies that available disk space exceeds the
329    /// configured reserve.  If the LMDB map is full but more disk space
330    /// exists (e.g. the operator added storage), the map is resized
331    /// automatically and the write is retried.
332    ///
333    /// # Returns
334    ///
335    /// Returns `true` if the chunk was newly stored, `false` if it already existed.
336    ///
337    /// # Errors
338    ///
339    /// Returns an error if the write fails, content doesn't match address,
340    /// or the disk is too full to accept new chunks.
341    pub async fn put(&self, address: &XorName, content: &[u8]) -> Result<bool> {
342        self.put_inner(address, content, true).await
343    }
344
345    /// Store bytes under a key they do not hash to. Tests only.
346    ///
347    /// Stands in for a record that rotted in place, which is the one shape the ordinary
348    /// path refuses to create and the migration has to survive finding.
349    ///
350    /// # Errors
351    ///
352    /// As [`Self::put`], minus the address check.
353    #[cfg(test)]
354    pub(crate) async fn put_unchecked(&self, address: &XorName, content: &[u8]) -> Result<bool> {
355        self.put_inner(address, content, false).await
356    }
357
358    async fn put_inner(&self, address: &XorName, content: &[u8], verify: bool) -> Result<bool> {
359        // Verify content address
360        let computed = Self::compute_address(content);
361        if verify && computed != *address {
362            return Err(Error::Storage(format!(
363                "Content address mismatch: expected {}, computed {}",
364                hex::encode(address),
365                hex::encode(computed)
366            )));
367        }
368
369        // Fast-path duplicate check (read-only, no write lock needed).
370        // This is an optimistic hint — the authoritative check happens inside
371        // the write transaction below to prevent TOCTOU races.
372        if self.exists(address)? {
373            trace!("Chunk {} already exists", hex::encode(address));
374            self.stats.write().duplicates += 1;
375            return Ok(false);
376        }
377
378        // ── Capacity guard (cached — at most one syscall per interval) ──
379        // Placed after the duplicate check so that re-storing an existing
380        // chunk remains a harmless no-op even when disk space is low.
381        //
382        // Below the reserve this pins the map instead of refusing outright, so
383        // the write is still attempted and LMDB decides whether a freed page
384        // can take it. A node that has pruned heavily keeps serving the network
385        // from the space it already occupies.
386        let no_growth = self.sync_growth_mode().await?;
387
388        // ── Write (with resize-on-demand) ───────────────────────────────
389        match self.try_put(address, content).await? {
390            PutOutcome::New => {}
391            PutOutcome::Duplicate => {
392                trace!("Chunk {} already exists", hex::encode(address));
393                self.stats.write().duplicates += 1;
394                return Ok(false);
395            }
396            PutOutcome::MapFull if no_growth => {
397                // Both halves are now true: the volume is below the reserve and
398                // no free page can take *this* value. Resizing would extend the
399                // file into the reserve, so refuse.
400                //
401                // The refusal is not remembered. `MapFull` is specific to the
402                // size just attempted — a smaller value may still fit a smaller
403                // run — so caching it would let one maximum-sized chunk lock out
404                // every subsequent write. `check_capacity` estimates instead.
405                return Err(Error::Storage(format!(
406                    "Insufficient disk space: {:.2} GiB reserve required and no reusable page \
407                     in the local store fits this {} B value. \
408                     Free disk space or increase the partition to continue storing chunks.",
409                    bytes_to_gib(self.config.disk_reserve),
410                    content.len(),
411                )));
412            }
413            PutOutcome::MapFull => {
414                // The map ceiling was reached but there may be more disk space
415                // available (e.g. operator expanded the partition).
416                //
417                // Guarded: `no_growth` was sampled before the write, so the
418                // store may have entered no-growth mode since. Growing the map
419                // outside the transition lock could undo a pin that a
420                // concurrent `sync_growth_mode` had just applied, handing the
421                // reserve back to ordinary writes.
422                self.try_resize_for_growth().await?;
423                // Retry once after resize.
424                match self.try_put(address, content).await? {
425                    PutOutcome::New => {}
426                    PutOutcome::Duplicate => {
427                        self.stats.write().duplicates += 1;
428                        return Ok(false);
429                    }
430                    PutOutcome::MapFull => {
431                        return Err(Error::Storage(
432                            "LMDB map full after resize — disk may be at capacity".into(),
433                        ));
434                    }
435                }
436            }
437        }
438
439        {
440            let mut stats = self.stats.write();
441            stats.chunks_stored += 1;
442            stats.bytes_stored += content.len() as u64;
443        }
444
445        debug!(
446            "Stored chunk {} ({} bytes)",
447            hex::encode(address),
448            content.len()
449        );
450
451        Ok(true)
452    }
453
454    /// Attempt a single put inside a write transaction.
455    ///
456    /// Returns [`PutOutcome::MapFull`] instead of an error when the LMDB map
457    /// ceiling is reached, so the caller can resize and retry.
458    async fn try_put(&self, address: &XorName, content: &[u8]) -> Result<PutOutcome> {
459        let key = *address;
460        let value = content.to_vec();
461        let env = self.env.clone();
462        let db = self.db;
463        let lock = Arc::clone(&self.env_lock);
464        #[cfg(any(test, feature = "test-utils"))]
465        let test_put_gate = Arc::clone(&self.test_put_gate);
466
467        self.blocking_tracker
468            .spawn_blocking(move || -> Result<PutOutcome> {
469                // Test-only: parks here while a test holds the write half.
470                #[cfg(any(test, feature = "test-utils"))]
471                let _test_put_gate = test_put_gate.read();
472                let _guard = lock.read();
473
474                let mut wtxn = env
475                    .write_txn()
476                    .map_err(|e| Error::Storage(format!("Failed to create write txn: {e}")))?;
477
478                // Authoritative existence check inside the serialized write txn
479                if db
480                    .get(&wtxn, &key)
481                    .map_err(|e| Error::Storage(format!("Failed to check existence: {e}")))?
482                    .is_some()
483                {
484                    return Ok(PutOutcome::Duplicate);
485                }
486
487                match db.put(&mut wtxn, &key, &value) {
488                    Ok(()) => {}
489                    Err(heed::Error::Mdb(MdbError::MapFull)) => return Ok(PutOutcome::MapFull),
490                    Err(e) => {
491                        return Err(Error::Storage(format!("Failed to put chunk: {e}")));
492                    }
493                }
494
495                match wtxn.commit() {
496                    Ok(()) => Ok(PutOutcome::New),
497                    Err(heed::Error::Mdb(MdbError::MapFull)) => Ok(PutOutcome::MapFull),
498                    Err(e) => Err(Error::Storage(format!("Failed to commit put: {e}"))),
499                }
500            })
501            .await
502            .map_err(|e| Error::Storage(format!("LMDB put task failed: {e}")))?
503    }
504
505    /// Retrieve a chunk.
506    ///
507    /// # Returns
508    ///
509    /// Returns `Some(content)` if found, `None` if not found.
510    ///
511    /// # Errors
512    ///
513    /// Returns an error if read fails or verification fails.
514    pub async fn get(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
515        let key = *address;
516        let env = self.env.clone();
517        let db = self.db;
518        let lock = Arc::clone(&self.env_lock);
519
520        let content = self
521            .blocking_tracker
522            .spawn_blocking(move || -> Result<Option<Vec<u8>>> {
523                let _guard = lock.read();
524                let rtxn = env
525                    .read_txn()
526                    .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
527                let value = db
528                    .get(&rtxn, &key)
529                    .map_err(|e| Error::Storage(format!("Failed to get chunk: {e}")))?;
530                Ok(value.map(Vec::from))
531            })
532            .await
533            .map_err(|e| Error::Storage(format!("LMDB get task failed: {e}")))??;
534
535        let Some(content) = content else {
536            trace!("Chunk {} not found", hex::encode(address));
537            return Ok(None);
538        };
539
540        // Verify content if configured
541        if self.config.verify_on_read {
542            let computed = Self::compute_address(&content);
543            if computed != *address {
544                self.stats.write().verification_failures += 1;
545                warn!(
546                    "Chunk verification failed: expected {}, computed {}",
547                    hex::encode(address),
548                    hex::encode(computed)
549                );
550                return Err(Error::Storage(format!(
551                    "Chunk verification failed for {}",
552                    hex::encode(address)
553                )));
554            }
555        }
556
557        {
558            let mut stats = self.stats.write();
559            stats.chunks_retrieved += 1;
560            stats.bytes_retrieved += content.len() as u64;
561        }
562
563        debug!(
564            "Retrieved chunk {} ({} bytes)",
565            hex::encode(address),
566            content.len()
567        );
568
569        Ok(Some(content))
570    }
571
572    /// Check if a chunk exists.
573    ///
574    /// # Errors
575    ///
576    /// Returns an error if the LMDB read transaction fails.
577    pub fn exists(&self, address: &XorName) -> Result<bool> {
578        let _guard = self.env_lock.read();
579        let rtxn = self
580            .env
581            .read_txn()
582            .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
583        let found = self
584            .db
585            .get(&rtxn, address.as_ref())
586            .map_err(|e| Error::Storage(format!("Failed to check existence: {e}")))?
587            .is_some();
588        Ok(found)
589    }
590
591    /// Delete a chunk.
592    ///
593    /// # Errors
594    ///
595    /// Returns an error if deletion fails.
596    pub async fn delete(&self, address: &XorName) -> Result<bool> {
597        let key = *address;
598
599        // Establish growth mode first, exactly as `put` does. Otherwise a
600        // delete arriving while the volume is low but before any write has
601        // pinned the map would copy-on-write into whatever head-room the
602        // ceiling still had, growing `data.mdb` into the reserve without
603        // passing through the budgeted allowance below.
604        self.sync_growth_mode().await?;
605
606        let deleted = match self.try_delete(&key).await? {
607            DeleteOutcome::Done(existed) => existed,
608            DeleteOutcome::MapFull => {
609                // A delete is a write: LMDB copies the B-tree path before it
610                // frees the leaf pages, so a store with no free page at all
611                // cannot delete inside a map pinned to the file size. Without a
612                // way through, a node that filled up before it ever pruned
613                // could never prune its way out.
614                //
615                // Serialised against `sync_growth_mode` so the two cannot
616                // interleave their resizes.
617                let _transition = self.growth_mode_lock.lock().await;
618                self.delete_with_slack(&key).await?
619            }
620        };
621
622        if deleted {
623            debug!("Deleted chunk {}", hex::encode(address));
624        }
625
626        Ok(deleted)
627    }
628
629    /// Attempt one delete, reporting `MapFull` rather than raising it.
630    async fn try_delete(&self, key: &XorName) -> Result<DeleteOutcome> {
631        let key = *key;
632        let env = self.env.clone();
633        let db = self.db;
634        let lock = Arc::clone(&self.env_lock);
635
636        self.blocking_tracker
637            .spawn_blocking(move || -> Result<DeleteOutcome> {
638                let _guard = lock.read();
639                delete_in_txn(&env, db, &key)
640            })
641            .await
642            .map_err(|e| Error::Storage(format!("LMDB delete task failed: {e}")))?
643    }
644
645    /// Get storage statistics.
646    #[must_use]
647    pub fn stats(&self) -> StorageStats {
648        let mut stats = self.stats.read().clone();
649        match self.current_chunks() {
650            Ok(count) => stats.current_chunks = count,
651            Err(e) => {
652                warn!("Failed to read current_chunks for stats: {e}");
653                stats.current_chunks = 0;
654            }
655        }
656        stats
657    }
658
659    /// Return the number of chunks currently stored, queried from LMDB metadata.
660    ///
661    /// This is an O(1) read of the B-tree page header — not a full scan.
662    ///
663    /// # Errors
664    ///
665    /// Returns an error if the LMDB read transaction fails.
666    pub fn current_chunks(&self) -> Result<u64> {
667        let _guard = self.env_lock.read();
668        let rtxn = self
669            .env
670            .read_txn()
671            .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
672        let entries = self
673            .db
674            .stat(&rtxn)
675            .map_err(|e| Error::Storage(format!("Failed to read db stats: {e}")))?
676            .entries;
677        Ok(entries as u64)
678    }
679
680    /// Compute content address (BLAKE3 hash).
681    #[must_use]
682    pub fn compute_address(content: &[u8]) -> XorName {
683        crate::client::compute_address(content)
684    }
685
686    /// Get the root directory.
687    #[must_use]
688    pub fn root_dir(&self) -> &Path {
689        &self.config.root_dir
690    }
691
692    /// Return all stored record keys.
693    ///
694    /// Iterates the LMDB database in a read transaction. Used by the
695    /// replication subsystem for hint construction and audit sampling.
696    ///
697    /// # Errors
698    ///
699    /// Returns an error if the LMDB read transaction fails.
700    pub async fn all_keys(&self) -> Result<Vec<XorName>> {
701        let env = self.env.clone();
702        let db = self.db;
703        let lock = Arc::clone(&self.env_lock);
704
705        let keys = self
706            .blocking_tracker
707            .spawn_blocking(move || -> Result<Vec<XorName>> {
708                // Hold the shared lock for the whole read so try_resize() (which
709                // takes the exclusive lock before the unsafe Env::resize()) cannot
710                // unmap the environment while this txn and its cursor are live.
711                let _guard = lock.read();
712                let rtxn = env
713                    .read_txn()
714                    .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
715                let mut keys = Vec::new();
716                let iter = db
717                    .iter(&rtxn)
718                    .map_err(|e| Error::Storage(format!("Failed to iterate database: {e}")))?;
719                for result in iter {
720                    let (key_bytes, _) =
721                        result.map_err(|e| Error::Storage(format!("Failed to read entry: {e}")))?;
722                    if key_bytes.len() == XORNAME_LEN {
723                        let mut key = [0u8; XORNAME_LEN];
724                        key.copy_from_slice(key_bytes);
725                        keys.push(key);
726                    } else {
727                        crate::logging::warn!(
728                            "LmdbStorage: skipping entry with unexpected key length {} (expected {XORNAME_LEN})",
729                            key_bytes.len()
730                        );
731                    }
732                }
733                Ok(keys)
734            })
735            .await
736            .map_err(|e| Error::Storage(format!("all_keys task failed: {e}")))?;
737
738        keys
739    }
740
741    /// Retrieve raw chunk bytes without content-address verification.
742    ///
743    /// Used by the audit subsystem to compute digests over stored bytes.
744    /// Unlike [`Self::get`], this does not verify `hash(content) == address`.
745    ///
746    /// # Errors
747    ///
748    /// Returns an error if the LMDB read transaction fails.
749    pub async fn get_raw(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
750        let key = *address;
751        let env = self.env.clone();
752        let db = self.db;
753        let lock = Arc::clone(&self.env_lock);
754        #[cfg(any(test, feature = "test-utils"))]
755        let test_read_gate = Arc::clone(&self.test_read_gate);
756
757        let value = self
758            .blocking_tracker
759            .spawn_blocking(move || -> Result<Option<Vec<u8>>> {
760                // Shared lock held until the bytes are copied out, so a concurrent
761                // try_resize() cannot unmap the environment mid-read. See all_keys.
762                let _guard = lock.read();
763                // Test-only: parks here, still holding the shared lock, while a
764                // test holds the write half — used to prove a resize waits.
765                #[cfg(any(test, feature = "test-utils"))]
766                let _test_read_gate = test_read_gate.read();
767                let rtxn = env
768                    .read_txn()
769                    .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
770                let val = db
771                    .get(&rtxn, key.as_ref())
772                    .map_err(|e| Error::Storage(format!("Failed to get chunk: {e}")))?;
773                Ok(val.map(Vec::from))
774            })
775            .await
776            .map_err(|e| Error::Storage(format!("get_raw task failed: {e}")))?;
777
778        value
779    }
780
781    /// Cheap capacity pre-check for callers that want to reject work *before*
782    /// doing expensive setup (e.g. the PUT handler skipping payment
783    /// verification on a full node — see `V2-411`).
784    ///
785    /// A node is full only when **both** halves are true: the volume is below
786    /// the reserve *and* the store has no reusable page left. Deleting a record
787    /// returns its pages to LMDB's free list and never to the filesystem, so a
788    /// node that has pruned heavily sits on reusable capacity while `statvfs`
789    /// still reports the volume as full. Refusing on the disk half alone stops
790    /// such a node from writing into space it already owns.
791    ///
792    /// This is a **hint**, deliberately biased towards admitting: it estimates
793    /// reusable bytes and only refuses when there is not even one chunk's worth.
794    /// The authority on whether a given write fits stays with LMDB's allocator
795    /// in [`Self::put`], because no page count can account for the
796    /// copy-on-write of the B-tree path, the contiguous run a multi-megabyte
797    /// value needs, or pages still pinned by an open read transaction. An
798    /// over-optimistic hint costs one refused write; an over-pessimistic one
799    /// would recreate the bug this exists to fix.
800    ///
801    /// # Errors
802    ///
803    /// Returns [`Error::Storage`] when the volume is below the reserve and the
804    /// store holds less than one chunk of reusable space, or when the
805    /// disk-space query itself fails.
806    /// Unused while the node is moving off this store.
807    ///
808    /// Capacity is now the file store's question, because that is where writes land, and
809    /// this predicate deliberately answers a different one: it counts pages this store can
810    /// reuse internally, which says nothing about whether the *file* about to be written
811    /// will fit. [`Self::capacity_verdict`] is still used, to decide whether the bridge's
812    /// copy into this store is worth attempting. Both go when this store does.
813    #[allow(dead_code)]
814    pub(crate) fn check_capacity(&self) -> Result<()> {
815        let Some(available) = self.available_space_cached()? else {
816            return Ok(());
817        };
818
819        let reusable = self.reusable_bytes()?;
820        if reusable >= MAX_CHUNK_SIZE as u64 {
821            return Ok(());
822        }
823
824        Err(Error::Storage(format!(
825            "Insufficient disk space: {:.2} GiB available, {:.2} GiB reserve required, \
826             and only {reusable} B reusable inside the local store. \
827             Free disk space or increase the partition to continue storing chunks.",
828            bytes_to_gib(available),
829            bytes_to_gib(self.config.disk_reserve),
830        )))
831    }
832
833    /// Capacity as a three-way verdict, distinguishing a full node from a
834    /// query that failed.
835    ///
836    /// Refuses on the same two-part predicate as [`Self::check_capacity`]:
837    /// `Full` only when the volume is below the reserve *and* the store holds
838    /// less than one chunk of reusable space. Deleted records return their
839    /// pages to LMDB's free list and never to the filesystem, so a pruned node
840    /// reads as full to `statvfs` while still able to store chunks — such a
841    /// node must keep discovering holders for the keys it owes.
842    ///
843    /// Shares the same TTL cache as [`Self::check_capacity`]: a passing disk
844    /// reading is cached, a failing one is always rechecked, so freed space is
845    /// noticed promptly. An admit that rests on reusable pages is deliberately
846    /// not cached, matching the pre-check, because the free list can drain a
847    /// chunk at a time.
848    pub(crate) fn capacity_verdict(&self) -> CapacityVerdict {
849        {
850            let last = self.last_disk_ok.lock();
851            if let Some(t) = *last {
852                if t.elapsed().as_secs() < DISK_CHECK_INTERVAL_SECS {
853                    return CapacityVerdict::Writable;
854                }
855            }
856        }
857        let disk = verdict_from_available_space(
858            fs2::available_space(&self.env_dir),
859            self.config.disk_reserve,
860        );
861        match disk {
862            CapacityVerdict::Writable => {
863                *self.last_disk_ok.lock() = Some(Instant::now());
864                CapacityVerdict::Writable
865            }
866            CapacityVerdict::Unknown => CapacityVerdict::Unknown,
867            // Below the reserve is only half the predicate: the store may
868            // still hold pages it can reuse without growing the file.
869            CapacityVerdict::Full => match self.reusable_bytes() {
870                Ok(reusable) if reusable >= MAX_CHUNK_SIZE as u64 => CapacityVerdict::Writable,
871                Ok(_) => CapacityVerdict::Full,
872                Err(e) => {
873                    warn!("Could not query the store's reusable space: {e}");
874                    CapacityVerdict::Unknown
875                }
876            },
877        }
878    }
879
880    /// Estimated bytes inside `data.mdb` that LMDB could write without growing
881    /// the file: the file size minus the pages currently holding data.
882    ///
883    /// Deliberately an over-estimate. `stat()` counts only the branch, leaf and
884    /// overflow pages of the unnamed database, so the free-list's own pages and
885    /// the environment metadata fall on the "reusable" side. Erring high keeps
886    /// [`Self::check_capacity`] biased towards admitting the attempt.
887    ///
888    /// Uses `stat()` rather than heed's `non_free_pages_size()`, which walks the
889    /// unnamed database calling `String::from_utf8(key).unwrap()` on every key
890    /// without a zero byte. Our keys are 32 random bytes, so that call panics
891    /// almost immediately. A single unnamed database makes `stat()` equivalent.
892    fn reusable_bytes(&self) -> Result<u64> {
893        // Order matters. The two samples are not atomic, so read the live pages
894        // first and the file length second: a write committing in between then
895        // pairs an older (smaller) live count with a newer (larger) file, which
896        // over-estimates. Sampling the other way round pairs a stale file
897        // length with a fresh live count and can under-estimate, which would
898        // refuse a node that has room — the very bug this fixes.
899        let stat = self.env.stat();
900        let live_pages = (stat.branch_pages as u64)
901            .saturating_add(stat.leaf_pages as u64)
902            .saturating_add(stat.overflow_pages as u64);
903        let live_bytes = live_pages.saturating_mul(u64::from(stat.page_size));
904
905        let file_bytes = self
906            .env
907            .real_disk_size()
908            .map_err(|e| Error::Storage(format!("Failed to query LMDB file size: {e}")))?;
909
910        Ok(file_bytes.saturating_sub(live_bytes))
911    }
912
913    /// Available bytes on the storage volume, or `None` when a recent check
914    /// already showed it above the reserve.
915    ///
916    /// Only *passing* results are cached, so a low-space condition is always
917    /// re-measured and freed space is detected promptly.
918    fn available_space_cached(&self) -> Result<Option<u64>> {
919        {
920            let last = self.last_disk_ok.lock();
921            if let Some(t) = *last {
922                if t.elapsed().as_secs() < DISK_CHECK_INTERVAL_SECS {
923                    return Ok(None);
924                }
925            }
926        }
927
928        let available = fs2::available_space(&self.env_dir)
929            .map_err(|e| Error::Storage(format!("Failed to query available disk space: {e}")))?;
930
931        if available >= self.config.disk_reserve {
932            *self.last_disk_ok.lock() = Some(Instant::now());
933            return Ok(None);
934        }
935
936        Ok(Some(available))
937    }
938
939    /// Align the map ceiling with the current disk state, returning whether the
940    /// store is in no-growth mode.
941    ///
942    /// Below the reserve the map is pinned to the file's high-water mark, so a
943    /// put succeeds exactly when LMDB can satisfy it from the free list and
944    /// returns `MapFull` the moment it would need to extend `data.mdb`. That
945    /// makes the allocator the authority on "can this write fit".
946    ///
947    /// The whole transition runs under `growth_mode_lock`. Setting the flag and
948    /// resizing the map is one compound change spanning an await, so without
949    /// serialisation two callers straddling the threshold can interleave and
950    /// leave the flag describing a map that was never applied.
951    async fn sync_growth_mode(&self) -> Result<bool> {
952        let _transition = self.growth_mode_lock.lock().await;
953
954        // Re-measured inside the lock: a caller that queued behind a transition
955        // must act on the state that transition left behind, not the one it saw
956        // before waiting.
957        // Pinned for the bridge: never unpinned by having room, because the room is not
958        // this environment's to spend while another store is measuring the same disk.
959        if self.growth_pinned.load(Ordering::Acquire) {
960            self.no_growth.store(true, Ordering::Release);
961            self.pin_map_to_high_water().await?;
962            return Ok(true);
963        }
964        if self.available_space_cached()?.is_none() {
965            // At or above the reserve: restore normal head-room if we pinned it.
966            if self.no_growth.load(Ordering::Acquire) {
967                // Intent first, work second. A `spawn_blocking` body outlives a
968                // cancelled awaiter, so ordering between two resizes cannot be
969                // guaranteed by holding an async lock. Publishing the intent
970                // before the work lets each closure re-read it under the
971                // exclusive lock and decline if it has since been reversed.
972                self.no_growth.store(false, Ordering::Release);
973                self.try_resize().await?;
974            }
975            // Real disk again: the maintenance allowance is refreshed. Done on
976            // every healthy pass, not just the transition, so an allowance
977            // spent while the flag happened to be clear is still returned.
978            self.delete_growth_charged.store(0, Ordering::Release);
979            return Ok(false);
980        }
981
982        // Called unconditionally, not just on the transition. A re-pin that
983        // failed, or a transition whose caller was cancelled while its detached
984        // resize was still in flight, can leave the flag set while the map is
985        // not actually pinned; re-asserting it here repairs that instead of
986        // trusting the flag. The call is a no-op when already pinned.
987        self.no_growth.store(true, Ordering::Release);
988        self.pin_map_to_high_water().await?;
989
990        Ok(true)
991    }
992
993    /// Keep this environment from ever claiming new disk, until the process ends.
994    ///
995    /// For the migration bridge, where a second store measures the same free space and
996    /// neither knows what the other is about to spend. Pinned, this one writes only from
997    /// pages it already holds, so the other's accounting is the only claim on free disk.
998    ///
999    /// # Errors
1000    ///
1001    /// Returns [`Error::Storage`] if the map cannot be pinned.
1002    pub async fn pin_growth(&self) -> Result<()> {
1003        self.growth_pinned.store(true, Ordering::Release);
1004        self.sync_growth_mode().await.map(|_| ())
1005    }
1006
1007    /// Pin the LMDB map to the size of `data.mdb` on disk.
1008    ///
1009    /// Every page already in the file stays usable, including free ones, but
1010    /// the file cannot grow, so the configured reserve is preserved by LMDB
1011    /// itself rather than by refusing writes it could have served.
1012    ///
1013    /// Deliberately leaves **no** head-room: any slack in the ceiling is
1014    /// ordinary put capacity, so it would be spent on the next chunk rather
1015    /// than kept for maintenance, and on a shared volume every node would take
1016    /// its own slice out of the reserve. Deletes get their copy-on-write room
1017    /// on demand instead, see [`Self::delete`].
1018    ///
1019    /// Takes the **exclusive** `env_lock` for the same reason
1020    /// [`Self::try_resize`] does: `mdb_env_set_mapsize` requires that no
1021    /// transaction is active. Callers hold `growth_mode_lock`.
1022    #[allow(unsafe_code)]
1023    async fn pin_map_to_high_water(&self) -> Result<()> {
1024        // The "is it already pinned?" test lives inside the exclusive lock
1025        // below, not out here. An unlocked pre-check can observe "already
1026        // pinned" moments before a detached resize from a cancelled transition
1027        // lands, after which the flag would claim a pin that no longer holds.
1028        // Callers invoke this on every low-disk write so the pinned state
1029        // repairs itself; the locked section is a few reads when nothing is to
1030        // be done.
1031        let env = self.env.clone();
1032        let lock = Arc::clone(&self.env_lock);
1033        let no_growth = Arc::clone(&self.no_growth);
1034
1035        self.blocking_tracker
1036            .spawn_blocking(move || -> Result<()> {
1037                // Exclusive lock guarantees no concurrent transactions.
1038                let _guard = lock.write();
1039
1040                // Re-read under the lock: this closure may have been queued
1041                // behind others, or its awaiter cancelled, and the store may
1042                // have left no-growth mode since it was spawned.
1043                if !no_growth.load(Ordering::Acquire) {
1044                    return Ok(());
1045                }
1046
1047                let current_map = env.info().map_size;
1048                let file_bytes = env
1049                    .real_disk_size()
1050                    .map_err(|e| Error::Storage(format!("Failed to query LMDB file size: {e}")))?;
1051
1052                let page = page_size::get() as u64;
1053                let aligned = file_bytes.div_ceil(page) * page;
1054                let target = usize::try_from(aligned).unwrap_or(usize::MAX);
1055
1056                // Re-checked under the lock: the state may have moved between
1057                // the cheap check and here.
1058                if target >= current_map {
1059                    return Ok(());
1060                }
1061
1062                // SAFETY: We hold an exclusive lock, so no transactions are active.
1063                unsafe {
1064                    env.resize(target)
1065                        .map_err(|e| Error::Storage(format!("Failed to pin LMDB map: {e}")))?;
1066                }
1067
1068                info!(
1069                    "Disk below reserve: pinned LMDB map to {:.2} GiB (was {:.2} GiB). \
1070                     Writes that fit in already-freed pages still succeed; \
1071                     only writes that would grow the file are refused.",
1072                    bytes_to_gib(target as u64),
1073                    bytes_to_gib(current_map as u64),
1074                );
1075                Ok(())
1076            })
1077            .await
1078            .map_err(|e| Error::Storage(format!("LMDB map pin task failed: {e}")))?
1079    }
1080
1081    /// Grow the map for a write, unless the store is pinned below the reserve.
1082    ///
1083    /// Serialised against [`Self::sync_growth_mode`] so a resize cannot land
1084    /// after a pin and quietly undo it. If the store entered no-growth mode
1085    /// while the write was in flight, the caller's `MapFull` is final and no
1086    /// growth happens.
1087    async fn try_resize_for_growth(&self) -> Result<()> {
1088        let _transition = self.growth_mode_lock.lock().await;
1089
1090        if self.no_growth.load(Ordering::Acquire) {
1091            return Ok(());
1092        }
1093
1094        self.try_resize().await
1095    }
1096
1097    /// Delete `key` with [`DELETE_COW_SLACK`] of temporary map head-room, then
1098    /// take the head-room straight back.
1099    ///
1100    /// The raise, the delete and the re-pin all happen inside **one** exclusive
1101    /// `env_lock` scope. Doing them as three separate locked steps would leave
1102    /// windows in which an ordinary put could allocate from the raised ceiling,
1103    /// spending the reserve on a chunk instead of on the maintenance it was
1104    /// granted for, and an error or cancellation between the steps would leave
1105    /// the ceiling raised for good.
1106    ///
1107    /// What is budgeted is the *growth*, not the grant. If the copy-on-write
1108    /// does extend `data.mdb` that growth is permanent, since LMDB never
1109    /// returns file space, so repeated fill-then-delete cycles could otherwise
1110    /// walk the file into the reserve a slice at a time. A delete that finds
1111    /// room inside the file is charged nothing.
1112    ///
1113    /// Charging per grant instead would be wrong, and was: page reuse is not
1114    /// reliably available to the very next delete, because LMDB will not hand
1115    /// back pages a still-recent transaction freed. A one-grant budget
1116    /// therefore stopped a node pruning after its first assisted delete, which
1117    /// showed up as every delete failing on 4 KiB-page hosts while passing on
1118    /// 16 KiB-page ones. The budget resets when the store leaves no-growth
1119    /// mode, i.e. when there is real disk to work with again.
1120    #[allow(unsafe_code)]
1121    async fn delete_with_slack(&self, key: &XorName) -> Result<bool> {
1122        let key = *key;
1123        let env = self.env.clone();
1124        let db = self.db;
1125        let lock = Arc::clone(&self.env_lock);
1126        let budget = Arc::clone(&self.delete_growth_charged);
1127
1128        let outcome = self
1129            .blocking_tracker
1130            .spawn_blocking(move || -> Result<DeleteOutcome> {
1131                // Checked and charged entirely inside the closure. A
1132                // `spawn_blocking` body keeps running when its awaiter is
1133                // dropped, so accounting split across the await could be
1134                // skipped, permanently costing the node its ability to prune.
1135                if budget.load(Ordering::Acquire) >= DELETE_COW_GROWTH_BUDGET {
1136                    return Err(Error::Storage(format!(
1137                        "Cannot delete: the local store is full and deletes have already used \
1138                         their {DELETE_COW_GROWTH_BUDGET} B growth allowance. \
1139                         Free disk space to continue."
1140                    )));
1141                }
1142
1143                // Exclusive for the whole sequence: no transaction may be
1144                // active across either resize, and no put may observe the
1145                // raised ceiling.
1146                let _guard = lock.write();
1147
1148                let page = page_size::get() as u64;
1149                let previous_map = env.info().map_size;
1150                let file_before = env
1151                    .real_disk_size()
1152                    .map_err(|e| Error::Storage(format!("Failed to query LMDB file size: {e}")))?;
1153                let raised = (previous_map as u64)
1154                    .saturating_add(DELETE_COW_SLACK)
1155                    .div_ceil(page)
1156                    .saturating_mul(page);
1157
1158                // SAFETY: exclusive lock held, so no transactions are active.
1159                let granted = unsafe {
1160                    env.resize(usize::try_from(raised).unwrap_or(usize::MAX))
1161                        .map_err(|e| Error::Storage(format!("Failed to grant delete slack: {e}")))
1162                };
1163                granted?;
1164
1165                // Armed across the delete so an unwind still restores the
1166                // ceiling; disarmed once the explicit restore below succeeds.
1167                let mut ceiling_guard = MapCeilingRestorer {
1168                    env: &env,
1169                    previous: previous_map,
1170                    armed: true,
1171                };
1172
1173                let outcome = delete_in_txn(&env, db, &key);
1174
1175                // Charge what the file actually gained, not the fact that slack
1176                // was offered. A delete that found room inside `data.mdb` costs
1177                // nothing and must not consume the allowance, otherwise a node
1178                // stops being able to prune after its first assisted delete.
1179                // Measured before the ceiling is restored, and before any error
1180                // is propagated, so a committed delete is always accounted for.
1181                //
1182                // A measurement that fails is charged the whole slack rather than nothing.
1183                // Reading it back as the size before the delete would say the file did not
1184                // grow, and a delete that did grow would then spend disk the budget never
1185                // saw. Repeat that and the ceiling stops meaning anything. Over-charging
1186                // costs at worst one assisted delete; under-charging costs the reserve.
1187                let grew = match env.real_disk_size() {
1188                    Ok(file_after) => file_after.saturating_sub(file_before),
1189                    Err(e) => {
1190                        warn!(
1191                            "Could not measure the LMDB file after an assisted delete \
1192                             ({e}); charging the whole slack rather than assuming it cost \
1193                             nothing"
1194                        );
1195                        DELETE_COW_SLACK
1196                    }
1197                };
1198                if grew > 0 {
1199                    budget.fetch_add(grew, Ordering::AcqRel);
1200                }
1201
1202                // Undo the raise before releasing the lock, on every path and
1203                // whatever the delete did. Restoring to the previous ceiling
1204                // rather than to a freshly measured file size keeps this
1205                // unconditional: it is exactly the inverse of the raise, needs
1206                // no second syscall that could itself fail, and is correct
1207                // whether or not the store was pinned. If the copy-on-write did
1208                // extend the file, LMDB clamps a request below the space in use,
1209                // so the map still covers the data.
1210                //
1211                // SAFETY: exclusive lock held, so no transactions are active.
1212                let restored = unsafe {
1213                    env.resize(previous_map)
1214                        .map_err(|e| Error::Storage(format!("Failed to restore LMDB map: {e}")))
1215                };
1216                if restored.is_ok() {
1217                    ceiling_guard.armed = false;
1218                }
1219
1220                // A failed restore is reported ahead of a failed delete, so the
1221                // failure is not lost behind the delete's own error.
1222                match (outcome, restored) {
1223                    (Ok(outcome), Ok(())) => Ok(outcome),
1224                    (_, Err(e)) | (Err(e), Ok(())) => Err(e),
1225                }
1226            })
1227            .await
1228            .map_err(|e| Error::Storage(format!("LMDB delete-slack task failed: {e}")))?;
1229
1230        match outcome? {
1231            DeleteOutcome::Done(existed) => Ok(existed),
1232            DeleteOutcome::MapFull => Err(Error::Storage(
1233                "LMDB map full during delete even with the maintenance allowance".into(),
1234            )),
1235        }
1236    }
1237
1238    /// Grow the LMDB map to match currently available disk space.
1239    ///
1240    /// The new size is the **larger** of:
1241    ///   1. the current map size (so existing data is never truncated), and
1242    ///   2. `current_db_file_size + available_space − reserve`
1243    ///      (so all reachable disk space can be used).
1244    ///
1245    /// Acquires an **exclusive** lock on `env_lock` so that no read or write
1246    /// transactions are active when the underlying `mdb_env_set_mapsize` is
1247    /// called (an LMDB safety requirement).
1248    #[allow(unsafe_code)]
1249    async fn try_resize(&self) -> Result<()> {
1250        let env = self.env.clone();
1251        let lock = Arc::clone(&self.env_lock);
1252        let no_growth = Arc::clone(&self.no_growth);
1253        let env_dir = self.env_dir.clone();
1254        let reserve = self.config.disk_reserve;
1255
1256        self.blocking_tracker
1257            .spawn_blocking(move || -> Result<()> {
1258                // Exclusive lock guarantees no concurrent transactions.
1259                let _guard = lock.write();
1260
1261                // Re-read under the lock. A `spawn_blocking` body outlives a
1262                // cancelled awaiter, so this closure may land after the store
1263                // entered no-growth mode. Growing then would hand back the
1264                // head-room a pin had just taken away, and with it the disk
1265                // reserve.
1266                if no_growth.load(Ordering::Acquire) {
1267                    return Ok(());
1268                }
1269
1270                // Measured here rather than before the spawn, so a late closure
1271                // sizes from the disk as it is now, not as it was when queued.
1272                let from_disk = compute_map_size(&env_dir, reserve)?;
1273
1274                // Never shrink below the current map — existing data must remain
1275                // addressable regardless of what the disk-space calculation says.
1276                let current_map = env.info().map_size;
1277                let new_size = from_disk.max(current_map);
1278
1279                if new_size <= current_map {
1280                    debug!("LMDB map resize skipped — no additional disk space available");
1281                    return Ok(());
1282                }
1283
1284                // SAFETY: We hold an exclusive lock, so no transactions are active.
1285                unsafe {
1286                    env.resize(new_size)
1287                        .map_err(|e| Error::Storage(format!("Failed to resize LMDB map: {e}")))?;
1288                }
1289
1290                info!(
1291                    "Resized LMDB map to {:.2} GiB (was {:.2} GiB)",
1292                    bytes_to_gib(new_size as u64),
1293                    bytes_to_gib(current_map as u64),
1294                );
1295                Ok(())
1296            })
1297            .await
1298            .map_err(|e| Error::Storage(format!("LMDB resize task failed: {e}")))?
1299    }
1300
1301    /// Wait until every tracked LMDB blocking task has finished.
1302    ///
1303    /// Dropping an async caller (e.g. a `select!` losing to a shutdown token)
1304    /// does not cancel an already-spawned blocking closure — the closure keeps
1305    /// running on the blocking pool with a cloned [`Env`].  This method waits
1306    /// for those detached closures too, so when it returns no blocking
1307    /// operation still holds the environment.
1308    ///
1309    /// Quiescence is only meaningful once callers have stopped issuing new
1310    /// operations; concurrent traffic can keep the tracker non-empty
1311    /// indefinitely.  The storage remains fully usable afterwards (the
1312    /// internal tracker is reopened before returning).
1313    pub async fn wait_idle(&self) {
1314        self.blocking_tracker.close();
1315        self.blocking_tracker.wait().await;
1316        self.blocking_tracker.reopen();
1317    }
1318
1319    /// Test-only handle to the put gate.
1320    ///
1321    /// Hold the write half to deterministically park the next put inside its
1322    /// blocking closure (e.g. to exercise [`Self::wait_idle`] with a write
1323    /// still in flight).
1324    #[cfg(any(test, feature = "test-utils"))]
1325    #[must_use]
1326    pub fn test_put_gate(&self) -> Arc<parking_lot::RwLock<()>> {
1327        Arc::clone(&self.test_put_gate)
1328    }
1329
1330    /// Test-only handle to the raw-read gate.
1331    ///
1332    /// Hold the write half to deterministically park the next raw read
1333    /// (`get_raw`) inside its blocking closure while it still holds the shared
1334    /// environment lock (e.g. to prove `try_resize` waits for active
1335    /// raw reads).
1336    #[cfg(any(test, feature = "test-utils"))]
1337    #[must_use]
1338    pub fn test_read_gate(&self) -> Arc<parking_lot::RwLock<()>> {
1339        Arc::clone(&self.test_read_gate)
1340    }
1341}
1342
1343// ────────────────────────────────────────────────────────────────────────────
1344// Helpers
1345// ────────────────────────────────────────────────────────────────────────────
1346
1347/// Outcome of a single `try_put` attempt.
1348enum PutOutcome {
1349    /// Chunk was newly stored.
1350    New,
1351    /// Chunk already existed (idempotent).
1352    Duplicate,
1353    /// The LMDB map ceiling was reached — caller should resize and retry.
1354    MapFull,
1355}
1356
1357/// Restores an LMDB map ceiling when dropped, including while unwinding.
1358///
1359/// The explicit restore in [`LmdbStorage::delete_with_slack`] is the normal
1360/// path, because it can report a failure to the caller. This exists so a panic
1361/// between the raise and that restore cannot leave the ceiling raised, which
1362/// would quietly hand ordinary writes the disk reserve.
1363struct MapCeilingRestorer<'a> {
1364    env: &'a Env,
1365    previous: usize,
1366    armed: bool,
1367}
1368
1369impl Drop for MapCeilingRestorer<'_> {
1370    #[allow(unsafe_code)]
1371    fn drop(&mut self) {
1372        if !self.armed {
1373            return;
1374        }
1375        // SAFETY: the owner holds the exclusive `env_lock` for this whole
1376        // scope, so no transaction is active.
1377        unsafe {
1378            if let Err(e) = self.env.resize(self.previous) {
1379                warn!("Failed to restore the LMDB map ceiling while unwinding: {e}");
1380            }
1381        }
1382    }
1383}
1384
1385/// Run one delete in its own write transaction, reporting `MapFull` rather than
1386/// raising it.
1387///
1388/// The caller owns the `env_lock` discipline: [`LmdbStorage::try_delete`] holds
1389/// the shared guard, [`LmdbStorage::delete_with_slack`] the exclusive one.
1390fn delete_in_txn(env: &Env, db: Database<Bytes, Bytes>, key: &XorName) -> Result<DeleteOutcome> {
1391    let mut wtxn = match env.write_txn() {
1392        Ok(wtxn) => wtxn,
1393        Err(heed::Error::Mdb(MdbError::MapFull)) => return Ok(DeleteOutcome::MapFull),
1394        Err(e) => return Err(Error::Storage(format!("Failed to create write txn: {e}"))),
1395    };
1396    let existed = match db.delete(&mut wtxn, key) {
1397        Ok(existed) => existed,
1398        Err(heed::Error::Mdb(MdbError::MapFull)) => return Ok(DeleteOutcome::MapFull),
1399        Err(e) => return Err(Error::Storage(format!("Failed to delete chunk: {e}"))),
1400    };
1401    match wtxn.commit() {
1402        Ok(()) => Ok(DeleteOutcome::Done(existed)),
1403        Err(heed::Error::Mdb(MdbError::MapFull)) => Ok(DeleteOutcome::MapFull),
1404        Err(e) => Err(Error::Storage(format!("Failed to commit delete: {e}"))),
1405    }
1406}
1407
1408/// Outcome of one delete attempt.
1409enum DeleteOutcome {
1410    /// The delete committed; the flag is whether the key had existed.
1411    Done(bool),
1412    /// The map ceiling left no room for the delete's copy-on-write.
1413    MapFull,
1414}
1415
1416/// Compute the LMDB map size from the disk hosting `db_dir`.
1417///
1418/// The result covers **all existing data** plus all remaining usable disk
1419/// space:
1420///
1421/// ```text
1422/// map_size = current_db_file_size + max(0, available_space − reserve)
1423/// ```
1424///
1425/// `available_space` (from `statvfs`) reports only the *free* bytes on the
1426/// partition — the DB file's own footprint is **not** included, so adding
1427/// it back ensures the map is always large enough for the data already
1428/// stored.
1429///
1430/// On Windows the disk-headroom term is additionally capped at
1431/// `WINDOWS_MAP_HEADROOM` to bound the map-proportional commit overhead (see
1432/// that constant); [`LmdbStorage::try_resize`] extends the map on demand as
1433/// data grows.
1434///
1435/// The result is page-aligned and never falls below [`MIN_MAP_SIZE`].
1436fn compute_map_size(db_dir: &Path, reserve: u64) -> Result<usize> {
1437    let available = fs2::available_space(db_dir)
1438        .map_err(|e| Error::Storage(format!("Failed to query available disk space: {e}")))?;
1439
1440    // The MDB data file may not exist yet on first run, and that is the only reason to
1441    // read zero here. Any other failure is a question that was not answered, and answering
1442    // it with zero sizes the map as though the database were empty, which on a node with a
1443    // large one is a map far too small to open it.
1444    let mdb_file = db_dir.join("data.mdb");
1445    let current_db_bytes = match std::fs::metadata(&mdb_file) {
1446        Ok(meta) => meta.len(),
1447        Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
1448        Err(e) => {
1449            return Err(Error::Storage(format!(
1450                "Failed to measure {}: {e}. Refusing to size the map as though it were \
1451                 empty.",
1452                mdb_file.display()
1453            )))
1454        }
1455    };
1456
1457    let target = map_target_bytes(current_db_bytes, available, reserve);
1458
1459    // Align up to system page size (required by heed's resize).
1460    let page = page_size::get() as u64;
1461    let aligned = target.div_ceil(page) * page;
1462
1463    let result = usize::try_from(aligned).unwrap_or(usize::MAX);
1464    Ok(result.max(MIN_MAP_SIZE))
1465}
1466
1467/// Head-room policy for the LMDB map, split out from [`compute_map_size`] so it
1468/// is unit-testable without touching the real filesystem.
1469///
1470/// `map = current_db_bytes + max(0, available − reserve)`, with the head-room
1471/// term capped at `WINDOWS_MAP_HEADROOM` on Windows. Existing data
1472/// (`current_db_bytes`) is always covered so a resize can never truncate the
1473/// database, even when the head-room cap or a nearly-full disk drives the
1474/// growth term to zero.
1475fn map_target_bytes(current_db_bytes: u64, available: u64, reserve: u64) -> u64 {
1476    // available_space excludes the DB file, so we add it back to get the
1477    // total space the DB could occupy while still leaving `reserve` free.
1478    let growth_room = available.saturating_sub(reserve);
1479
1480    // On Windows, bound the head-room so the mapped size (and its
1481    // size-proportional commit overhead) stays proportional to stored data
1482    // rather than disk capacity. Elsewhere, use all reachable space.
1483    #[cfg(windows)]
1484    let growth_room = growth_room.min(WINDOWS_MAP_HEADROOM);
1485
1486    current_db_bytes.saturating_add(growth_room)
1487}
1488
1489/// Map the result of a space query onto the *disk half* of the capacity
1490/// verdict.
1491///
1492/// `Full` here means "below the reserve", which since ant-node #210 is only
1493/// half the refusal predicate: [`LmdbStorage::capacity_verdict`] goes on to
1494/// consult the store's reusable pages before refusing.
1495///
1496/// Split out from [`LmdbStorage::capacity_verdict`] because the three-way
1497/// mapping is the part worth proving, and proving it through the filesystem is
1498/// not portable: asking for the free space of a directory that does not exist
1499/// fails on Unix but succeeds on Windows, which resolves it to the volume.
1500fn verdict_from_available_space(available: std::io::Result<u64>, reserve: u64) -> CapacityVerdict {
1501    match available {
1502        Ok(available) if available < reserve => CapacityVerdict::Full,
1503        Ok(_) => CapacityVerdict::Writable,
1504        Err(e) => {
1505            warn!("Could not query available disk space: {e}");
1506            CapacityVerdict::Unknown
1507        }
1508    }
1509}
1510
1511/// What a capacity check concluded, when the caller needs to tell "this node is
1512/// full" apart from "this node could not find out".
1513///
1514/// [`LmdbStorage::check_capacity`] collapses both into `Err`, which is right for
1515/// a caller that only wants to know whether to attempt a write. A caller
1516/// deciding *how long to stand down* needs the distinction: a full disk is a
1517/// standing condition worth waiting minutes on, while a failed `statvfs` may
1518/// have cleared by the next attempt and must not be treated as one.
1519#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1520pub enum CapacityVerdict {
1521    /// Available space is at or above the configured reserve. That is what the
1522    /// query establishes, and possibly from the TTL cache — not a promise the
1523    /// next write succeeds.
1524    Writable,
1525    /// Available space is below the configured reserve.
1526    Full,
1527    /// The query itself failed, so nothing is known about available space.
1528    Unknown,
1529}
1530
1531#[cfg(test)]
1532#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1533mod tests {
1534    use super::*;
1535    use crate::ant_protocol::MAX_CHUNK_SIZE;
1536
1537    /// Short probe used to prove `wait_idle` is still blocked on a parked op.
1538    const WAIT_IDLE_BLOCKED_PROBE: std::time::Duration = std::time::Duration::from_millis(200);
1539    /// Generous ceiling for `wait_idle` to complete once the op is released.
1540    const WAIT_IDLE_COMPLETE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1541    /// Poll interval while waiting for a parked raw read to take the shared lock.
1542    const RAW_READ_LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(5);
1543    /// Ceiling for a parked raw read to take the shared lock.
1544    const RAW_READ_LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
1545    /// Short probe used to prove `try_resize` is still blocked on the shared lock.
1546    const RESIZE_BLOCKED_PROBE: std::time::Duration = std::time::Duration::from_millis(200);
1547    /// Generous ceiling for `try_resize` to complete once the raw read releases.
1548    const RESIZE_COMPLETE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1549
1550    #[test]
1551    fn map_target_covers_existing_data_and_headroom() {
1552        // A partition with far more free space than any node needs.
1553        let huge_free = 100 * 1024 * GIB; // 100 TiB
1554        let reserve = 500 * MIB;
1555
1556        // Fresh node, no data yet.
1557        let fresh = map_target_bytes(0, huge_free, reserve);
1558        // Node already holding 16 GiB of chunks.
1559        let with_data = map_target_bytes(16 * GIB, huge_free, reserve);
1560
1561        #[cfg(windows)]
1562        {
1563            // Windows: head-room is capped, so the map (and thus page tables)
1564            // stay bounded regardless of disk size. Existing data always sits
1565            // on top of the capped head-room.
1566            assert_eq!(fresh, WINDOWS_MAP_HEADROOM);
1567            assert_eq!(with_data, 16 * GIB + WINDOWS_MAP_HEADROOM);
1568            // Sanity: page-table cost (~map/512) is tens of MiB, not tens of GiB.
1569            assert!(with_data / 512 < 128 * MIB);
1570        }
1571
1572        #[cfg(not(windows))]
1573        {
1574            // Other platforms keep the disk-sized map (lazy page tables cost
1575            // nothing), so head-room is the full free span minus reserve.
1576            assert_eq!(fresh, huge_free - reserve);
1577            assert_eq!(with_data, 16 * GIB + (huge_free - reserve));
1578        }
1579    }
1580
1581    #[test]
1582    fn map_target_never_truncates_data_when_disk_nearly_full() {
1583        // Free space below the reserve → head-room saturates to 0 on every
1584        // platform, but the existing 4 GiB of data must still be covered.
1585        assert_eq!(map_target_bytes(4 * GIB, 100 * MIB, 500 * MIB), 4 * GIB);
1586    }
1587
1588    /// Regression (V2-620 review): `all_keys` and `get_raw` must take the shared
1589    /// `env_lock` so their LMDB read transaction can never run concurrently with
1590    /// `try_resize()`'s unsafe `Env::resize()` — which this PR turns into a
1591    /// routine ~per-32-GiB Windows event. We prove it by holding the exclusive
1592    /// lock (as a resize does) and asserting both calls block until it is freed.
1593    ///
1594    /// Holding a `parking_lot` guard across `.await` is deliberate and safe here:
1595    /// the guard stays on this current-thread test task while `all_keys`/`get_raw`
1596    /// run their blocking work on the `spawn_blocking` pool (separate threads).
1597    #[tokio::test]
1598    #[allow(clippy::await_holding_lock)]
1599    async fn read_paths_block_while_env_is_being_resized() {
1600        use std::time::Duration;
1601        let (storage, _temp) = create_test_storage().await;
1602
1603        // Store one chunk so the read paths have real work to return.
1604        let content = b"resize-safety";
1605        let address = LmdbStorage::compute_address(content);
1606        storage.put(&address, content).await.expect("put");
1607
1608        // Simulate a resize in progress: hold the exclusive env lock.
1609        let write_guard = storage.env_lock.write();
1610
1611        // Neither read path may complete while the exclusive lock is held —
1612        // before the fix they took no lock and would return immediately.
1613        assert!(
1614            tokio::time::timeout(Duration::from_millis(250), storage.all_keys())
1615                .await
1616                .is_err(),
1617            "all_keys completed while env_lock was held exclusively — missing shared guard"
1618        );
1619        assert!(
1620            tokio::time::timeout(Duration::from_millis(250), storage.get_raw(&address))
1621                .await
1622                .is_err(),
1623            "get_raw completed while env_lock was held exclusively — missing shared guard"
1624        );
1625
1626        // Once the exclusive lock is released, both proceed and see the data.
1627        drop(write_guard);
1628        assert_eq!(storage.all_keys().await.expect("all_keys").len(), 1);
1629        assert_eq!(
1630            storage.get_raw(&address).await.expect("get_raw").as_deref(),
1631            Some(content.as_slice())
1632        );
1633    }
1634
1635    async fn create_test_storage() -> (LmdbStorage, tempfile::TempDir) {
1636        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
1637        let config = LmdbStorageConfig {
1638            root_dir: temp_dir.path().to_path_buf(),
1639            ..LmdbStorageConfig::test_default()
1640        };
1641        let storage = LmdbStorage::new(config).await.expect("create storage");
1642        (storage, temp_dir)
1643    }
1644
1645    #[tokio::test]
1646    async fn test_put_and_get() {
1647        let (storage, _temp) = create_test_storage().await;
1648
1649        let content = b"hello world";
1650        let address = LmdbStorage::compute_address(content);
1651
1652        // Store chunk
1653        let is_new = storage.put(&address, content).await.expect("put");
1654        assert!(is_new);
1655
1656        // Retrieve chunk
1657        let retrieved = storage.get(&address).await.expect("get");
1658        assert_eq!(retrieved, Some(content.to_vec()));
1659    }
1660
1661    #[tokio::test]
1662    async fn test_put_duplicate() {
1663        let (storage, _temp) = create_test_storage().await;
1664
1665        let content = b"test data";
1666        let address = LmdbStorage::compute_address(content);
1667
1668        // First store
1669        let is_new1 = storage.put(&address, content).await.expect("put 1");
1670        assert!(is_new1);
1671
1672        // Duplicate store
1673        let is_new2 = storage.put(&address, content).await.expect("put 2");
1674        assert!(!is_new2);
1675
1676        // Check stats
1677        let stats = storage.stats();
1678        assert_eq!(stats.chunks_stored, 1);
1679        assert_eq!(stats.duplicates, 1);
1680    }
1681
1682    #[tokio::test]
1683    async fn test_get_not_found() {
1684        let (storage, _temp) = create_test_storage().await;
1685
1686        let address = [0xAB; 32];
1687        let result = storage.get(&address).await.expect("get");
1688        assert!(result.is_none());
1689    }
1690
1691    #[tokio::test]
1692    async fn test_exists() {
1693        let (storage, _temp) = create_test_storage().await;
1694
1695        let content = b"exists test";
1696        let address = LmdbStorage::compute_address(content);
1697
1698        assert!(!storage.exists(&address).expect("exists"));
1699
1700        storage.put(&address, content).await.expect("put");
1701
1702        assert!(storage.exists(&address).expect("exists"));
1703    }
1704
1705    #[tokio::test]
1706    async fn test_delete() {
1707        let (storage, _temp) = create_test_storage().await;
1708
1709        let content = b"delete test";
1710        let address = LmdbStorage::compute_address(content);
1711
1712        // Store
1713        storage.put(&address, content).await.expect("put");
1714        assert!(storage.exists(&address).expect("exists"));
1715
1716        // Delete
1717        let deleted = storage.delete(&address).await.expect("delete");
1718        assert!(deleted);
1719        assert!(!storage.exists(&address).expect("exists"));
1720
1721        // Delete again (already deleted)
1722        let deleted2 = storage.delete(&address).await.expect("delete 2");
1723        assert!(!deleted2);
1724    }
1725
1726    #[tokio::test]
1727    async fn test_address_mismatch() {
1728        let (storage, _temp) = create_test_storage().await;
1729
1730        let content = b"some content";
1731        let wrong_address = [0xFF; 32]; // Wrong address
1732
1733        let result = storage.put(&wrong_address, content).await;
1734        assert!(result.is_err());
1735        assert!(result.unwrap_err().to_string().contains("mismatch"));
1736    }
1737
1738    #[test]
1739    fn test_compute_address() {
1740        // Known BLAKE3 hash of "hello world"
1741        let content = b"hello world";
1742        let address = LmdbStorage::compute_address(content);
1743
1744        let expected_hex = "d74981efa70a0c880b8d8c1985d075dbcbf679b99a5f9914e5aaf96b831a9e24";
1745        assert_eq!(hex::encode(address), expected_hex);
1746    }
1747
1748    #[tokio::test]
1749    async fn test_stats() {
1750        let (storage, _temp) = create_test_storage().await;
1751
1752        let content1 = b"content 1";
1753        let content2 = b"content 2";
1754        let address1 = LmdbStorage::compute_address(content1);
1755        let address2 = LmdbStorage::compute_address(content2);
1756
1757        // Store two chunks
1758        storage.put(&address1, content1).await.expect("put 1");
1759        storage.put(&address2, content2).await.expect("put 2");
1760
1761        // Retrieve one
1762        storage.get(&address1).await.expect("get");
1763
1764        let stats = storage.stats();
1765        assert_eq!(stats.chunks_stored, 2);
1766        assert_eq!(stats.chunks_retrieved, 1);
1767        assert_eq!(
1768            stats.bytes_stored,
1769            content1.len() as u64 + content2.len() as u64
1770        );
1771        assert_eq!(stats.bytes_retrieved, content1.len() as u64);
1772        assert_eq!(stats.current_chunks, 2);
1773    }
1774
1775    #[tokio::test]
1776    async fn test_persistence_across_reopen() {
1777        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
1778        let content = b"persistent data";
1779        let address = LmdbStorage::compute_address(content);
1780
1781        // Store a chunk
1782        {
1783            let config = LmdbStorageConfig {
1784                root_dir: temp_dir.path().to_path_buf(),
1785                ..LmdbStorageConfig::test_default()
1786            };
1787            let storage = LmdbStorage::new(config).await.expect("create storage");
1788            storage.put(&address, content).await.expect("put");
1789        }
1790
1791        // Re-open and verify it persisted
1792        {
1793            let config = LmdbStorageConfig {
1794                root_dir: temp_dir.path().to_path_buf(),
1795                ..LmdbStorageConfig::test_default()
1796            };
1797            let storage = LmdbStorage::new(config).await.expect("reopen storage");
1798            assert_eq!(storage.current_chunks().expect("current_chunks"), 1);
1799            let retrieved = storage.get(&address).await.expect("get");
1800            assert_eq!(retrieved, Some(content.to_vec()));
1801        }
1802    }
1803
1804    #[tokio::test]
1805    async fn test_all_keys() {
1806        let (storage, _temp) = create_test_storage().await;
1807
1808        // Empty storage
1809        let keys = storage.all_keys().await.expect("all_keys empty");
1810        assert!(keys.is_empty());
1811
1812        // Store some chunks
1813        let content1 = b"chunk one for keys";
1814        let content2 = b"chunk two for keys";
1815        let addr1 = LmdbStorage::compute_address(content1);
1816        let addr2 = LmdbStorage::compute_address(content2);
1817        storage.put(&addr1, content1).await.expect("put 1");
1818        storage.put(&addr2, content2).await.expect("put 2");
1819
1820        let mut keys = storage.all_keys().await.expect("all_keys");
1821        keys.sort_unstable();
1822        let mut expected = vec![addr1, addr2];
1823        expected.sort_unstable();
1824        assert_eq!(keys, expected);
1825    }
1826
1827    #[tokio::test]
1828    async fn test_get_raw() {
1829        let (storage, _temp) = create_test_storage().await;
1830
1831        let content = b"raw test data";
1832        let address = LmdbStorage::compute_address(content);
1833        storage.put(&address, content).await.expect("put");
1834
1835        // get_raw returns bytes without verification
1836        let raw = storage.get_raw(&address).await.expect("get_raw");
1837        assert_eq!(raw, Some(content.to_vec()));
1838
1839        // Non-existent key
1840        let missing = storage.get_raw(&[0xFF; 32]).await.expect("get_raw missing");
1841        assert!(missing.is_none());
1842    }
1843
1844    /// Dropping a put's awaiter does not cancel its `spawn_blocking` LMDB
1845    /// transaction; `wait_idle` must wait for that detached write, and the
1846    /// storage must remain usable afterwards.
1847    // Holding the gate's write guard across awaits is the point of the test:
1848    // it parks the blocking closure while we probe wait_idle.
1849    #[allow(clippy::await_holding_lock)]
1850    #[tokio::test]
1851    async fn wait_idle_waits_for_detached_put_blocking_op() {
1852        let (storage, _temp) = create_test_storage().await;
1853
1854        let content = b"detached put survives its dropped awaiter";
1855        let address = LmdbStorage::compute_address(content);
1856
1857        // Park the put's blocking closure on the test gate.
1858        let gate = storage.test_put_gate();
1859        let parked = gate.write();
1860
1861        // Drop the awaiting future mid-flight: the biased select! polls the
1862        // put once — far enough to spawn the blocking task, which parks on
1863        // the gate — then completes on the ready branch, dropping the put.
1864        tokio::select! {
1865            biased;
1866            res = storage.put(&address, content) => {
1867                panic!("put must be parked on the test gate, got {res:?}")
1868            }
1869            () = std::future::ready(()) => {}
1870        }
1871
1872        // The blocking op is still running: wait_idle must not complete.
1873        let blocked = tokio::time::timeout(WAIT_IDLE_BLOCKED_PROBE, storage.wait_idle()).await;
1874        assert!(
1875            blocked.is_err(),
1876            "wait_idle returned while the blocking op was parked"
1877        );
1878
1879        // Release the gate: the detached closure commits and exits.
1880        drop(parked);
1881        tokio::time::timeout(WAIT_IDLE_COMPLETE_TIMEOUT, storage.wait_idle())
1882            .await
1883            .expect("wait_idle after release");
1884
1885        // The dropped awaiter did not lose the write: it committed.
1886        assert!(storage.exists(&address).expect("exists after release"));
1887
1888        // The storage remains usable after wait_idle (tracker reopened).
1889        let more = b"storage still usable after wait_idle";
1890        let more_addr = LmdbStorage::compute_address(more);
1891        assert!(storage
1892            .put(&more_addr, more)
1893            .await
1894            .expect("put after wait_idle"));
1895    }
1896
1897    /// A map resize takes the environment's *exclusive* lock, so it must wait
1898    /// for in-flight raw reads (which hold the *shared* lock) to finish before
1899    /// calling `env.resize()`. This proves `get_raw` holds that shared lock for
1900    /// the whole duration of its blocking closure; `all_keys` uses the same
1901    /// guard.
1902    // Holding the gate's write guard across awaits is the point of the test:
1903    // it parks the raw read's blocking closure while we probe try_resize.
1904    #[allow(clippy::await_holding_lock)]
1905    #[tokio::test]
1906    async fn resize_waits_for_in_flight_raw_read() {
1907        let (storage, _temp) = create_test_storage().await;
1908
1909        let content = b"raw read holds the shared env lock";
1910        let address = LmdbStorage::compute_address(content);
1911        storage.put(&address, content).await.expect("put");
1912
1913        // Park the raw read's blocking closure on the test gate. It acquires
1914        // the shared env_lock first, then parks here still holding it.
1915        let gate = storage.test_read_gate();
1916        let parked = gate.write();
1917
1918        // Drop the awaiting future mid-flight: the biased select! polls get_raw
1919        // once — far enough to spawn the blocking task, which takes the shared
1920        // lock and parks on the gate — then completes on the ready branch,
1921        // dropping the awaiter. The detached closure keeps holding the lock.
1922        tokio::select! {
1923            biased;
1924            res = storage.get_raw(&address) => {
1925                panic!("get_raw must be parked on the test gate, got {res:?}")
1926            }
1927            () = std::future::ready(()) => {}
1928        }
1929
1930        // Wait until the detached read has actually taken the shared lock,
1931        // signalled by the exclusive half no longer being immediately available.
1932        tokio::time::timeout(RAW_READ_LOCK_TIMEOUT, async {
1933            loop {
1934                let free = storage.env_lock.try_write().is_some();
1935                if !free {
1936                    break;
1937                }
1938                tokio::time::sleep(RAW_READ_LOCK_POLL).await;
1939            }
1940        })
1941        .await
1942        .expect("raw read did not take the shared env lock");
1943
1944        // A resize needs the exclusive lock, so it must block while the raw
1945        // read holds the shared lock.
1946        let resize = storage.try_resize();
1947        tokio::pin!(resize);
1948        let blocked = tokio::time::timeout(RESIZE_BLOCKED_PROBE, &mut resize).await;
1949        assert!(
1950            blocked.is_err(),
1951            "try_resize completed while a raw read held the shared env lock"
1952        );
1953
1954        // Release the read: it drops the shared lock, letting the resize take
1955        // the exclusive lock and finish.
1956        drop(parked);
1957        tokio::time::timeout(RESIZE_COMPLETE_TIMEOUT, &mut resize)
1958            .await
1959            .expect("try_resize did not complete after the raw read released")
1960            .expect("try_resize");
1961    }
1962
1963    /// The gate fires on `Full` and only on `Full`, so the verdict has to tell a
1964    /// disk below its reserve from one above it, and has to notice when that
1965    /// stops being true.
1966    ///
1967    /// The third call is the one that matters for recovery: the below-reserve
1968    /// condition clears, and the verdict has to follow it rather than stay stuck
1969    /// on its earlier answer. A node that remembered a refusal would stop
1970    /// fetching for good.
1971    ///
1972    /// What this does not show: that a changed free-space reading is re-read from
1973    /// the filesystem. The condition is cleared by dropping the reserve, which is
1974    /// the same comparison approached from the other side.
1975    #[tokio::test]
1976    async fn capacity_verdict_follows_the_reserve_and_notices_recovery() {
1977        let (writable, _temp) = create_test_storage().await;
1978        assert_eq!(writable.capacity_verdict(), CapacityVerdict::Writable);
1979
1980        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
1981        let config = LmdbStorageConfig {
1982            root_dir: temp_dir.path().to_path_buf(),
1983            // Far above any real free space, the same way the e2e builds a
1984            // write-blocked node.
1985            disk_reserve: u64::MAX / 2,
1986            ..LmdbStorageConfig::test_default()
1987        };
1988        let mut full = LmdbStorage::new(config).await.expect("create storage");
1989        assert_eq!(full.capacity_verdict(), CapacityVerdict::Full);
1990
1991        // Still short of space, so still `Full`. A `Full` result that populated
1992        // the passing-result cache would answer `Writable` here.
1993        assert_eq!(full.capacity_verdict(), CapacityVerdict::Full);
1994
1995        // Space is no longer short. Nothing cached a refusal, so the very next
1996        // read has to see it.
1997        full.config.disk_reserve = 0;
1998        assert_eq!(
1999            full.capacity_verdict(),
2000            CapacityVerdict::Writable,
2001            "a refusal must not be negatively cached: the next read has to see the \
2002             below-reserve condition clear"
2003        );
2004    }
2005
2006    /// A space query that fails says nothing about available space, so it must
2007    /// not read as a full disk. The gate stands a key down for five minutes on
2008    /// `Full` alone, and a failed `statvfs` is not a condition worth standing
2009    /// down for: it may be gone by the next cycle.
2010    ///
2011    /// The two `Ok` cases pin the boundary the reserve names: equal to the
2012    /// reserve is writable, one byte under it is not.
2013    ///
2014    /// What this does not show: that the gate leaves `Unknown` alone. The gate
2015    /// tests `== Full` on a separate line inside the verification cycle, which
2016    /// needs a network to reach, so this covers the classification only.
2017    #[test]
2018    fn a_failed_space_query_reads_as_unknown_not_full() {
2019        const RESERVE: u64 = 1024;
2020
2021        assert_eq!(
2022            verdict_from_available_space(Err(std::io::Error::other("space query failed")), RESERVE),
2023            CapacityVerdict::Unknown,
2024            "a failed query must not be reported as a full disk"
2025        );
2026
2027        assert_eq!(
2028            verdict_from_available_space(Ok(RESERVE - 1), RESERVE),
2029            CapacityVerdict::Full
2030        );
2031        assert_eq!(
2032            verdict_from_available_space(Ok(RESERVE), RESERVE),
2033            CapacityVerdict::Writable,
2034            "at the reserve is not below it"
2035        );
2036    }
2037
2038    /// The verdict and the pre-check have to refuse on the same condition.
2039    ///
2040    /// They are two readings of one question — can this node write? — and two
2041    /// callers depend on them separately: the verification cycle gates the
2042    /// close-group probe on the verdict, while `execute_single_fetch` gates the
2043    /// dial on the pre-check. A verdict stricter than the pre-check is the
2044    /// harmful direction. A node the pre-check would let write stops
2045    /// discovering holders for keys it could have stored, which is
2046    /// under-replication rather than a saved probe, and nothing else in the
2047    /// change would notice.
2048    ///
2049    /// This is a tripwire, deliberately built on the state where the two are
2050    /// about to part company rather than on a bare full disk. ant-node
2051    /// \#210 makes the pre-check a two-part predicate — below the reserve *and*
2052    /// out of reusable pages inside the store — and a store that has deleted
2053    /// more than one chunk's worth of pages fails only the first half, because
2054    /// LMDB returns those pages to its own free list and never to the
2055    /// filesystem. On a bare full disk the two predicates still agree, so a
2056    /// test built on one would pass straight through the divergence. Whichever
2057    /// of the two changes merges second has to carry the second half into the
2058    /// verdict, and this is what makes that a red test rather than a textual
2059    /// conflict resolved without it.
2060    ///
2061    /// What this does not show: which of `Full` and `Unknown` a refusal is.
2062    /// `a_failed_space_query_reads_as_unknown_not_full` pins that, and only
2063    /// `Full` reaches the gate.
2064    #[tokio::test]
2065    async fn capacity_verdict_refuses_exactly_when_check_capacity_does() {
2066        let (mut storage, _temp) = create_test_storage().await;
2067        assert_eq!(storage.capacity_verdict(), CapacityVerdict::Writable);
2068        assert!(
2069            storage.check_capacity().is_ok(),
2070            "a writable verdict has to mean the pre-check admits the write"
2071        );
2072
2073        // Two chunks written and deleted, so the store sits on more than one
2074        // chunk of space LMDB can reuse and the filesystem will never take
2075        // back. This is the pruned node the two predicates disagree about.
2076        for fill in [1u8, 2u8] {
2077            let content = vec![fill; MAX_CHUNK_SIZE];
2078            let address = LmdbStorage::compute_address(&content);
2079            assert!(storage.put(&address, &content).await.expect("put"));
2080            assert!(storage.delete(&address).await.expect("delete"));
2081        }
2082
2083        // Established without either function under test, so the scenario does
2084        // not rest on the thing being measured.
2085        storage.config.disk_reserve = u64::MAX / 2;
2086        *storage.last_disk_ok.lock() = None;
2087        let available = fs2::available_space(&storage.env_dir).expect("query available space");
2088        assert!(
2089            available < storage.config.disk_reserve,
2090            "the volume has to read as below the reserve, or neither predicate is \
2091             being asked the interesting question"
2092        );
2093        // Reusable bytes read the way the two-part predicate reads them: the
2094        // file's size less the pages still holding data. `Env::stat` rather
2095        // than `non_free_pages_size`, which calls `String::from_utf8(key)` and
2096        // unwraps, so it panics on our 32 random bytes of key.
2097        let stat = storage.env.stat();
2098        let live_pages = (stat.branch_pages as u64)
2099            .saturating_add(stat.leaf_pages as u64)
2100            .saturating_add(stat.overflow_pages as u64);
2101        let live_bytes = live_pages.saturating_mul(u64::from(stat.page_size));
2102        let file_bytes = storage.env.real_disk_size().expect("query store file size");
2103        let reusable = file_bytes.saturating_sub(live_bytes);
2104        assert!(
2105            reusable > MAX_CHUNK_SIZE as u64,
2106            "the store has to sit on more than one chunk of reusable space, or the \
2107             two predicates are not yet being asked to differ \
2108             (file_bytes={file_bytes}, live_bytes={live_bytes})"
2109        );
2110
2111        // Neither call caches a refusal, so the order of the two does not
2112        // decide either answer.
2113        let pre_check_refuses = storage.check_capacity().is_err();
2114        let verdict = storage.capacity_verdict();
2115        assert_eq!(
2116            pre_check_refuses,
2117            verdict != CapacityVerdict::Writable,
2118            "the dial pre-check and the verification gate disagree about whether \
2119             this node can write: check_capacity refuses={pre_check_refuses}, \
2120             verdict={verdict:?}. A verdict of Full under a pre-check that admits \
2121             the write leaves a node that can store chunks refusing to look for \
2122             them"
2123        );
2124    }
2125
2126    // ── Capacity below the disk reserve (LMDB reuse) ────────────────────
2127
2128    /// Value size for the reuse tests. A whole number of chunks' worth, so the
2129    /// space freed by a few deletes is unambiguously enough for one more.
2130    const REUSE_VALUE_LEN: usize = 1024 * 1024;
2131
2132    /// Distinct filler of `REUSE_VALUE_LEN` bytes.
2133    fn reuse_filler(seed: u32) -> Vec<u8> {
2134        let mut content = seed.to_le_bytes().to_vec();
2135        content.resize(REUSE_VALUE_LEN, 0u8);
2136        content
2137    }
2138
2139    /// A config for `dir` whose reserve exceeds any real disk, so the store
2140    /// always sees itself as below the reserve.
2141    fn below_reserve_config(dir: &Path) -> LmdbStorageConfig {
2142        LmdbStorageConfig {
2143            root_dir: dir.to_path_buf(),
2144            disk_reserve: u64::MAX,
2145            ..LmdbStorageConfig::test_default()
2146        }
2147    }
2148
2149    /// Write `count` chunks with an unconstrained reserve, returning their
2150    /// addresses in insertion order.
2151    async fn seed_chunks(dir: &Path, count: u32) -> Vec<XorName> {
2152        let config = LmdbStorageConfig {
2153            root_dir: dir.to_path_buf(),
2154            ..LmdbStorageConfig::test_default()
2155        };
2156        let storage = LmdbStorage::new(config).await.expect("create storage");
2157
2158        let mut addresses = Vec::new();
2159        for seed in 0..count {
2160            let content = reuse_filler(seed);
2161            let address = LmdbStorage::compute_address(&content);
2162            storage.put(&address, &content).await.expect("seed put");
2163            addresses.push(address);
2164        }
2165
2166        storage.wait_idle().await;
2167        addresses
2168    }
2169
2170    fn file_len(storage: &LmdbStorage) -> u64 {
2171        storage.env.real_disk_size().expect("real_disk_size")
2172    }
2173
2174    /// The regression this change is about: a node whose volume is below the
2175    /// reserve must still write into pages an earlier delete freed. Before the
2176    /// fix the pre-check refused on the disk half alone, so a node that had
2177    /// pruned sat on reusable space it could not use.
2178    #[tokio::test]
2179    async fn below_reserve_put_reuses_freed_pages() {
2180        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
2181        let seeded = seed_chunks(temp_dir.path(), 12).await;
2182
2183        let storage = LmdbStorage::new(below_reserve_config(temp_dir.path()))
2184            .await
2185            .expect("reopen storage");
2186
2187        let content = reuse_filler(u32::MAX);
2188        let address = LmdbStorage::compute_address(&content);
2189
2190        // Nothing freed yet, so this write would have to grow the file. Below
2191        // the reserve that is exactly what must be refused.
2192        assert!(
2193            storage.put(&address, &content).await.is_err(),
2194            "a write that must grow the file was allowed below the reserve"
2195        );
2196
2197        // Free several chunks. Their pages go on LMDB's free list, not back to
2198        // the filesystem, so `statvfs` still reports the volume as full.
2199        for seeded_address in seeded.iter().take(6) {
2200            assert!(storage.delete(seeded_address).await.expect("delete"));
2201        }
2202
2203        let before = file_len(&storage);
2204        let stored = storage
2205            .put(&address, &content)
2206            .await
2207            .expect("put into freed pages was refused below the reserve");
2208        assert!(stored);
2209        assert_eq!(
2210            storage.get(&address).await.expect("get"),
2211            Some(content),
2212            "chunk written into reused pages did not read back"
2213        );
2214
2215        // The whole point: it was served from inside the existing file.
2216        assert_eq!(
2217            file_len(&storage),
2218            before,
2219            "reusing freed pages grew data.mdb, consuming the reserve"
2220        );
2221    }
2222
2223    /// A refused write must not have grown the file on its way to failing,
2224    /// which is what protects the reserve while the map is pinned.
2225    #[tokio::test]
2226    async fn below_reserve_refused_put_does_not_grow_the_file() {
2227        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
2228        let _ = seed_chunks(temp_dir.path(), 6).await;
2229
2230        let storage = LmdbStorage::new(below_reserve_config(temp_dir.path()))
2231            .await
2232            .expect("reopen storage");
2233
2234        let content = reuse_filler(u32::MAX);
2235        let address = LmdbStorage::compute_address(&content);
2236
2237        // Take the baseline after the first attempt, so it includes the pin.
2238        let refusal = storage
2239            .put(&address, &content)
2240            .await
2241            .expect_err("a write that must grow the file was allowed");
2242        assert!(
2243            refusal.to_string().contains("Insufficient disk space"),
2244            "refused for the wrong reason: {refusal}"
2245        );
2246        let before = file_len(&storage);
2247        let pinned_map = storage.env.info().map_size;
2248
2249        for seed in 0..4u32 {
2250            let content = reuse_filler(u32::MAX - 1 - seed);
2251            let address = LmdbStorage::compute_address(&content);
2252            let refusal = storage
2253                .put(&address, &content)
2254                .await
2255                .expect_err("a write that must grow the file was allowed");
2256            assert!(
2257                refusal.to_string().contains("Insufficient disk space"),
2258                "refused for the wrong reason: {refusal}"
2259            );
2260        }
2261
2262        assert_eq!(
2263            storage.env.info().map_size,
2264            pinned_map,
2265            "the map ceiling drifted while writes were being refused"
2266        );
2267
2268        assert_eq!(
2269            file_len(&storage),
2270            before,
2271            "refused writes still extended data.mdb into the reserve"
2272        );
2273    }
2274
2275    /// One refused maximum-sized value must not lock out smaller ones. LMDB's
2276    /// `MapFull` is specific to the allocation it was asked for, so remembering
2277    /// it store-wide would let a single large chunk deny every later write.
2278    #[tokio::test]
2279    async fn large_refusal_does_not_block_a_smaller_put() {
2280        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
2281        let seeded = seed_chunks(temp_dir.path(), 10).await;
2282
2283        let storage = LmdbStorage::new(below_reserve_config(temp_dir.path()))
2284            .await
2285            .expect("reopen storage");
2286
2287        // Free room for a small value, but not for a large one.
2288        let Some(first) = seeded.first() else {
2289            panic!("seed_chunks returned no addresses");
2290        };
2291        assert!(storage.delete(first).await.expect("delete"));
2292
2293        // A value far larger than what was freed cannot fit.
2294        let oversized = vec![3u8; 8 * REUSE_VALUE_LEN];
2295        let oversized_address = LmdbStorage::compute_address(&oversized);
2296        assert!(storage.put(&oversized_address, &oversized).await.is_err());
2297
2298        // A small value still must, using the pages the delete released.
2299        let small = b"small record that fits in a freed page".to_vec();
2300        let small_address = LmdbStorage::compute_address(&small);
2301        let stored = storage
2302            .put(&small_address, &small)
2303            .await
2304            .expect("a large refusal blocked a small put that had room");
2305        assert!(stored);
2306    }
2307
2308    /// A store with no reusable page must still be able to delete, or it can
2309    /// never prune its way back to health.
2310    #[tokio::test]
2311    async fn full_store_below_reserve_can_still_delete() {
2312        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
2313        let seeded = seed_chunks(temp_dir.path(), 8).await;
2314
2315        let storage = LmdbStorage::new(below_reserve_config(temp_dir.path()))
2316            .await
2317            .expect("reopen storage");
2318
2319        // Pin the map by attempting a write that cannot fit.
2320        let content = reuse_filler(u32::MAX);
2321        let address = LmdbStorage::compute_address(&content);
2322        assert!(storage.put(&address, &content).await.is_err());
2323        assert!(storage.no_growth.load(Ordering::Acquire));
2324
2325        let pinned_map = storage.env.info().map_size;
2326
2327        for seeded_address in &seeded {
2328            assert!(
2329                storage.delete(seeded_address).await.expect("delete"),
2330                "a pinned store could not prune"
2331            );
2332        }
2333        assert_eq!(storage.current_chunks().expect("current_chunks"), 0);
2334
2335        // The allowance bounds permanent file growth, not the number of
2336        // assisted deletes. Pruning a pinned store must stay possible however
2337        // many deletes it takes, so whatever was charged has to be growth the
2338        // file really took, and has to stay inside the budget.
2339        let charged = storage.delete_growth_charged.load(Ordering::Acquire);
2340        assert!(
2341            charged < DELETE_COW_GROWTH_BUDGET,
2342            "deletes exhausted the growth allowance ({charged} B) while pruning a pinned store"
2343        );
2344
2345        // Whether or not any delete needed the maintenance allowance, none of
2346        // it may be left in the ceiling afterwards: a raised ceiling is
2347        // ordinary put capacity, so leaking it hands away the reserve.
2348        let file_bytes = file_len(&storage);
2349        assert!(
2350            storage.env.info().map_size as u64 <= file_bytes.max(pinned_map as u64),
2351            "delete left maintenance slack in the map ceiling"
2352        );
2353
2354        // And the store must still refuse a write it cannot fit, i.e. the pin
2355        // is still doing its job after the prune.
2356        let oversized = vec![9u8; 64 * REUSE_VALUE_LEN];
2357        let oversized_address = LmdbStorage::compute_address(&oversized);
2358        assert!(
2359            storage.put(&oversized_address, &oversized).await.is_err(),
2360            "pinning stopped working after a delete used the allowance"
2361        );
2362    }
2363
2364    /// The pre-check must admit while reuse is plausible and refuse once it is
2365    /// not. Refusing on `statvfs` alone is what blinded a node to its own free
2366    /// pages, so being below the reserve cannot by itself be an error.
2367    #[tokio::test]
2368    async fn check_capacity_tracks_reusable_space_not_just_disk() {
2369        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
2370        let seeded = seed_chunks(temp_dir.path(), 16).await;
2371
2372        let storage = LmdbStorage::new(below_reserve_config(temp_dir.path()))
2373            .await
2374            .expect("reopen storage");
2375
2376        // A freshly written store has almost no free page, so below the reserve
2377        // the pre-check refuses and the caller skips its expensive setup.
2378        assert!(
2379            storage.check_capacity().is_err(),
2380            "pre-check stayed open on a store with no reusable space"
2381        );
2382
2383        // Pruning puts pages back on the free list. Nothing is returned to the
2384        // filesystem, so `statvfs` is unchanged and only the reusable half of
2385        // the predicate can reopen the node.
2386        for seeded_address in seeded.iter().take(10) {
2387            assert!(storage.delete(seeded_address).await.expect("delete"));
2388        }
2389
2390        storage
2391            .check_capacity()
2392            .expect("pre-check stayed closed after pruning freed pages");
2393    }
2394
2395    /// Freeing disk must lift the pin, or a node would stay clamped to its
2396    /// high-water mark after an operator grew the partition.
2397    #[tokio::test]
2398    async fn leaving_no_growth_restores_head_room() {
2399        let temp_dir = tempfile::TempDir::new().expect("create temp dir");
2400        let _ = seed_chunks(temp_dir.path(), 6).await;
2401
2402        let mut storage = LmdbStorage::new(below_reserve_config(temp_dir.path()))
2403            .await
2404            .expect("reopen storage");
2405
2406        let content = reuse_filler(u32::MAX);
2407        let address = LmdbStorage::compute_address(&content);
2408        assert!(storage.put(&address, &content).await.is_err());
2409        assert!(storage.no_growth.load(Ordering::Acquire));
2410        let pinned_map = storage.env.info().map_size;
2411
2412        // Simulate the operator freeing space: the reserve is now satisfiable.
2413        storage.config.disk_reserve = 0;
2414        *storage.last_disk_ok.lock() = None;
2415
2416        let stored = storage
2417            .put(&address, &content)
2418            .await
2419            .expect("store stayed pinned after disk was freed");
2420        assert!(stored);
2421        assert!(!storage.no_growth.load(Ordering::Acquire));
2422        assert!(
2423            storage.env.info().map_size > pinned_map,
2424            "map was not re-grown after leaving no-growth mode"
2425        );
2426    }
2427
2428    /// Above the reserve nothing changes: no pinning, and writes grow the file
2429    /// on demand exactly as before.
2430    #[tokio::test]
2431    async fn above_reserve_behaviour_is_unchanged() {
2432        let (storage, _temp) = create_test_storage().await;
2433
2434        storage
2435            .check_capacity()
2436            .expect("pre-check on a healthy node");
2437
2438        let content = reuse_filler(1);
2439        let address = LmdbStorage::compute_address(&content);
2440        assert!(storage.put(&address, &content).await.expect("put"));
2441        assert!(!storage.no_growth.load(Ordering::Acquire));
2442        storage
2443            .check_capacity()
2444            .expect("pre-check after a healthy put");
2445    }
2446}