cache2 0.3.0

Performance-first bounded RAM and NVMe hybrid cache
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
// Copyright 2026 ScopeDB, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Public cache API and configuration.
//!
//! Static configuration defines disk identity; runtime configuration is chosen
//! per open. `close_warm` publishes recoverable state.

use std::fmt;
use std::future::Future;
use std::io;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use crate::error::{Error, ErrorOperation, Result};
use crate::index::{MAX_PACKED_REGION_COUNT, MAX_PACKED_REGION_SIZE};
use crate::index_storage::{
    IndexStorageError, canonical_index_partition_ranges, validate_index_slot_count,
};
use crate::recovery::{
    DataGeometry, DataSuperblock, KEY_HASH_ALGORITHM_XXH3_64, PersistentId,
    RECOVERY_IMAGE_INDEX_OFFSET, STATE_FILE_SIZE, recovery_image_index_len,
};
use crate::region::{FileRegionBackend, RegionFiles, SystemRegionFileSystem};
use crate::region_metadata::{
    REGION_METADATA_PAGE_SIZE, REGION_METADATA_PARTITIONS_PER_PAGE,
    REGION_METADATA_REGIONS_PER_PAGE,
};
use crate::region_runtime::{HybridValueRead, RegionDataPlane};
use crate::region_store::RegionStore;
use crate::runtime_config::RuntimeConfig;
use crate::snapshot::{CacheSnapshot, DetailedCacheSnapshot, StartupMode};

const DEFAULT_REGION_SIZE: u64 = 32 * 1024 * 1024;
const DEFAULT_EXPECTED_ENTRY_BYTES: u64 = 16 * 1024;
const KEY_HASH_SEED: u64 = 0x6a09_e667_f3bc_c909;
const MIN_INDEX_SLOTS: usize = 8;
const STATIC_FINGERPRINT_SCHEMA: u64 = 3;

/// Persistent L2 geometry and fixed-index sizing.
///
/// These values define the static disk identity. A clean image created with a
/// different static configuration is discarded and the cache starts empty.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StaticConfig {
    capacity_bytes: u64,
    region_size_bytes: u64,
    index_slots: usize,
}

impl StaticConfig {
    /// Creates static L2 geometry and sizes its index assuming an average
    /// 16 KiB live entry.
    ///
    /// `capacity_bytes` is the total Region extent, excluding the data
    /// superblock, state, and clean-image files. The default Region size is
    /// 32 MiB. Index size grows with capacity and is accepted when its complete
    /// page and mapping layout is representable. Use
    /// [`Self::with_expected_entries`] when the live-key count is known, and use
    /// [`Self::peak_disk_bytes`] for the cache-owned logical disk bound.
    pub fn new(capacity_bytes: u64) -> Self {
        let expected_entries = capacity_bytes / DEFAULT_EXPECTED_ENTRY_BYTES;
        let index_slots = usize::try_from(
            expected_entries
                .saturating_mul(2)
                .max(MIN_INDEX_SLOTS as u64),
        )
        .unwrap_or(usize::MAX);
        Self {
            capacity_bytes,
            region_size_bytes: DEFAULT_REGION_SIZE,
            index_slots,
        }
    }

    /// Sets the Region size in bytes.
    ///
    /// Valid sizes are 4 KiB multiples through 32 MiB. L2 capacity is an exact
    /// multiple containing at least two Regions. A complete encoded record fits
    /// in one Region. Every append shard eagerly owns two Region-sized staging
    /// buffers.
    pub fn with_region_size_bytes(mut self, bytes: u64) -> Self {
        self.region_size_bytes = bytes;
        self
    }

    /// Sizes the fixed L2 index for the expected number of simultaneously live
    /// keys.
    ///
    /// This counts simultaneously live keys. The resulting index uses roughly
    /// two physical buckets per expected live key and is part of the static disk
    /// identity.
    pub fn with_expected_entries(mut self, entries: usize) -> Self {
        self.index_slots = entries.saturating_mul(2).max(MIN_INDEX_SLOTS);
        self
    }

    /// Returns the total Region extent in bytes.
    pub const fn capacity_bytes(&self) -> u64 {
        self.capacity_bytes
    }

    /// Returns the Region size in bytes.
    pub const fn region_size_bytes(&self) -> u64 {
        self.region_size_bytes
    }

    /// Returns the fixed number of physical L2 index slots.
    pub const fn index_slots(&self) -> usize {
        self.index_slots
    }

    /// Validates the static physical geometry before opening cache files.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::InvalidInput`] when the capacity, Region
    /// geometry, or index size is not representable.
    pub fn validate(&self) -> Result<()> {
        public_result(ErrorOperation::ValidateConfig, self.geometry().map(|_| ()))
    }

    /// Maximum cache-owned logical disk bytes after a successful open.
    ///
    /// The bound includes the fixed data and state files plus both the current
    /// clean image and the temporary image used for atomic warm publication.
    /// Filesystem metadata and block-allocation granularity are outside it.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::InvalidInput`] when the static geometry is
    /// invalid or its disk bound overflows.
    pub fn peak_disk_bytes(&self) -> Result<u64> {
        public_result(ErrorOperation::PeakDiskBytes, self.peak_disk_bytes_inner())
    }

    fn peak_disk_bytes_inner(&self) -> io::Result<u64> {
        let geometry = self.geometry()?;
        let index_slots = u64::try_from(self.index_slots)
            .map_err(|_| invalid_config("index capacity does not fit u64"))?;
        let index_len = recovery_image_index_len(index_slots)
            .ok_or_else(|| invalid_config("index image length overflow"))?;
        let partition_count = u64::try_from(
            canonical_index_partition_ranges(self.index_slots)
                .map_err(index_layout_error)?
                .len(),
        )
        .map_err(|_| invalid_config("index partition count does not fit u64"))?;
        let region_pages =
            u64::from(geometry.region_count).div_ceil(REGION_METADATA_REGIONS_PER_PAGE as u64);
        let partition_pages = partition_count.div_ceil(REGION_METADATA_PARTITIONS_PER_PAGE as u64);
        let metadata_len = 1_u64
            .checked_add(region_pages)
            .and_then(|pages| pages.checked_add(partition_pages))
            .and_then(|pages| pages.checked_mul(REGION_METADATA_PAGE_SIZE as u64))
            .ok_or_else(|| invalid_config("Region metadata length overflow"))?;
        let image_len = RECOVERY_IMAGE_INDEX_OFFSET
            .checked_add(index_len)
            .and_then(|bytes| bytes.checked_add(metadata_len))
            .ok_or_else(|| invalid_config("recovery image length overflow"))?;
        geometry
            .data_file_len
            .checked_add(STATE_FILE_SIZE as u64)
            .and_then(|bytes| bytes.checked_add(image_len.checked_mul(2)?))
            .ok_or_else(|| invalid_config("peak disk usage overflow"))
    }

    fn geometry(&self) -> io::Result<DataGeometry> {
        if self.region_size_bytes == 0
            || self.region_size_bytes > MAX_PACKED_REGION_SIZE
            || !self.region_size_bytes.is_multiple_of(4096)
            || self.capacity_bytes == 0
            || !self.capacity_bytes.is_multiple_of(self.region_size_bytes)
        {
            return Err(invalid_config(
                "capacity must be a non-zero multiple of an aligned representable Region size",
            ));
        }
        let region_count = u32::try_from(self.capacity_bytes / self.region_size_bytes)
            .ok()
            .filter(|count| *count <= MAX_PACKED_REGION_COUNT)
            .ok_or_else(|| invalid_config("cache Region count is not representable"))?;
        if region_count < 2 {
            return Err(invalid_config("cache requires at least two Regions"));
        }
        if self.index_slots < MIN_INDEX_SLOTS {
            return Err(invalid_config("index slots must be at least 8"));
        }
        validate_index_slot_count(self.index_slots).map_err(index_layout_error)?;
        let data_file_len = DataGeometry::expected_file_len(self.region_size_bytes, region_count)
            .ok_or_else(|| invalid_config("cache data length overflow"))?;
        let geometry = DataGeometry {
            data_file_len,
            region_size: self.region_size_bytes,
            region_count,
        };
        if !geometry.is_valid() {
            return Err(invalid_config("cache data geometry is not representable"));
        }
        Ok(geometry)
    }

    fn fingerprint(&self, geometry: DataGeometry) -> u64 {
        self.fingerprint_with_hash_algorithm(geometry, u64::from(KEY_HASH_ALGORITHM_XXH3_64))
    }

    fn fingerprint_with_hash_algorithm(
        &self,
        geometry: DataGeometry,
        hash_algorithm_id: u64,
    ) -> u64 {
        let mut hash = 0xcbf2_9ce4_8422_2325_u64;
        for value in [
            STATIC_FINGERPRINT_SCHEMA,
            geometry.data_file_len,
            geometry.region_size,
            u64::from(geometry.region_count),
            self.index_slots as u64,
            KEY_HASH_SEED,
            hash_algorithm_id,
        ] {
            for byte in value.to_le_bytes() {
                hash ^= u64::from(byte);
                hash = hash.wrapping_mul(0x100_0000_01b3);
            }
        }
        hash.max(1)
    }
}

/// Builder that combines a cache path, static geometry, runtime tuning, and a
/// Tokio runtime binding before opening a [`Cache`].
#[derive(Clone, Debug)]
pub struct CacheBuilder {
    path: PathBuf,
    static_config: StaticConfig,
    runtime_config: RuntimeConfig,
    tokio_handle: Option<tokio::runtime::Handle>,
}

impl CacheBuilder {
    /// Creates a builder using default static and runtime tuning.
    ///
    /// The L2 index is sized for 16 KiB live entries. Use
    /// [`Self::from_static`] when Region or index geometry must be explicit.
    pub fn new(path: impl AsRef<Path>, capacity_bytes: u64) -> Self {
        Self::from_static(path, StaticConfig::new(capacity_bytes))
    }

    /// Creates a cache builder from a complete static configuration.
    pub fn from_static(path: impl AsRef<Path>, static_config: StaticConfig) -> Self {
        Self {
            path: path.as_ref().to_path_buf(),
            static_config,
            runtime_config: RuntimeConfig::default(),
            tokio_handle: None,
        }
    }

    /// Replaces the process-local runtime tuning used by [`Self::open`].
    pub fn with_runtime_config(mut self, config: RuntimeConfig) -> Self {
        self.runtime_config = config;
        self
    }

    /// Uses a specific Tokio runtime for blocking lifecycle work and L2 read
    /// deadlines. The runtime must have time enabled and outlive the cache.
    pub fn with_tokio_handle(mut self, handle: tokio::runtime::Handle) -> Self {
        self.tokio_handle = Some(handle);
        self
    }

    /// Opens the cache on Tokio's blocking pool because recovery and file setup
    /// use blocking filesystem operations. The default captures the current
    /// Tokio runtime when the future is first polled.
    ///
    /// # Errors
    ///
    /// Returns a structured [`crate::Error`] with
    /// [`crate::ErrorOperation::Open`]. Invalid or unsupported configuration is
    /// rejected before file creation; [`crate::ErrorKind::Busy`] means another
    /// owner holds the cache files. Allocation, filesystem, device, and worker
    /// startup failures retain their underlying [`io::Error`].
    pub async fn open(self) -> Result<Cache> {
        let tokio_handle = match self.tokio_handle.clone() {
            Some(handle) => handle,
            None => tokio::runtime::Handle::try_current().map_err(|error| {
                Error::from_io(
                    ErrorOperation::Open,
                    io::Error::new(io::ErrorKind::InvalidInput, error.to_string()),
                )
            })?,
        };
        let cache_handle = tokio_handle.clone();
        let started = Instant::now();
        let result = tokio_handle
            .spawn_blocking(move || self.open_blocking(cache_handle, started))
            .await
            .map_err(|error| {
                Error::from_io(
                    ErrorOperation::Open,
                    blocking_task_error("cache open", error),
                )
            })?;
        public_result(ErrorOperation::Open, result)
    }

    fn open_blocking(
        self,
        tokio_handle: tokio::runtime::Handle,
        started: Instant,
    ) -> io::Result<Cache> {
        let path = self.path.clone();
        let capacity_bytes = self.static_config.capacity_bytes;
        let index_slots = self.static_config.index_slots;
        let index_bytes = u64::try_from(index_slots)
            .ok()
            .and_then(recovery_image_index_len)
            .unwrap_or(0);
        let result = self.open_blocking_inner(tokio_handle);
        match &result {
            Ok(cache) => {
                let startup = cache.startup_mode();
                log::info!(
                    target: "cache2::lifecycle",
                    event = "cache_opened",
                    path:% = path.display(),
                    startup = startup_name(startup),
                    index_backing = index_backing_name(startup),
                    index_validation = index_validation_name(startup),
                    index_copy_on_write = matches!(startup, StartupMode::Warm),
                    capacity_bytes,
                    index_slots,
                    index_mapping_bytes = index_mapping_bytes(startup, index_bytes),
                    elapsed_us = elapsed_micros(started.elapsed());
                    "cache opened"
                );
            }
            Err(error) => log::error!(
                target: "cache2::lifecycle",
                event = "cache_open_failed",
                path:% = path.display(),
                capacity_bytes,
                index_slots,
                elapsed_us = elapsed_micros(started.elapsed()),
                error:% = error;
                "cache open failed"
            ),
        }
        result
    }

    fn open_blocking_inner(self, tokio_handle: tokio::runtime::Handle) -> io::Result<Cache> {
        let geometry = self.static_config.geometry()?;
        let logical_disk_peak_bytes = self.static_config.peak_disk_bytes_inner()?;
        let runtime_config = self.runtime_config;
        runtime_config.validate()?;
        if geometry.region_count <= runtime_config.append_shards {
            return Err(invalid_config(
                "append shards require one Active Region each plus one spare Region",
            ));
        }
        runtime_config.validate_memory_plan(
            geometry,
            self.static_config.index_slots,
            runtime_config.append_shards as usize,
        )?;
        let format_data = DataSuperblock {
            generation: 1,
            cache_uuid: next_persistent_id(),
            data_identity: next_persistent_id(),
            geometry,
            hash_seed: KEY_HASH_SEED,
            config_fingerprint: self.static_config.fingerprint(geometry),
        };
        let files = RegionFiles::new(
            &self.path,
            sidecar_path(&self.path, ".state"),
            sidecar_path(&self.path, ".image"),
        );
        let backend = FileRegionBackend::new_with_configs(
            files,
            format_data,
            runtime_config.append_shards,
            runtime_config,
        );
        let store = RegionStore::open(self.static_config.index_slots, backend)?;
        let startup = store.startup();
        let data_plane = store.data_plane_handle()?;
        Ok(Cache {
            closed: AtomicBool::new(false),
            data_plane,
            owner: Arc::new(Mutex::new(store)),
            startup,
            path: self.path,
            logical_disk_peak_bytes,
            tokio_handle,
        })
    }
}

/// Storage tier that backs a returned [`Value`].
///
/// This describes the value's backing after the lookup completes, not
/// necessarily the tier where the lookup began. A successful L2 promotion is
/// therefore backed by L1.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CacheTier {
    /// Process-local in-memory storage.
    L1,
    /// A transient buffer read from the Region store.
    L2,
}

/// Owned cache value returned by [`Cache::get`].
///
/// The value dereferences to its bytes and keeps its L1 or transient L2
/// backing alive until it is dropped.
pub struct Value {
    inner: HybridValueRead,
}

impl Deref for Value {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        self.inner.value()
    }
}

impl AsRef<[u8]> for Value {
    fn as_ref(&self) -> &[u8] {
        self
    }
}

impl Value {
    /// Returns the storage tier backing this value.
    ///
    /// A Region hit successfully promoted before return reports
    /// [`CacheTier::L1`]; hit counters still record it as an L2 hit.
    pub const fn tier(&self) -> CacheTier {
        if self.inner.is_l1() {
            CacheTier::L1
        } else {
            CacheTier::L2
        }
    }
}

/// An open cache bound to one Tokio runtime.
///
/// Prefer [`Self::close_fast`] or [`Self::close_warm`] for async shutdown.
/// Either close method can be called through a shared [`Arc`] and immediately
/// makes every surviving handle inert; unique ownership is not required.
/// Dropping an open cache is a synchronous fast close and may block the thread
/// performing the drop while accepted work is fenced.
pub struct Cache {
    // Keep public reads off the write-mutated admission counter's cache line.
    closed: AtomicBool,
    data_plane: RegionDataPlane,
    owner: Arc<Mutex<RegionStore<FileRegionBackend<SystemRegionFileSystem>>>>,
    startup: StartupMode,
    path: PathBuf,
    logical_disk_peak_bytes: u64,
    tokio_handle: tokio::runtime::Handle,
}

impl fmt::Debug for Cache {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Cache")
            .field("startup", &self.startup_mode())
            .finish_non_exhaustive()
    }
}

impl Cache {
    /// Reports whether this open started empty or mapped a clean recovery image.
    pub const fn startup_mode(&self) -> StartupMode {
        self.startup
    }

    /// Stores a value and returns its monotonic mutation sequence.
    ///
    /// Keys are limited to 4 KiB. The complete encoded record must fit in one
    /// Region; the Region fit determines the value limit.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::InvalidInput`] for an oversized key or
    /// record and [`crate::ErrorKind::Overloaded`] when bounded mutation
    /// admission is busy. Returns [`crate::ErrorKind::Unavailable`] after close
    /// starts. Runtime and device failures use their corresponding structured
    /// classifications.
    pub fn put(&self, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>) -> Result<u64> {
        self.ensure_open(ErrorOperation::Put)?;
        public_result(
            ErrorOperation::Put,
            self.data_plane.put(key.as_ref(), value.as_ref()),
        )
    }

    /// Stages a value directly for L2 and returns its monotonic mutation
    /// sequence.
    ///
    /// An older L1 value is removed best effort. Success means the value entered
    /// bounded staging; use [`Self::drain`] to wait for L2 publication. Keys are
    /// limited to 4 KiB, and the encoded record must fit one Region.
    ///
    /// # Errors
    ///
    /// Uses the same input, overload, runtime, and device classifications as
    /// [`Self::put`], including unavailable after close starts, with
    /// [`crate::ErrorOperation::PutL2`] as its context.
    pub fn put_l2(&self, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>) -> Result<u64> {
        self.ensure_open(ErrorOperation::PutL2)?;
        public_result(
            ErrorOperation::PutL2,
            self.data_plane.put_l2(key.as_ref(), value.as_ref()),
        )
    }

    /// Deletes a key and returns its monotonic mutation sequence.
    ///
    /// This removes the L2 mapping and cleans L1 best effort using bounded
    /// in-memory work. Keys are limited to 4 KiB.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::InvalidInput`] for an oversized key and
    /// [`crate::ErrorKind::Overloaded`] when bounded mutation admission is
    /// busy. Returns [`crate::ErrorKind::Unavailable`] after close starts.
    /// Runtime and device failures remain explicit.
    pub fn delete(&self, key: impl AsRef<[u8]>) -> Result<u64> {
        self.ensure_open(ErrorOperation::Delete)?;
        public_result(ErrorOperation::Delete, self.data_plane.delete(key.as_ref()))
    }

    /// Looks up a value in L1 and then L2.
    ///
    /// An L2 candidate performs at most one bounded, locally validated record
    /// read. By default, memory or I/O pressure is a miss. With read waiting
    /// enabled, queue, memory, or timeout pressure is an overload error. A key
    /// longer than 4 KiB is also a miss.
    ///
    /// Once close starts, every lookup returns a miss.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::Overloaded`] for explicit read pressure when
    /// waiting is enabled. Cache data and device failures that can safely fail
    /// open transition reads to misses instead of surfacing an application
    /// error.
    pub async fn get(&self, key: impl AsRef<[u8]> + Send) -> Result<Option<Value>> {
        if self.is_closed() {
            return Ok(None);
        }
        public_result(
            ErrorOperation::Get,
            self.data_plane
                .get_async(key.as_ref(), &self.tokio_handle)
                .await,
        )
        .map(|value| value.map(|inner| Value { inner }))
    }

    /// Waits until all accepted mutations have completed their Region writes
    /// and index publication. Use [`Self::close_warm`] to publish a recoverable
    /// image.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::Overloaded`] if another drain is active, or
    /// [`crate::ErrorKind::Unavailable`] after close starts. Accepted work that
    /// cannot complete returns a structured runtime/device failure.
    pub async fn drain(&self) -> Result<()> {
        self.ensure_open(ErrorOperation::Drain)?;
        public_result(ErrorOperation::Drain, self.data_plane.drain_async().await)
    }

    /// Returns a lock-free operational snapshot. Activity and I/O counters are
    /// cumulative for this open and are populated only when statistics are
    /// enabled; health and resource gauges are always available.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::Unavailable`] after close starts, or a
    /// structured runtime failure if the snapshot cannot be read.
    pub fn snapshot(&self) -> Result<CacheSnapshot> {
        self.ensure_open(ErrorOperation::Snapshot)?;
        let mut snapshot = public_result(ErrorOperation::Snapshot, self.data_plane.snapshot())?;
        snapshot.logical_disk_peak_bytes = self.logical_disk_peak_bytes;
        Ok(snapshot)
    }

    /// Samples L1, index, write-buffer rejection, I/O, and Region state in
    /// addition to the regular cache summary. This periodic diagnostic briefly
    /// reads every configured L1 shard and index partition and scans Region
    /// metadata. Sampling is limited to metadata.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::Unavailable`] after close starts, or a
    /// structured runtime failure if any diagnostic partition cannot be
    /// sampled.
    pub fn detailed_snapshot(&self) -> Result<DetailedCacheSnapshot> {
        self.ensure_open(ErrorOperation::DetailedSnapshot)?;
        let mut snapshot = public_result(
            ErrorOperation::DetailedSnapshot,
            self.data_plane.detailed_snapshot(),
        )?;
        snapshot.summary.logical_disk_peak_bytes = self.logical_disk_peak_bytes;
        Ok(snapshot)
    }

    /// Stops on Tokio's blocking pool and makes the next open a cold start.
    /// Calling this method immediately rejects new operations through every
    /// shared handle; unique [`Arc`] ownership is not required. The first close
    /// call wins and continues even if the returned future is dropped.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::Unavailable`] if close already started, or a
    /// structured runtime, worker, or filesystem failure with
    /// [`crate::ErrorOperation::CloseFast`].
    pub fn close_fast(&self) -> impl Future<Output = Result<()>> + Send + 'static {
        self.close(false)
    }

    /// Publishes a clean recovery image on Tokio's blocking pool. Calling this
    /// method immediately rejects new operations through every shared handle;
    /// unique [`Arc`] ownership is not required. Accepted mutations and their
    /// submitted writes are fenced before the image is frozen. The first close
    /// call wins and continues even if the returned future is dropped.
    ///
    /// # Errors
    ///
    /// Returns [`crate::ErrorKind::Unavailable`] if close already started, or a
    /// structured runtime, worker, filesystem, or device failure with
    /// [`crate::ErrorOperation::CloseWarm`]. A failed warm close does not
    /// publish a recoverable image.
    pub fn close_warm(&self) -> impl Future<Output = Result<()>> + Send + 'static {
        self.close(true)
    }

    #[inline(always)]
    fn ensure_open(&self, operation: ErrorOperation) -> Result<()> {
        if self.is_closed() {
            return public_result(operation, Err(cache_closed_error()));
        }
        Ok(())
    }

    #[inline(always)]
    fn is_closed(&self) -> bool {
        self.closed.load(Ordering::Acquire)
    }

    fn close(&self, warm: bool) -> impl Future<Output = Result<()>> + Send + 'static {
        let (operation, mode) = if warm {
            (ErrorOperation::CloseWarm, "warm")
        } else {
            (ErrorOperation::CloseFast, "fast")
        };
        let tokio_handle = self.tokio_handle.clone();
        let close = (!self.closed.swap(true, Ordering::AcqRel)).then(|| {
            self.data_plane.start_close();
            let owner = Arc::clone(&self.owner);
            let path = self.path.clone();
            let started = Instant::now();
            tokio_handle.spawn_blocking(move || {
                let result = owner
                    .lock()
                    .map_err(|_| cache_lifecycle_poisoned())
                    .and_then(|mut store| {
                        if warm {
                            store.close_warm()
                        } else {
                            store.close_fast()
                        }
                    });
                log_cache_close(&path, mode, started.elapsed(), &result);
                result
            })
        });
        async move {
            let result = match close {
                Some(close) => match close.await {
                    Ok(result) => result,
                    Err(error) => Err(blocking_task_error("cache close", error)),
                },
                None => Err(cache_closed_error()),
            };
            public_result(operation, result)
        }
    }
}

fn cache_closed_error() -> io::Error {
    io::Error::new(io::ErrorKind::NotConnected, "cache is closing or closed")
}

fn cache_lifecycle_poisoned() -> io::Error {
    io::Error::new(
        io::ErrorKind::InvalidData,
        "cache lifecycle synchronization is poisoned",
    )
}

fn startup_name(startup: StartupMode) -> &'static str {
    match startup {
        StartupMode::Cold => "cold",
        StartupMode::Warm => "warm",
    }
}

fn index_backing_name(startup: StartupMode) -> &'static str {
    match startup {
        StartupMode::Cold => anonymous_index_backing_name(),
        StartupMode::Warm => "file_private_mmap",
    }
}

const fn anonymous_index_backing_name() -> &'static str {
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    {
        "anonymous_mmap"
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        "heap"
    }
}

fn index_validation_name(startup: StartupMode) -> &'static str {
    match startup {
        StartupMode::Cold => "not_required",
        StartupMode::Warm => "lazy_crc32c",
    }
}

fn index_mapping_bytes(startup: StartupMode, index_bytes: u64) -> u64 {
    match startup {
        StartupMode::Cold => index_bytes,
        StartupMode::Warm => RECOVERY_IMAGE_INDEX_OFFSET.saturating_add(index_bytes),
    }
}

fn elapsed_micros(elapsed: Duration) -> u64 {
    u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX)
}

fn log_cache_close(path: &Path, mode: &'static str, elapsed: Duration, result: &io::Result<()>) {
    match result {
        Ok(()) => log::info!(
            target: "cache2::lifecycle",
            event = "cache_closed",
            path:% = path.display(),
            mode,
            elapsed_us = elapsed_micros(elapsed);
            "cache closed"
        ),
        Err(error) => log::error!(
            target: "cache2::lifecycle",
            event = "cache_close_failed",
            path:% = path.display(),
            mode,
            elapsed_us = elapsed_micros(elapsed),
            error:% = error;
            "cache close failed"
        ),
    }
}

fn blocking_task_error(operation: &'static str, error: tokio::task::JoinError) -> io::Error {
    io::Error::other(format!("{operation} task failed: {error}"))
}

fn sidecar_path(path: &Path, suffix: &str) -> PathBuf {
    let mut value = path.as_os_str().to_owned();
    value.push(suffix);
    PathBuf::from(value)
}

fn invalid_config(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, message)
}

fn index_layout_error(error: IndexStorageError) -> io::Error {
    match error {
        IndexStorageError::Io(error) => error,
        error => io::Error::new(io::ErrorKind::InvalidInput, error),
    }
}

fn public_result<T>(operation: ErrorOperation, result: io::Result<T>) -> Result<T> {
    result.map_err(|error| Error::from_io(operation, error))
}

fn next_persistent_id() -> PersistentId {
    static NEXT_ID: AtomicU64 = AtomicU64::new(1);
    let counter = NEXT_ID.fetch_add(1, Ordering::Relaxed);
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let mut bytes = now.to_le_bytes();
    let mix = counter ^ u64::from(std::process::id()).rotate_left(32);
    for (target, source) in bytes[8..].iter_mut().zip(mix.to_le_bytes()) {
        *target ^= source;
    }
    PersistentId::from_bytes(bytes).unwrap_or_else(|| {
        PersistentId::from_bytes(counter.max(1).to_le_bytes().repeat(2).try_into().unwrap())
            .expect("non-zero counter produces a cache identity")
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_send_sync<T: Send + Sync>() {}

    #[test]
    fn public_cache_and_values_are_send_and_sync() {
        assert_send_sync::<Cache>();
        assert_send_sync::<Value>();
    }

    #[test]
    fn static_fingerprint_binds_the_hash_algorithm() {
        let config = StaticConfig::new(5 * DEFAULT_REGION_SIZE);
        let geometry = config.geometry().unwrap();
        let algorithm = u64::from(KEY_HASH_ALGORITHM_XXH3_64);
        assert_eq!(
            config.fingerprint(geometry),
            config.fingerprint_with_hash_algorithm(geometry, algorithm)
        );
        assert_ne!(
            config.fingerprint(geometry),
            config.fingerprint_with_hash_algorithm(geometry, algorithm + 1)
        );
    }

    #[test]
    fn minimum_static_region_geometry_is_encodable() {
        let config = StaticConfig::new(5 * 4096).with_region_size_bytes(4096);
        config.validate().unwrap();
        let geometry = config.geometry().unwrap();
        let data = DataSuperblock {
            generation: 1,
            cache_uuid: PersistentId::from_bytes([1; 16]).unwrap(),
            data_identity: PersistentId::from_bytes([2; 16]).unwrap(),
            geometry,
            hash_seed: KEY_HASH_SEED,
            config_fingerprint: config.fingerprint(geometry),
        };
        assert!(data.encode().is_ok());
    }

    #[test]
    fn four_tib_default_index_matches_sixteen_kib_entries() {
        let config = StaticConfig::new(4_u64 << 40);

        assert_eq!(config.index_slots(), 536_870_912);
        config.validate().unwrap();
    }

    #[test]
    fn maximum_capacity_default_index_remains_proportional_and_representable() {
        let capacity = MAX_PACKED_REGION_SIZE * u64::from(MAX_PACKED_REGION_COUNT);
        let config = StaticConfig::new(capacity);

        assert_eq!(capacity, 32_u64 << 40);
        assert_eq!(config.index_slots(), 1_usize << 32);
        config.validate().unwrap();
        assert!(config.peak_disk_bytes().unwrap() > capacity);
    }

    #[test]
    fn unrepresentable_explicit_index_is_rejected_without_clamping() {
        let config = StaticConfig::new(2 * DEFAULT_REGION_SIZE).with_expected_entries(usize::MAX);

        assert_eq!(config.index_slots(), usize::MAX);
        assert!(config.validate().is_err());
    }

    #[test]
    fn index_layout_allocation_error_remains_out_of_memory() {
        let error = index_layout_error(IndexStorageError::Io(io::Error::new(
            io::ErrorKind::OutOfMemory,
            "injected allocation failure",
        )));

        assert_eq!(error.kind(), io::ErrorKind::OutOfMemory);
    }
}