Skip to main content

hawdb_storage/
read_view.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::cache::ManifestGeneration;
16
17/// Ownership of a query's admitted graph-read allocation. Implementations
18/// release the reservation on Drop; storage retains it through consumption.
19/// Standalone storage callers may use their own explicit allocation policy.
20pub trait GraphReadAllocation {
21    fn bytes(&self) -> usize;
22
23    /// Reserve additional bytes atomically before allocation. Refusal leaves
24    /// the existing reservation intact.
25    fn grow(&mut self, bytes: usize) -> hawdb_core::Result<()>;
26
27    /// Move an admitted read into retained operator state before insertion.
28    /// Query allocators may atomically transfer to a separately bounded state
29    /// account. Standalone allocators retain their existing explicit policy.
30    fn retain_state(&mut self) -> hawdb_core::Result<()> {
31        Ok(())
32    }
33}
34
35/// A borrowed read policy. Work accounting never invokes payload admission:
36/// payload callbacks can add fixed overhead, flush a batch, or request Stop.
37pub struct GraphReadAllocator<'a, T = Box<dyn GraphReadAllocation>> {
38    admit: &'a mut dyn FnMut(usize) -> hawdb_core::Result<T>,
39    work: GraphReadWork<'a>,
40    control: Option<&'a hawdb_core::RuntimeTaskContext>,
41}
42
43impl<'a, T> GraphReadAllocator<'a, T> {
44    pub fn new(
45        admit: &'a mut dyn FnMut(usize) -> hawdb_core::Result<T>,
46        task_context: Option<&'a hawdb_core::RuntimeTaskContext>,
47    ) -> Self {
48        Self {
49            admit,
50            work: GraphReadWork(task_context.filter(|task| task.has_work_limit())),
51            control: task_context,
52        }
53    }
54
55    pub fn reserve(&mut self, bytes: usize) -> hawdb_core::Result<T> {
56        (self.admit)(bytes)
57    }
58
59    pub(crate) fn work(&self) -> GraphReadWork<'a> {
60        self.work
61    }
62
63    pub(crate) fn checkpoint(&self) -> hawdb_core::Result<()> {
64        self.control.map_or(Ok(()), |task| {
65            task.checkpoint()
66                .map_err(hawdb_core::HawDBError::RuntimeTaskStopped)
67        })
68    }
69
70    pub(crate) fn reborrow(&mut self) -> GraphReadAllocator<'_, T> {
71        GraphReadAllocator {
72            admit: self.admit,
73            work: self.work,
74            control: self.control,
75        }
76    }
77}
78
79#[derive(Clone, Copy)]
80pub(crate) struct GraphReadWork<'a>(Option<&'a hawdb_core::RuntimeTaskContext>);
81
82impl GraphReadWork<'_> {
83    pub(crate) fn has_work_limit(self) -> bool {
84        self.0.is_some()
85    }
86
87    pub(crate) fn check_work_limit(self) -> hawdb_core::Result<()> {
88        self.0.map_or(Ok(()), |task| task.check_work_limit())
89    }
90
91    pub(crate) fn charge_work(self, units: usize) -> hawdb_core::Result<()> {
92        self.0.map_or(Ok(()), |task| task.charge_work(units))
93    }
94}
95
96/// None requests ordinary scan Stop before selected values are owned.
97pub type ControlledGraphReadAllocator<'a> =
98    GraphReadAllocator<'a, Option<Box<dyn GraphReadAllocation>>>;
99
100/// A point read can be absent from the requested visible label set, or stop
101/// normally before owning its payload. A successful read transfers its permit.
102pub enum AdmittedNodeRead {
103    Missing,
104    Stopped,
105    Node(AdmittedNodeRecord),
106}
107
108/// Relationship point reads transfer the permit acquired before ownership.
109pub enum AdmittedRelationshipRead {
110    Missing,
111    Stopped,
112    Relationship(AdmittedRelationshipRecord),
113}
114
115pub struct AdmittedRelationshipRecord {
116    relationship: crate::RelRecord,
117    allocation: Box<dyn GraphReadAllocation>,
118}
119
120impl AdmittedRelationshipRecord {
121    pub(crate) fn new(
122        relationship: crate::RelRecord,
123        allocation: Box<dyn GraphReadAllocation>,
124    ) -> Self {
125        Self {
126            relationship,
127            allocation,
128        }
129    }
130
131    pub fn clone_admitted(
132        relationship: &crate::RelRecord,
133        allocation: Box<dyn GraphReadAllocation>,
134    ) -> hawdb_core::Result<Self> {
135        if allocation.bytes() < hawdb_core::ids::relationship_allocation_bytes(relationship) {
136            return Err(hawdb_core::HawDBError::Execution(
137                "relationship admission returned an insufficient allocation permit".into(),
138            ));
139        }
140        Ok(Self {
141            relationship: relationship.clone(),
142            allocation,
143        })
144    }
145
146    /// Borrow the admitted record while its source allocation remains owned.
147    pub fn relationship(&self) -> &crate::RelRecord {
148        &self.relationship
149    }
150
151    /// Drops the properties `keep` rejects. The record only shrinks, so its
152    /// allocation still covers it.
153    pub fn retain_properties(&mut self, mut keep: impl FnMut(&str) -> bool) {
154        self.relationship
155            .properties
156            .retain(|name, _| keep(name.as_str()));
157    }
158
159    pub fn into_parts(self) -> (crate::RelRecord, Box<dyn GraphReadAllocation>) {
160        (self.relationship, self.allocation)
161    }
162}
163
164/// Selected record and the reservation acquired before its values were owned.
165/// Buffered consumers retain both until the record is consumed or dropped.
166pub struct AdmittedProjectedNode {
167    node: crate::ProjectedNodeRecord,
168    allocation: Box<dyn GraphReadAllocation>,
169}
170
171impl AdmittedProjectedNode {
172    pub(crate) fn new(
173        node: crate::ProjectedNodeRecord,
174        allocation: Box<dyn GraphReadAllocation>,
175    ) -> Self {
176        Self { node, allocation }
177    }
178
179    /// Custom readers admit the selected allocation before copying any values.
180    pub fn clone_admitted(
181        node: &crate::NodeRecord,
182        properties: &std::collections::BTreeSet<String>,
183        allocation: Box<dyn GraphReadAllocation>,
184    ) -> hawdb_core::Result<Self> {
185        if allocation.bytes() < hawdb_core::ids::projected_node_allocation_bytes(node, properties) {
186            return Err(hawdb_core::HawDBError::Execution(
187                "projected node admission returned an insufficient allocation permit".into(),
188            ));
189        }
190        Ok(Self {
191            node: hawdb_core::ids::project_node_record_ref(node, properties),
192            allocation,
193        })
194    }
195
196    pub fn into_parts(self) -> (crate::ProjectedNodeRecord, Box<dyn GraphReadAllocation>) {
197        (self.node, self.allocation)
198    }
199}
200
201/// Full node and the reservation acquired before any owned values were copied.
202pub struct AdmittedNodeRecord {
203    node: crate::NodeRecord,
204    allocation: Box<dyn GraphReadAllocation>,
205}
206
207impl AdmittedNodeRecord {
208    pub(crate) fn new(node: crate::NodeRecord, allocation: Box<dyn GraphReadAllocation>) -> Self {
209        Self { node, allocation }
210    }
211
212    /// Custom resident readers can construct the admitted record directly
213    /// from a borrowed source. Reject a short permit before cloning any Value.
214    pub fn clone_admitted(
215        node: &crate::NodeRecord,
216        allocation: Box<dyn GraphReadAllocation>,
217    ) -> hawdb_core::Result<Self> {
218        if allocation.bytes() < hawdb_core::ids::node_allocation_bytes(node) {
219            return Err(hawdb_core::HawDBError::Execution(
220                "full node admission returned an insufficient allocation permit".into(),
221            ));
222        }
223        Ok(Self {
224            node: node.clone(),
225            allocation,
226        })
227    }
228
229    pub(crate) fn from_full_projection(input: AdmittedProjectedNode) -> Self {
230        let (node, allocation) = input.into_parts();
231        Self {
232            node: crate::NodeRecord {
233                id: node.id,
234                labels: node.labels,
235                properties: node.properties,
236            },
237            allocation,
238        }
239    }
240
241    pub fn into_parts(self) -> (crate::NodeRecord, Box<dyn GraphReadAllocation>) {
242        (self.node, self.allocation)
243    }
244}
245
246/// Shared allocation policy for concurrently live graph-read collections.
247pub struct GraphReadAdmission<'a> {
248    admit: std::cell::RefCell<
249        &'a mut dyn FnMut(usize) -> hawdb_core::Result<Box<dyn GraphReadAllocation>>,
250    >,
251}
252
253impl<'a> GraphReadAdmission<'a> {
254    pub fn new(
255        admit: &'a mut dyn FnMut(usize) -> hawdb_core::Result<Box<dyn GraphReadAllocation>>,
256    ) -> Self {
257        Self {
258            admit: std::cell::RefCell::new(admit),
259        }
260    }
261
262    pub fn reserve(&self, bytes: usize) -> hawdb_core::Result<Box<dyn GraphReadAllocation>> {
263        let allocation = (self.admit.borrow_mut())(bytes)?;
264        if allocation.bytes() < bytes {
265            return Err(hawdb_core::HawDBError::Execution(
266                "graph read admission returned an insufficient allocation permit".into(),
267            ));
268        }
269        Ok(allocation)
270    }
271}
272
273/// A graph-read key set whose permit grows before a new key is inserted.
274/// Each set owns a distinct permit, including simultaneously live AND/OR
275/// candidates. Duplicate keys neither allocate tree nodes nor grow the permit.
276pub struct AdmittedKeySet<T: Ord> {
277    keys: std::collections::BTreeSet<T>,
278    allocation: Box<dyn GraphReadAllocation>,
279}
280
281impl<T: Ord> AdmittedKeySet<T> {
282    pub fn new(admission: &GraphReadAdmission<'_>) -> hawdb_core::Result<Self> {
283        Ok(Self::with_allocation(admission.reserve(0)?))
284    }
285
286    pub(crate) fn with_allocation(allocation: Box<dyn GraphReadAllocation>) -> Self {
287        Self {
288            keys: std::collections::BTreeSet::new(),
289            allocation,
290        }
291    }
292
293    pub fn try_insert(&mut self, key: T) -> hawdb_core::Result<bool> {
294        // Grow also carries the caller's task checkpoint. Repeated lookup
295        // values must stay cancellable even when no new tree key is needed.
296        self.allocation.grow(0)?;
297        if self.keys.contains(&key) {
298            return Ok(false);
299        }
300        self.allocation.retain_state()?;
301        // Pinned std B-trees keep up to eleven keys plus node links. Cover
302        // the first sparse node and conservative per-key tree overhead. These
303        // read sets contain NodeId or borrowed Value keys, never owned Values.
304        let key_bytes = std::mem::size_of::<T>();
305        let bytes = self
306            .keys
307            .len()
308            .saturating_add(1)
309            .saturating_mul(64usize.saturating_add(key_bytes.saturating_mul(2)))
310            .saturating_add(128usize.saturating_add(key_bytes.saturating_mul(11)));
311        let additional = bytes.saturating_sub(self.allocation.bytes());
312        self.allocation.grow(additional)?;
313        if self.allocation.bytes() < bytes {
314            return Err(hawdb_core::HawDBError::Execution(
315                "graph read admission did not grow its allocation permit".into(),
316            ));
317        }
318        Ok(self.keys.insert(key))
319    }
320
321    pub fn try_extend(&mut self, keys: impl IntoIterator<Item = T>) -> hawdb_core::Result<()> {
322        for key in keys {
323            self.try_insert(key)?;
324        }
325        Ok(())
326    }
327}
328
329impl<T: Ord> std::ops::Deref for AdmittedKeySet<T> {
330    type Target = std::collections::BTreeSet<T>;
331    fn deref(&self) -> &Self::Target {
332        &self.keys
333    }
334}
335
336/// Capacity is admitted before a graph-read vector grows. Its permit can move
337/// with the vector into a consumer iterator.
338pub struct AdmittedVec<T> {
339    values: Vec<T>,
340    allocation: Box<dyn GraphReadAllocation>,
341}
342
343impl<T> AdmittedVec<T> {
344    pub fn new(admission: &GraphReadAdmission<'_>) -> hawdb_core::Result<Self> {
345        Ok(Self {
346            values: Vec::new(),
347            allocation: admission.reserve(0)?,
348        })
349    }
350
351    pub fn try_push(&mut self, value: T) -> hawdb_core::Result<()> {
352        if self.values.len() == self.values.capacity() {
353            let capacity = self.values.capacity().saturating_mul(2).max(4);
354            let bytes = capacity.saturating_mul(std::mem::size_of::<T>());
355            self.allocation
356                .grow(bytes.saturating_sub(self.allocation.bytes()))?;
357            if self.allocation.bytes() < bytes {
358                return Err(hawdb_core::HawDBError::Execution(
359                    "graph read admission did not grow its allocation permit".into(),
360                ));
361            }
362            self.values.reserve_exact(capacity - self.values.len());
363        }
364        self.values.push(value);
365        Ok(())
366    }
367
368    pub fn into_parts(self) -> (Vec<T>, Box<dyn GraphReadAllocation>) {
369        (self.values, self.allocation)
370    }
371
372    pub fn as_slice(&self) -> &[T] {
373        &self.values
374    }
375
376    /// Mutate admitted elements without changing vector capacity or ownership.
377    pub fn as_mut_slice(&mut self) -> &mut [T] {
378        &mut self.values
379    }
380
381    pub fn clear(&mut self) {
382        // The vector still owns its capacity; retain that allocation permit.
383        self.values.clear();
384    }
385
386    /// Remove a consumed or displaced element, retaining admitted capacity.
387    pub fn swap_remove(&mut self, index: usize) -> T {
388        self.values.swap_remove(index)
389    }
390}
391
392/// The immutable identity of one published database read.
393///
394/// The logical commit epoch controls visibility. The physical generation only
395/// identifies the checkpoint base beneath that logical snapshot; later commits
396/// may be represented by an immutable delta without changing the base.
397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398pub struct PublishedReadView {
399    visible_commit_epoch: u64,
400    checkpoint_commit_epoch: Option<u64>,
401    physical_generation: Option<ManifestGeneration>,
402}
403
404impl PublishedReadView {
405    #[doc(hidden)]
406    pub fn new(
407        visible_commit_epoch: u64,
408        checkpoint_commit_epoch: Option<u64>,
409        physical_generation: Option<ManifestGeneration>,
410    ) -> Self {
411        debug_assert_eq!(
412            checkpoint_commit_epoch.is_some(),
413            physical_generation.is_some(),
414            "checkpoint epoch and physical generation must be published together"
415        );
416        debug_assert!(
417            checkpoint_commit_epoch.is_none_or(|epoch| epoch <= visible_commit_epoch),
418            "checkpoint commit epoch must not exceed the visible commit epoch"
419        );
420        Self {
421            visible_commit_epoch,
422            checkpoint_commit_epoch,
423            physical_generation,
424        }
425    }
426
427    pub const fn visible_commit_epoch(self) -> u64 {
428        self.visible_commit_epoch
429    }
430
431    pub const fn checkpoint_commit_epoch(self) -> Option<u64> {
432        self.checkpoint_commit_epoch
433    }
434
435    pub const fn physical_generation(self) -> Option<ManifestGeneration> {
436        self.physical_generation
437    }
438
439    pub const fn physical_base_is_current(self) -> bool {
440        matches!(
441            self.checkpoint_commit_epoch,
442            Some(checkpoint_commit_epoch) if checkpoint_commit_epoch == self.visible_commit_epoch
443        )
444    }
445
446    pub const fn has_delta_after_physical_generation(self) -> bool {
447        matches!(
448            self.checkpoint_commit_epoch,
449            Some(checkpoint_commit_epoch) if checkpoint_commit_epoch < self.visible_commit_epoch
450        )
451    }
452}