cache2 0.4.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
// 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;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

use tokio::task::JoinError;

use crate::config::CacheConfig;
use crate::config::storage::KEY_HASH_SEED;
use crate::config::storage_fingerprint;
use crate::config::storage_geometry;
use crate::error::Error;
use crate::error::ErrorOperation;
use crate::error::from_io;
use crate::region::file_backend::FileRegionBackend;
use crate::region::file_backend::RegionFiles;
use crate::region::file_backend::SystemRegionFileSystem;
use crate::region::recovery::DataSuperblock;
use crate::region::recovery::PersistentId;
use crate::region::recovery::RECOVERY_IMAGE_INDEX_OFFSET;
use crate::region::recovery::recovery_image_index_len;
use crate::region::runtime::HybridValueRead;
use crate::region::runtime::RegionDataPlane;
use crate::region::store::RegionStore;
use crate::snapshot::CacheSnapshot;
use crate::snapshot::DetailedCacheSnapshot;
use crate::snapshot::StartupMode;

/// 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 {
    /// Opens a configured cache using the current Tokio runtime at first poll.
    /// The runtime must have time enabled and outlive the cache. File setup and
    /// recovery run on its blocking pool.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorOperation::Open`] for file locking, recovery, allocation,
    /// device support, runtime binding, or worker startup failures. Configuration
    /// has already been checked by [`CacheConfig::new`].
    pub async fn open(path: impl AsRef<Path>, config: CacheConfig) -> Result<Self, Error> {
        let handle = tokio::runtime::Handle::try_current().map_err(|error| {
            from_io(
                ErrorOperation::Open,
                io::Error::new(io::ErrorKind::InvalidInput, error.to_string()),
            )
        })?;
        Self::open_with_handle(path, config, handle).await
    }

    /// Opens on an explicit Tokio runtime, including from a caller without an
    /// active runtime. The selected runtime must have time enabled and outlive
    /// the cache. Each open independently locks files and acquires resources.
    ///
    /// # Errors
    ///
    /// Uses the same [`ErrorOperation::Open`] failures as [`Self::open`].
    pub async fn open_with_handle(
        path: impl AsRef<Path>,
        config: CacheConfig,
        tokio_handle: tokio::runtime::Handle,
    ) -> Result<Self, Error> {
        let path = path.as_ref().to_path_buf();
        let cache_handle = tokio_handle.clone();
        let started = Instant::now();
        let result = tokio_handle
            .spawn_blocking(move || Self::open_blocking(path, config, cache_handle, started))
            .await
            .map_err(|error| {
                from_io(
                    ErrorOperation::Open,
                    blocking_task_error("cache open", error),
                )
            })?;
        public_result(ErrorOperation::Open, result)
    }

    fn open_blocking(
        path: PathBuf,
        config: CacheConfig,
        tokio_handle: tokio::runtime::Handle,
        started: Instant,
    ) -> io::Result<Cache> {
        let capacity_bytes = config.storage().capacity_bytes();
        let index_slots = config.storage().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(path.clone(), config, 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(
        path: PathBuf,
        config: CacheConfig,
        tokio_handle: tokio::runtime::Handle,
    ) -> io::Result<Cache> {
        let format_data = DataSuperblock {
            generation: 1,
            cache_uuid: next_persistent_id(),
            data_identity: next_persistent_id(),
            geometry: storage_geometry(config.storage()),
            hash_seed: KEY_HASH_SEED,
            config_fingerprint: storage_fingerprint(config.storage()),
        };
        let files = RegionFiles::new(
            &path,
            sidecar_path(&path, ".state"),
            sidecar_path(&path, ".image"),
        );
        let index_slots = config.storage().index_slots();
        let logical_disk_peak_bytes = config.storage().peak_disk_bytes();
        let backend = FileRegionBackend::new(files, format_data, config);
        let store = RegionStore::open(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,
            logical_disk_peak_bytes,
            tokio_handle,
        })
    }
    /// 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 [`ErrorKind::InvalidInput`](crate::ErrorKind::InvalidInput) for an oversized key or
    /// record and [`ErrorKind::Overloaded`](crate::ErrorKind::Overloaded) when bounded mutation
    /// admission is busy. Returns [`ErrorKind::Unavailable`](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, Error> {
        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
    /// [`ErrorOperation::PutL2`](crate::ErrorOperation::PutL2) as its context.
    pub fn put_l2(&self, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>) -> Result<u64, Error> {
        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 [`ErrorKind::InvalidInput`](crate::ErrorKind::InvalidInput) for an oversized key and
    /// [`ErrorKind::Overloaded`](crate::ErrorKind::Overloaded) when bounded mutation admission is
    /// busy. Returns [`ErrorKind::Unavailable`](crate::ErrorKind::Unavailable) after close starts.
    /// Runtime and device failures remain explicit.
    pub fn delete(&self, key: impl AsRef<[u8]>) -> Result<u64, Error> {
        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 [`ErrorKind::Overloaded`](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>, Error> {
        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 [`ErrorKind::Overloaded`](crate::ErrorKind::Overloaded) if another drain is active,
    /// or [`ErrorKind::Unavailable`](crate::ErrorKind::Unavailable) after close starts.
    /// Accepted work that cannot complete returns a structured runtime/device failure.
    pub async fn drain(&self) -> Result<(), Error> {
        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 [`ErrorKind::Unavailable`](crate::ErrorKind::Unavailable) after close starts, or a
    /// structured runtime failure if the snapshot cannot be read.
    pub fn snapshot(&self) -> Result<CacheSnapshot, Error> {
        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 [`ErrorKind::Unavailable`](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, Error> {
        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 [`ErrorKind::Unavailable`](crate::ErrorKind::Unavailable) if close already started,
    /// or a structured runtime, worker, or filesystem failure with
    /// [`ErrorOperation::CloseFast`](crate::ErrorOperation::CloseFast).
    pub fn close_fast(&self) -> impl Future<Output = Result<(), Error>> + 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 [`ErrorKind::Unavailable`](crate::ErrorKind::Unavailable) if close already started,
    /// or a structured runtime, worker, filesystem, or device failure with
    /// [`ErrorOperation::CloseWarm`](crate::ErrorOperation::CloseWarm). A failed warm close does
    /// not publish a recoverable image.
    pub fn close_warm(&self) -> impl Future<Output = Result<(), Error>> + Send + 'static {
        self.close(true)
    }

    #[inline(always)]
    fn ensure_open(&self, operation: ErrorOperation) -> Result<(), Error> {
        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<(), Error>> + 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: 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 public_result<T>(operation: ErrorOperation, result: io::Result<T>) -> Result<T, Error> {
    result.map_err(|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>();
    }
}