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