Skip to main content

uqa_storage/
read_only_snapshot.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Read-only adapters retain storage-owned snapshots and forward every read capability.
8
9use std::sync::Arc;
10use uqa_core::memory::{Budgeted, MemoryReservation};
11
12use crate::StorageBackendError;
13
14mod canonical_vectors;
15mod documents;
16mod inverted;
17mod vectors;
18
19/// Adapt an already captured snapshot to an owned read-only handle without copying its contents. The caller must supply the snapshot selected for its visibility boundary; this adapter does not capture or advance that boundary.
20pub struct ReadOnlySnapshot<T: ?Sized>(
21    Arc<T>,
22    Option<Arc<MemoryReservation>>,
23    Option<crate::read_control::StorageReadControl>,
24    Option<crate::vector_index::VectorReadSnapshot>,
25);
26
27impl<T> ReadOnlySnapshot<T> {
28    /// Share a captured value without separating its allocations from their original allowance.
29    pub fn from_budgeted(snapshot: Budgeted<T>) -> crate::StorageBackendResult<Self> {
30        let mut pending = snapshot.into_parts();
31        let shared = pending.1.budget().reserve(size_of::<T>())?;
32        pending.1.absorb(shared);
33        Self::with_retention(Arc::new(pending.0), pending.1)
34    }
35}
36
37impl<T: ?Sized> ReadOnlySnapshot<T> {
38    #[must_use]
39    pub fn new(snapshot: Arc<T>) -> Self {
40        Self(snapshot, None, None, None)
41    }
42
43    pub(crate) fn with_retention(
44        snapshot: Arc<T>,
45        memory: MemoryReservation,
46    ) -> crate::StorageBackendResult<Self> {
47        // Keep the snapshot ahead of its lease on failure, including the shared lease allocation.
48        let mut pending = (snapshot, memory);
49        let shared = pending.1.budget().reserve(size_of::<MemoryReservation>())?;
50        pending.1.absorb(shared);
51        Ok(Self::with_shared_retention(pending.0, Arc::new(pending.1)))
52    }
53
54    /// The owning value can retain the same lease so direct owner snapshots cannot separate shared data from its allowance.
55    pub(crate) fn with_shared_retention(snapshot: Arc<T>, memory: Arc<MemoryReservation>) -> Self {
56        Self(snapshot, Some(memory), None, None)
57    }
58}
59
60impl<T: ?Sized> Clone for ReadOnlySnapshot<T> {
61    fn clone(&self) -> Self {
62        Self(
63            Arc::clone(&self.0),
64            self.1.as_ref().map(Arc::clone),
65            self.2.clone(),
66            self.3.clone(),
67        )
68    }
69}
70
71impl<T: ?Sized> std::ops::Deref for ReadOnlySnapshot<T> {
72    type Target = T;
73
74    fn deref(&self) -> &T {
75        &self.0
76    }
77}
78
79fn read_only_error() -> StorageBackendError {
80    StorageBackendError::Other("cannot write a retained storage snapshot".into())
81}
82
83#[cfg(test)]
84mod tests;