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