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;
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::Arc;
17use std::time::Instant;
18use tokio::task::spawn_blocking;
19
20use crate::ant_protocol::XORNAME_LEN;
21
22/// Bytes in one MiB.
23pub const MIB: u64 = 1024 * 1024;
24
25/// Bytes in one GiB.
26pub const GIB: u64 = 1024 * MIB;
27
28/// Default minimum free disk space to preserve on the storage partition.
29const DEFAULT_DISK_RESERVE: u64 = 500 * MIB;
30
31/// Convert a byte count to GiB for human-readable log messages.
32#[allow(clippy::cast_precision_loss)] // display only — sub-byte precision is irrelevant
33fn bytes_to_gib(bytes: u64) -> f64 {
34    bytes as f64 / GIB as f64
35}
36
37/// Absolute minimum LMDB map size.
38///
39/// Even on a nearly-full disk the database must be able to open.
40/// Set to 256 MiB — enough for millions of LMDB pages.
41const MIN_MAP_SIZE: usize = 256 * 1024 * 1024;
42
43/// Maximum head-room (beyond the current data footprint) to reserve for the
44/// LMDB map **on Windows**.
45///
46/// On Windows a node's committed / private memory scales with the *mapped*
47/// size rather than with the data actually stored. Measured on a live node:
48/// ~7.4 GB of extra commit for a ~3.7 TiB map, versus ~181 MB for a ~55 GiB
49/// map — roughly 0.2% of the mapped size, resident and attributed to *no*
50/// user-space allocation. That size-proportional cost is consistent with
51/// kernel page tables / section metadata for the mapping; the exact kernel
52/// structure was inferred from the scaling rather than measured directly, but
53/// the size-proportional *effect* is what this cap targets. Linux keeps the
54/// mapping sparse, so a disk-sized map is nearly free there — the overhead is
55/// Windows-specific, which is why it only surfaced in Windows reports.
56///
57/// Sizing the map to the whole disk therefore costs ~0.2% of *free disk* per
58/// node, multiplied by every node sharing the host (e.g. a 10 TiB partition ≈
59/// 20 GiB). We instead cap the head-room on Windows and lean on
60/// `LmdbStorage::try_resize` to extend the map on demand as data accumulates,
61/// keeping the overhead proportional to *stored data* rather than *disk
62/// capacity*. At 32 GiB the extra commit is ~100 MB, and a resize happens at
63/// most once per 32 GiB written.
64#[cfg(windows)]
65const WINDOWS_MAP_HEADROOM: u64 = 32 * GIB;
66
67/// How often to re-query available disk space (in seconds).
68///
69/// Between checks the cached result is trusted.  Disk space changes slowly
70/// relative to chunk-write throughput, so a multi-second window is safe.
71const DISK_CHECK_INTERVAL_SECS: u64 = 5;
72
73/// Configuration for LMDB storage.
74#[derive(Debug, Clone)]
75pub struct LmdbStorageConfig {
76    /// Root directory for storage (LMDB env lives at `{root_dir}/chunks.mdb/`).
77    pub root_dir: PathBuf,
78    /// Whether to verify content on read (compares hash to address).
79    pub verify_on_read: bool,
80    /// Explicit LMDB map size cap in bytes.
81    ///
82    /// When 0 (default), the map size is computed automatically from available
83    /// disk space and grows on demand when more storage becomes available.
84    pub max_map_size: usize,
85    /// Minimum free disk space (in bytes) to preserve on the storage partition.
86    ///
87    /// Writes are refused when available space drops below this threshold.
88    pub disk_reserve: u64,
89}
90
91impl Default for LmdbStorageConfig {
92    fn default() -> Self {
93        Self {
94            root_dir: PathBuf::from(".ant/chunks"),
95            verify_on_read: true,
96            max_map_size: 0,
97            disk_reserve: DEFAULT_DISK_RESERVE,
98        }
99    }
100}
101
102impl LmdbStorageConfig {
103    /// A test-friendly default with `disk_reserve` set to 0 so unit tests
104    /// don't depend on the host having >= 1 GiB free disk space.
105    #[cfg(any(test, feature = "test-utils"))]
106    #[must_use]
107    pub fn test_default() -> Self {
108        Self {
109            disk_reserve: 0,
110            ..Self::default()
111        }
112    }
113}
114
115/// Statistics about storage operations.
116#[derive(Debug, Clone, Default)]
117pub struct StorageStats {
118    /// Total number of chunks stored.
119    pub chunks_stored: u64,
120    /// Total number of chunks retrieved.
121    pub chunks_retrieved: u64,
122    /// Total bytes stored.
123    pub bytes_stored: u64,
124    /// Total bytes retrieved.
125    pub bytes_retrieved: u64,
126    /// Number of duplicate writes (already exists).
127    pub duplicates: u64,
128    /// Number of verification failures on read.
129    pub verification_failures: u64,
130    /// Number of chunks currently persisted.
131    pub current_chunks: u64,
132}
133
134/// Content-addressed LMDB storage.
135///
136/// Uses heed (LMDB wrapper) for memory-mapped, transactional chunk storage.
137/// Keys are 32-byte `XorName` addresses, values are raw chunk bytes.
138pub struct LmdbStorage {
139    /// LMDB environment.
140    env: Env,
141    /// The unnamed default database (key=XorName bytes, value=chunk bytes).
142    db: Database<Bytes, Bytes>,
143    /// Storage configuration.
144    config: LmdbStorageConfig,
145    /// Path to the LMDB environment directory (for disk-space queries).
146    env_dir: PathBuf,
147    /// Operation statistics.
148    stats: parking_lot::RwLock<StorageStats>,
149    /// Serialises access to the LMDB environment during a map resize.
150    ///
151    /// Normal read/write operations acquire a **shared** lock.  The rare
152    /// resize path acquires an **exclusive** lock, ensuring no transactions
153    /// are active when `env.resize()` is called (an LMDB safety requirement).
154    env_lock: Arc<parking_lot::RwLock<()>>,
155    /// Timestamp of the last successful disk-space check.
156    ///
157    /// `None` means "never checked — check on next write".  Updated only
158    /// after a passing check, so a low-space result is always rechecked.
159    last_disk_ok: parking_lot::Mutex<Option<Instant>>,
160}
161
162impl LmdbStorage {
163    /// Create a new LMDB storage instance.
164    ///
165    /// Opens (or creates) an LMDB environment at `{root_dir}/chunks.mdb/`.
166    ///
167    /// When `config.max_map_size` is 0 (the default) the map size is derived
168    /// from the available disk space on the partition that hosts the database,
169    /// minus `config.disk_reserve`.  This allows a node to use all available
170    /// storage without a fixed cap.  If the operator adds more storage later
171    /// the map is resized on demand (see [`Self::put`]).
172    ///
173    /// # Errors
174    ///
175    /// Returns an error if the LMDB environment cannot be opened.
176    #[allow(unsafe_code)]
177    pub async fn new(config: LmdbStorageConfig) -> Result<Self> {
178        let env_dir = config.root_dir.join("chunks.mdb");
179
180        // Create the directory synchronously before opening LMDB
181        std::fs::create_dir_all(&env_dir)
182            .map_err(|e| Error::Storage(format!("Failed to create LMDB directory: {e}")))?;
183
184        let map_size = if config.max_map_size > 0 {
185            // Operator provided an explicit cap.
186            config.max_map_size
187        } else {
188            // Auto-scale: current DB footprint + available space − reserve.
189            let computed = compute_map_size(&env_dir, config.disk_reserve)?;
190            info!(
191                "Auto-computed LMDB map size: {:.2} GiB (data + available disk minus {:.2} GiB \
192                 reserve, head-room capped on Windows to bound page-table overhead)",
193                bytes_to_gib(computed as u64),
194                bytes_to_gib(config.disk_reserve),
195            );
196            computed
197        };
198
199        let env_dir_clone = env_dir.clone();
200        let (env, db) = spawn_blocking(move || -> Result<(Env, Database<Bytes, Bytes>)> {
201            // SAFETY: `EnvOpenOptions::open()` is unsafe because LMDB uses memory-mapped
202            // I/O and relies on OS file-locking to prevent corruption from concurrent
203            // access by multiple processes. We satisfy this by giving each node instance
204            // a unique `root_dir` (typically a directory named by its full 64-hex peer
205            // ID), ensuring no two processes open the same LMDB environment. Callers
206            // who manually configure `--root-dir` must not point multiple nodes at the
207            // same directory.
208            let env = unsafe {
209                EnvOpenOptions::new()
210                    .map_size(map_size)
211                    .max_dbs(1)
212                    .open(&env_dir_clone)
213                    .map_err(|e| Error::Storage(format!("Failed to open LMDB env: {e}")))?
214            };
215
216            let mut wtxn = env
217                .write_txn()
218                .map_err(|e| Error::Storage(format!("Failed to create write txn: {e}")))?;
219            let db: Database<Bytes, Bytes> = env
220                .create_database(&mut wtxn, None)
221                .map_err(|e| Error::Storage(format!("Failed to create database: {e}")))?;
222            wtxn.commit()
223                .map_err(|e| Error::Storage(format!("Failed to commit db creation: {e}")))?;
224
225            Ok((env, db))
226        })
227        .await
228        .map_err(|e| Error::Storage(format!("LMDB init task failed: {e}")))??;
229
230        let storage = Self {
231            env,
232            db,
233            config,
234            env_dir,
235            stats: parking_lot::RwLock::new(StorageStats::default()),
236            env_lock: Arc::new(parking_lot::RwLock::new(())),
237            last_disk_ok: parking_lot::Mutex::new(None),
238        };
239
240        debug!(
241            "Initialized LMDB storage at {:?} ({} existing chunks)",
242            storage.env_dir,
243            storage.current_chunks()?
244        );
245
246        Ok(storage)
247    }
248
249    /// Store a chunk.
250    ///
251    /// Before writing, verifies that available disk space exceeds the
252    /// configured reserve.  If the LMDB map is full but more disk space
253    /// exists (e.g. the operator added storage), the map is resized
254    /// automatically and the write is retried.
255    ///
256    /// # Returns
257    ///
258    /// Returns `true` if the chunk was newly stored, `false` if it already existed.
259    ///
260    /// # Errors
261    ///
262    /// Returns an error if the write fails, content doesn't match address,
263    /// or the disk is too full to accept new chunks.
264    pub async fn put(&self, address: &XorName, content: &[u8]) -> Result<bool> {
265        // Verify content address
266        let computed = Self::compute_address(content);
267        if computed != *address {
268            return Err(Error::Storage(format!(
269                "Content address mismatch: expected {}, computed {}",
270                hex::encode(address),
271                hex::encode(computed)
272            )));
273        }
274
275        // Fast-path duplicate check (read-only, no write lock needed).
276        // This is an optimistic hint — the authoritative check happens inside
277        // the write transaction below to prevent TOCTOU races.
278        if self.exists(address)? {
279            trace!("Chunk {} already exists", hex::encode(address));
280            self.stats.write().duplicates += 1;
281            return Ok(false);
282        }
283
284        // ── Disk-space guard (cached — at most one syscall per interval) ─
285        // Placed after the duplicate check so that re-storing an existing
286        // chunk remains a harmless no-op even when disk space is low.
287        self.check_disk_space_cached()?;
288
289        // ── Write (with resize-on-demand) ───────────────────────────────
290        match self.try_put(address, content).await? {
291            PutOutcome::New => {}
292            PutOutcome::Duplicate => {
293                trace!("Chunk {} already exists", hex::encode(address));
294                self.stats.write().duplicates += 1;
295                return Ok(false);
296            }
297            PutOutcome::MapFull => {
298                // The map ceiling was reached but there may be more disk space
299                // available (e.g. operator expanded the partition).
300                self.try_resize().await?;
301                // Retry once after resize.
302                match self.try_put(address, content).await? {
303                    PutOutcome::New => {}
304                    PutOutcome::Duplicate => {
305                        self.stats.write().duplicates += 1;
306                        return Ok(false);
307                    }
308                    PutOutcome::MapFull => {
309                        return Err(Error::Storage(
310                            "LMDB map full after resize — disk may be at capacity".into(),
311                        ));
312                    }
313                }
314            }
315        }
316
317        {
318            let mut stats = self.stats.write();
319            stats.chunks_stored += 1;
320            stats.bytes_stored += content.len() as u64;
321        }
322
323        debug!(
324            "Stored chunk {} ({} bytes)",
325            hex::encode(address),
326            content.len()
327        );
328
329        Ok(true)
330    }
331
332    /// Attempt a single put inside a write transaction.
333    ///
334    /// Returns [`PutOutcome::MapFull`] instead of an error when the LMDB map
335    /// ceiling is reached, so the caller can resize and retry.
336    async fn try_put(&self, address: &XorName, content: &[u8]) -> Result<PutOutcome> {
337        let key = *address;
338        let value = content.to_vec();
339        let env = self.env.clone();
340        let db = self.db;
341        let lock = Arc::clone(&self.env_lock);
342
343        spawn_blocking(move || -> Result<PutOutcome> {
344            let _guard = lock.read();
345
346            let mut wtxn = env
347                .write_txn()
348                .map_err(|e| Error::Storage(format!("Failed to create write txn: {e}")))?;
349
350            // Authoritative existence check inside the serialized write txn
351            if db
352                .get(&wtxn, &key)
353                .map_err(|e| Error::Storage(format!("Failed to check existence: {e}")))?
354                .is_some()
355            {
356                return Ok(PutOutcome::Duplicate);
357            }
358
359            match db.put(&mut wtxn, &key, &value) {
360                Ok(()) => {}
361                Err(heed::Error::Mdb(MdbError::MapFull)) => return Ok(PutOutcome::MapFull),
362                Err(e) => {
363                    return Err(Error::Storage(format!("Failed to put chunk: {e}")));
364                }
365            }
366
367            match wtxn.commit() {
368                Ok(()) => Ok(PutOutcome::New),
369                Err(heed::Error::Mdb(MdbError::MapFull)) => Ok(PutOutcome::MapFull),
370                Err(e) => Err(Error::Storage(format!("Failed to commit put: {e}"))),
371            }
372        })
373        .await
374        .map_err(|e| Error::Storage(format!("LMDB put task failed: {e}")))?
375    }
376
377    /// Retrieve a chunk.
378    ///
379    /// # Returns
380    ///
381    /// Returns `Some(content)` if found, `None` if not found.
382    ///
383    /// # Errors
384    ///
385    /// Returns an error if read fails or verification fails.
386    pub async fn get(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
387        let key = *address;
388        let env = self.env.clone();
389        let db = self.db;
390        let lock = Arc::clone(&self.env_lock);
391
392        let content = spawn_blocking(move || -> Result<Option<Vec<u8>>> {
393            let _guard = lock.read();
394            let rtxn = env
395                .read_txn()
396                .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
397            let value = db
398                .get(&rtxn, &key)
399                .map_err(|e| Error::Storage(format!("Failed to get chunk: {e}")))?;
400            Ok(value.map(Vec::from))
401        })
402        .await
403        .map_err(|e| Error::Storage(format!("LMDB get task failed: {e}")))??;
404
405        let Some(content) = content else {
406            trace!("Chunk {} not found", hex::encode(address));
407            return Ok(None);
408        };
409
410        // Verify content if configured
411        if self.config.verify_on_read {
412            let computed = Self::compute_address(&content);
413            if computed != *address {
414                self.stats.write().verification_failures += 1;
415                warn!(
416                    "Chunk verification failed: expected {}, computed {}",
417                    hex::encode(address),
418                    hex::encode(computed)
419                );
420                return Err(Error::Storage(format!(
421                    "Chunk verification failed for {}",
422                    hex::encode(address)
423                )));
424            }
425        }
426
427        {
428            let mut stats = self.stats.write();
429            stats.chunks_retrieved += 1;
430            stats.bytes_retrieved += content.len() as u64;
431        }
432
433        debug!(
434            "Retrieved chunk {} ({} bytes)",
435            hex::encode(address),
436            content.len()
437        );
438
439        Ok(Some(content))
440    }
441
442    /// Check if a chunk exists.
443    ///
444    /// # Errors
445    ///
446    /// Returns an error if the LMDB read transaction fails.
447    pub fn exists(&self, address: &XorName) -> Result<bool> {
448        let _guard = self.env_lock.read();
449        let rtxn = self
450            .env
451            .read_txn()
452            .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
453        let found = self
454            .db
455            .get(&rtxn, address.as_ref())
456            .map_err(|e| Error::Storage(format!("Failed to check existence: {e}")))?
457            .is_some();
458        Ok(found)
459    }
460
461    /// Delete a chunk.
462    ///
463    /// # Errors
464    ///
465    /// Returns an error if deletion fails.
466    pub async fn delete(&self, address: &XorName) -> Result<bool> {
467        let key = *address;
468        let env = self.env.clone();
469        let db = self.db;
470        let lock = Arc::clone(&self.env_lock);
471
472        let deleted = spawn_blocking(move || -> Result<bool> {
473            let _guard = lock.read();
474            let mut wtxn = env
475                .write_txn()
476                .map_err(|e| Error::Storage(format!("Failed to create write txn: {e}")))?;
477            let existed = db
478                .delete(&mut wtxn, &key)
479                .map_err(|e| Error::Storage(format!("Failed to delete chunk: {e}")))?;
480            wtxn.commit()
481                .map_err(|e| Error::Storage(format!("Failed to commit delete: {e}")))?;
482            Ok(existed)
483        })
484        .await
485        .map_err(|e| Error::Storage(format!("LMDB delete task failed: {e}")))??;
486
487        if deleted {
488            debug!("Deleted chunk {}", hex::encode(address));
489        }
490
491        Ok(deleted)
492    }
493
494    /// Get storage statistics.
495    #[must_use]
496    pub fn stats(&self) -> StorageStats {
497        let mut stats = self.stats.read().clone();
498        match self.current_chunks() {
499            Ok(count) => stats.current_chunks = count,
500            Err(e) => {
501                warn!("Failed to read current_chunks for stats: {e}");
502                stats.current_chunks = 0;
503            }
504        }
505        stats
506    }
507
508    /// Return the number of chunks currently stored, queried from LMDB metadata.
509    ///
510    /// This is an O(1) read of the B-tree page header — not a full scan.
511    ///
512    /// # Errors
513    ///
514    /// Returns an error if the LMDB read transaction fails.
515    pub fn current_chunks(&self) -> Result<u64> {
516        let _guard = self.env_lock.read();
517        let rtxn = self
518            .env
519            .read_txn()
520            .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
521        let entries = self
522            .db
523            .stat(&rtxn)
524            .map_err(|e| Error::Storage(format!("Failed to read db stats: {e}")))?
525            .entries;
526        Ok(entries as u64)
527    }
528
529    /// Compute content address (BLAKE3 hash).
530    #[must_use]
531    pub fn compute_address(content: &[u8]) -> XorName {
532        crate::client::compute_address(content)
533    }
534
535    /// Get the root directory.
536    #[must_use]
537    pub fn root_dir(&self) -> &Path {
538        &self.config.root_dir
539    }
540
541    /// Return all stored record keys.
542    ///
543    /// Iterates the LMDB database in a read transaction. Used by the
544    /// replication subsystem for hint construction and audit sampling.
545    ///
546    /// # Errors
547    ///
548    /// Returns an error if the LMDB read transaction fails.
549    pub async fn all_keys(&self) -> Result<Vec<XorName>> {
550        let env = self.env.clone();
551        let db = self.db;
552        let lock = Arc::clone(&self.env_lock);
553
554        let keys = spawn_blocking(move || -> Result<Vec<XorName>> {
555            // Hold the shared lock for the whole read so try_resize() (which
556            // takes the exclusive lock before the unsafe Env::resize()) cannot
557            // unmap the environment while this txn and its cursor are live.
558            let _guard = lock.read();
559            let rtxn = env
560                .read_txn()
561                .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
562            let mut keys = Vec::new();
563            let iter = db
564                .iter(&rtxn)
565                .map_err(|e| Error::Storage(format!("Failed to iterate database: {e}")))?;
566            for result in iter {
567                let (key_bytes, _) =
568                    result.map_err(|e| Error::Storage(format!("Failed to read entry: {e}")))?;
569                if key_bytes.len() == XORNAME_LEN {
570                    let mut key = [0u8; XORNAME_LEN];
571                    key.copy_from_slice(key_bytes);
572                    keys.push(key);
573                } else {
574                    crate::logging::warn!(
575                        "LmdbStorage: skipping entry with unexpected key length {} (expected {XORNAME_LEN})",
576                        key_bytes.len()
577                    );
578                }
579            }
580            Ok(keys)
581        })
582        .await
583        .map_err(|e| Error::Storage(format!("all_keys task failed: {e}")))?;
584
585        keys
586    }
587
588    /// Retrieve raw chunk bytes without content-address verification.
589    ///
590    /// Used by the audit subsystem to compute digests over stored bytes.
591    /// Unlike [`Self::get`], this does not verify `hash(content) == address`.
592    ///
593    /// # Errors
594    ///
595    /// Returns an error if the LMDB read transaction fails.
596    pub async fn get_raw(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
597        let key = *address;
598        let env = self.env.clone();
599        let db = self.db;
600        let lock = Arc::clone(&self.env_lock);
601
602        let value = spawn_blocking(move || -> Result<Option<Vec<u8>>> {
603            // Shared lock held until the bytes are copied out, so a concurrent
604            // try_resize() cannot unmap the environment mid-read. See all_keys.
605            let _guard = lock.read();
606            let rtxn = env
607                .read_txn()
608                .map_err(|e| Error::Storage(format!("Failed to create read txn: {e}")))?;
609            let val = db
610                .get(&rtxn, key.as_ref())
611                .map_err(|e| Error::Storage(format!("Failed to get chunk: {e}")))?;
612            Ok(val.map(Vec::from))
613        })
614        .await
615        .map_err(|e| Error::Storage(format!("get_raw task failed: {e}")))?;
616
617        value
618    }
619
620    /// Cheap capacity pre-check for callers that want to reject work *before*
621    /// doing expensive setup (e.g. the PUT handler skipping payment
622    /// verification on a disk-full node — see `V2-411`).
623    ///
624    /// Delegates to the private `check_disk_space_cached`, so it shares the same
625    /// TTL cache and only ever performs an `fs2::available_space` syscall on a
626    /// cache miss. Returns the same `Insufficient disk space …` error the
627    /// store path raises, keeping caller behaviour identical.
628    ///
629    /// # Errors
630    ///
631    /// Returns [`Error::Storage`] when available space is below the configured
632    /// reserve, or when the disk-space query itself fails.
633    pub(crate) fn check_capacity(&self) -> Result<()> {
634        self.check_disk_space_cached()
635    }
636
637    /// Check available disk space, skipping the syscall if a recent check passed.
638    ///
639    /// Only caches *passing* results — a low-space condition is always
640    /// rechecked so we detect freed space promptly.
641    fn check_disk_space_cached(&self) -> Result<()> {
642        {
643            let last = self.last_disk_ok.lock();
644            if let Some(t) = *last {
645                if t.elapsed().as_secs() < DISK_CHECK_INTERVAL_SECS {
646                    return Ok(());
647                }
648            }
649        }
650        // Cache miss or stale — perform the actual statvfs check.
651        check_disk_space(&self.env_dir, self.config.disk_reserve)?;
652        // Passed — update the cache timestamp.
653        *self.last_disk_ok.lock() = Some(Instant::now());
654        Ok(())
655    }
656
657    /// Grow the LMDB map to match currently available disk space.
658    ///
659    /// The new size is the **larger** of:
660    ///   1. the current map size (so existing data is never truncated), and
661    ///   2. `current_db_file_size + available_space − reserve`
662    ///      (so all reachable disk space can be used).
663    ///
664    /// Acquires an **exclusive** lock on `env_lock` so that no read or write
665    /// transactions are active when the underlying `mdb_env_set_mapsize` is
666    /// called (an LMDB safety requirement).
667    #[allow(unsafe_code)]
668    async fn try_resize(&self) -> Result<()> {
669        let from_disk = compute_map_size(&self.env_dir, self.config.disk_reserve)?;
670        let env = self.env.clone();
671        let lock = Arc::clone(&self.env_lock);
672
673        spawn_blocking(move || -> Result<()> {
674            // Exclusive lock guarantees no concurrent transactions.
675            let _guard = lock.write();
676
677            // Never shrink below the current map — existing data must remain
678            // addressable regardless of what the disk-space calculation says.
679            let current_map = env.info().map_size;
680            let new_size = from_disk.max(current_map);
681
682            if new_size <= current_map {
683                debug!("LMDB map resize skipped — no additional disk space available");
684                return Ok(());
685            }
686
687            // SAFETY: We hold an exclusive lock, so no transactions are active.
688            unsafe {
689                env.resize(new_size)
690                    .map_err(|e| Error::Storage(format!("Failed to resize LMDB map: {e}")))?;
691            }
692
693            info!(
694                "Resized LMDB map to {:.2} GiB (was {:.2} GiB)",
695                bytes_to_gib(new_size as u64),
696                bytes_to_gib(current_map as u64),
697            );
698            Ok(())
699        })
700        .await
701        .map_err(|e| Error::Storage(format!("LMDB resize task failed: {e}")))?
702    }
703}
704
705// ────────────────────────────────────────────────────────────────────────────
706// Helpers
707// ────────────────────────────────────────────────────────────────────────────
708
709/// Outcome of a single `try_put` attempt.
710enum PutOutcome {
711    /// Chunk was newly stored.
712    New,
713    /// Chunk already existed (idempotent).
714    Duplicate,
715    /// The LMDB map ceiling was reached — caller should resize and retry.
716    MapFull,
717}
718
719/// Compute the LMDB map size from the disk hosting `db_dir`.
720///
721/// The result covers **all existing data** plus all remaining usable disk
722/// space:
723///
724/// ```text
725/// map_size = current_db_file_size + max(0, available_space − reserve)
726/// ```
727///
728/// `available_space` (from `statvfs`) reports only the *free* bytes on the
729/// partition — the DB file's own footprint is **not** included, so adding
730/// it back ensures the map is always large enough for the data already
731/// stored.
732///
733/// On Windows the disk-headroom term is additionally capped at
734/// `WINDOWS_MAP_HEADROOM` to bound the map-proportional commit overhead (see
735/// that constant); [`LmdbStorage::try_resize`] extends the map on demand as
736/// data grows.
737///
738/// The result is page-aligned and never falls below [`MIN_MAP_SIZE`].
739fn compute_map_size(db_dir: &Path, reserve: u64) -> Result<usize> {
740    let available = fs2::available_space(db_dir)
741        .map_err(|e| Error::Storage(format!("Failed to query available disk space: {e}")))?;
742
743    // The MDB data file may not exist yet on first run.
744    let mdb_file = db_dir.join("data.mdb");
745    let current_db_bytes = std::fs::metadata(&mdb_file).map_or(0, |m| m.len());
746
747    let target = map_target_bytes(current_db_bytes, available, reserve);
748
749    // Align up to system page size (required by heed's resize).
750    let page = page_size::get() as u64;
751    let aligned = target.div_ceil(page) * page;
752
753    let result = usize::try_from(aligned).unwrap_or(usize::MAX);
754    Ok(result.max(MIN_MAP_SIZE))
755}
756
757/// Head-room policy for the LMDB map, split out from [`compute_map_size`] so it
758/// is unit-testable without touching the real filesystem.
759///
760/// `map = current_db_bytes + max(0, available − reserve)`, with the head-room
761/// term capped at `WINDOWS_MAP_HEADROOM` on Windows. Existing data
762/// (`current_db_bytes`) is always covered so a resize can never truncate the
763/// database, even when the head-room cap or a nearly-full disk drives the
764/// growth term to zero.
765fn map_target_bytes(current_db_bytes: u64, available: u64, reserve: u64) -> u64 {
766    // available_space excludes the DB file, so we add it back to get the
767    // total space the DB could occupy while still leaving `reserve` free.
768    let growth_room = available.saturating_sub(reserve);
769
770    // On Windows, bound the head-room so the mapped size (and its
771    // size-proportional commit overhead) stays proportional to stored data
772    // rather than disk capacity. Elsewhere, use all reachable space.
773    #[cfg(windows)]
774    let growth_room = growth_room.min(WINDOWS_MAP_HEADROOM);
775
776    current_db_bytes.saturating_add(growth_room)
777}
778
779/// Reject the write early if available disk space is below `reserve`.
780fn check_disk_space(db_dir: &Path, reserve: u64) -> Result<()> {
781    let available = fs2::available_space(db_dir)
782        .map_err(|e| Error::Storage(format!("Failed to query available disk space: {e}")))?;
783
784    if available < reserve {
785        return Err(Error::Storage(format!(
786            "Insufficient disk space: {:.2} GiB available, {:.2} GiB reserve required. \
787             Free disk space or increase the partition to continue storing chunks.",
788            bytes_to_gib(available),
789            bytes_to_gib(reserve),
790        )));
791    }
792
793    Ok(())
794}
795
796#[cfg(test)]
797#[allow(clippy::unwrap_used, clippy::expect_used)]
798mod tests {
799    use super::*;
800    use tempfile::TempDir;
801
802    #[test]
803    fn map_target_covers_existing_data_and_headroom() {
804        // A partition with far more free space than any node needs.
805        let huge_free = 100 * 1024 * GIB; // 100 TiB
806        let reserve = 500 * MIB;
807
808        // Fresh node, no data yet.
809        let fresh = map_target_bytes(0, huge_free, reserve);
810        // Node already holding 16 GiB of chunks.
811        let with_data = map_target_bytes(16 * GIB, huge_free, reserve);
812
813        #[cfg(windows)]
814        {
815            // Windows: head-room is capped, so the map (and thus page tables)
816            // stay bounded regardless of disk size. Existing data always sits
817            // on top of the capped head-room.
818            assert_eq!(fresh, WINDOWS_MAP_HEADROOM);
819            assert_eq!(with_data, 16 * GIB + WINDOWS_MAP_HEADROOM);
820            // Sanity: page-table cost (~map/512) is tens of MiB, not tens of GiB.
821            assert!(with_data / 512 < 128 * MIB);
822        }
823
824        #[cfg(not(windows))]
825        {
826            // Other platforms keep the disk-sized map (lazy page tables cost
827            // nothing), so head-room is the full free span minus reserve.
828            assert_eq!(fresh, huge_free - reserve);
829            assert_eq!(with_data, 16 * GIB + (huge_free - reserve));
830        }
831    }
832
833    #[test]
834    fn map_target_never_truncates_data_when_disk_nearly_full() {
835        // Free space below the reserve → head-room saturates to 0 on every
836        // platform, but the existing 4 GiB of data must still be covered.
837        assert_eq!(map_target_bytes(4 * GIB, 100 * MIB, 500 * MIB), 4 * GIB);
838    }
839
840    /// Regression (V2-620 review): `all_keys` and `get_raw` must take the shared
841    /// `env_lock` so their LMDB read transaction can never run concurrently with
842    /// `try_resize()`'s unsafe `Env::resize()` — which this PR turns into a
843    /// routine ~per-32-GiB Windows event. We prove it by holding the exclusive
844    /// lock (as a resize does) and asserting both calls block until it is freed.
845    ///
846    /// Holding a `parking_lot` guard across `.await` is deliberate and safe here:
847    /// the guard stays on this current-thread test task while `all_keys`/`get_raw`
848    /// run their blocking work on the `spawn_blocking` pool (separate threads).
849    #[tokio::test]
850    #[allow(clippy::await_holding_lock)]
851    async fn read_paths_block_while_env_is_being_resized() {
852        use std::time::Duration;
853        let (storage, _temp) = create_test_storage().await;
854
855        // Store one chunk so the read paths have real work to return.
856        let content = b"resize-safety";
857        let address = LmdbStorage::compute_address(content);
858        storage.put(&address, content).await.expect("put");
859
860        // Simulate a resize in progress: hold the exclusive env lock.
861        let write_guard = storage.env_lock.write();
862
863        // Neither read path may complete while the exclusive lock is held —
864        // before the fix they took no lock and would return immediately.
865        assert!(
866            tokio::time::timeout(Duration::from_millis(250), storage.all_keys())
867                .await
868                .is_err(),
869            "all_keys completed while env_lock was held exclusively — missing shared guard"
870        );
871        assert!(
872            tokio::time::timeout(Duration::from_millis(250), storage.get_raw(&address))
873                .await
874                .is_err(),
875            "get_raw completed while env_lock was held exclusively — missing shared guard"
876        );
877
878        // Once the exclusive lock is released, both proceed and see the data.
879        drop(write_guard);
880        assert_eq!(storage.all_keys().await.expect("all_keys").len(), 1);
881        assert_eq!(
882            storage.get_raw(&address).await.expect("get_raw").as_deref(),
883            Some(content.as_slice())
884        );
885    }
886
887    async fn create_test_storage() -> (LmdbStorage, TempDir) {
888        let temp_dir = TempDir::new().expect("create temp dir");
889        let config = LmdbStorageConfig {
890            root_dir: temp_dir.path().to_path_buf(),
891            ..LmdbStorageConfig::test_default()
892        };
893        let storage = LmdbStorage::new(config).await.expect("create storage");
894        (storage, temp_dir)
895    }
896
897    #[tokio::test]
898    async fn test_put_and_get() {
899        let (storage, _temp) = create_test_storage().await;
900
901        let content = b"hello world";
902        let address = LmdbStorage::compute_address(content);
903
904        // Store chunk
905        let is_new = storage.put(&address, content).await.expect("put");
906        assert!(is_new);
907
908        // Retrieve chunk
909        let retrieved = storage.get(&address).await.expect("get");
910        assert_eq!(retrieved, Some(content.to_vec()));
911    }
912
913    #[tokio::test]
914    async fn test_put_duplicate() {
915        let (storage, _temp) = create_test_storage().await;
916
917        let content = b"test data";
918        let address = LmdbStorage::compute_address(content);
919
920        // First store
921        let is_new1 = storage.put(&address, content).await.expect("put 1");
922        assert!(is_new1);
923
924        // Duplicate store
925        let is_new2 = storage.put(&address, content).await.expect("put 2");
926        assert!(!is_new2);
927
928        // Check stats
929        let stats = storage.stats();
930        assert_eq!(stats.chunks_stored, 1);
931        assert_eq!(stats.duplicates, 1);
932    }
933
934    #[tokio::test]
935    async fn test_get_not_found() {
936        let (storage, _temp) = create_test_storage().await;
937
938        let address = [0xAB; 32];
939        let result = storage.get(&address).await.expect("get");
940        assert!(result.is_none());
941    }
942
943    #[tokio::test]
944    async fn test_exists() {
945        let (storage, _temp) = create_test_storage().await;
946
947        let content = b"exists test";
948        let address = LmdbStorage::compute_address(content);
949
950        assert!(!storage.exists(&address).expect("exists"));
951
952        storage.put(&address, content).await.expect("put");
953
954        assert!(storage.exists(&address).expect("exists"));
955    }
956
957    #[tokio::test]
958    async fn test_delete() {
959        let (storage, _temp) = create_test_storage().await;
960
961        let content = b"delete test";
962        let address = LmdbStorage::compute_address(content);
963
964        // Store
965        storage.put(&address, content).await.expect("put");
966        assert!(storage.exists(&address).expect("exists"));
967
968        // Delete
969        let deleted = storage.delete(&address).await.expect("delete");
970        assert!(deleted);
971        assert!(!storage.exists(&address).expect("exists"));
972
973        // Delete again (already deleted)
974        let deleted2 = storage.delete(&address).await.expect("delete 2");
975        assert!(!deleted2);
976    }
977
978    #[tokio::test]
979    async fn test_address_mismatch() {
980        let (storage, _temp) = create_test_storage().await;
981
982        let content = b"some content";
983        let wrong_address = [0xFF; 32]; // Wrong address
984
985        let result = storage.put(&wrong_address, content).await;
986        assert!(result.is_err());
987        assert!(result.unwrap_err().to_string().contains("mismatch"));
988    }
989
990    #[test]
991    fn test_compute_address() {
992        // Known BLAKE3 hash of "hello world"
993        let content = b"hello world";
994        let address = LmdbStorage::compute_address(content);
995
996        let expected_hex = "d74981efa70a0c880b8d8c1985d075dbcbf679b99a5f9914e5aaf96b831a9e24";
997        assert_eq!(hex::encode(address), expected_hex);
998    }
999
1000    #[tokio::test]
1001    async fn test_stats() {
1002        let (storage, _temp) = create_test_storage().await;
1003
1004        let content1 = b"content 1";
1005        let content2 = b"content 2";
1006        let address1 = LmdbStorage::compute_address(content1);
1007        let address2 = LmdbStorage::compute_address(content2);
1008
1009        // Store two chunks
1010        storage.put(&address1, content1).await.expect("put 1");
1011        storage.put(&address2, content2).await.expect("put 2");
1012
1013        // Retrieve one
1014        storage.get(&address1).await.expect("get");
1015
1016        let stats = storage.stats();
1017        assert_eq!(stats.chunks_stored, 2);
1018        assert_eq!(stats.chunks_retrieved, 1);
1019        assert_eq!(
1020            stats.bytes_stored,
1021            content1.len() as u64 + content2.len() as u64
1022        );
1023        assert_eq!(stats.bytes_retrieved, content1.len() as u64);
1024        assert_eq!(stats.current_chunks, 2);
1025    }
1026
1027    #[tokio::test]
1028    async fn test_persistence_across_reopen() {
1029        let temp_dir = TempDir::new().expect("create temp dir");
1030        let content = b"persistent data";
1031        let address = LmdbStorage::compute_address(content);
1032
1033        // Store a chunk
1034        {
1035            let config = LmdbStorageConfig {
1036                root_dir: temp_dir.path().to_path_buf(),
1037                ..LmdbStorageConfig::test_default()
1038            };
1039            let storage = LmdbStorage::new(config).await.expect("create storage");
1040            storage.put(&address, content).await.expect("put");
1041        }
1042
1043        // Re-open and verify it persisted
1044        {
1045            let config = LmdbStorageConfig {
1046                root_dir: temp_dir.path().to_path_buf(),
1047                ..LmdbStorageConfig::test_default()
1048            };
1049            let storage = LmdbStorage::new(config).await.expect("reopen storage");
1050            assert_eq!(storage.current_chunks().expect("current_chunks"), 1);
1051            let retrieved = storage.get(&address).await.expect("get");
1052            assert_eq!(retrieved, Some(content.to_vec()));
1053        }
1054    }
1055
1056    #[tokio::test]
1057    async fn test_all_keys() {
1058        let (storage, _temp) = create_test_storage().await;
1059
1060        // Empty storage
1061        let keys = storage.all_keys().await.expect("all_keys empty");
1062        assert!(keys.is_empty());
1063
1064        // Store some chunks
1065        let content1 = b"chunk one for keys";
1066        let content2 = b"chunk two for keys";
1067        let addr1 = LmdbStorage::compute_address(content1);
1068        let addr2 = LmdbStorage::compute_address(content2);
1069        storage.put(&addr1, content1).await.expect("put 1");
1070        storage.put(&addr2, content2).await.expect("put 2");
1071
1072        let mut keys = storage.all_keys().await.expect("all_keys");
1073        keys.sort_unstable();
1074        let mut expected = vec![addr1, addr2];
1075        expected.sort_unstable();
1076        assert_eq!(keys, expected);
1077    }
1078
1079    #[tokio::test]
1080    async fn test_get_raw() {
1081        let (storage, _temp) = create_test_storage().await;
1082
1083        let content = b"raw test data";
1084        let address = LmdbStorage::compute_address(content);
1085        storage.put(&address, content).await.expect("put");
1086
1087        // get_raw returns bytes without verification
1088        let raw = storage.get_raw(&address).await.expect("get_raw");
1089        assert_eq!(raw, Some(content.to_vec()));
1090
1091        // Non-existent key
1092        let missing = storage.get_raw(&[0xFF; 32]).await.expect("get_raw missing");
1093        assert!(missing.is_none());
1094    }
1095}