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(Clone, Copy, PartialEq, Eq)]
398pub struct PublishedReadView {
399    visible_commit_epoch: u64,
400    checkpoint_commit_epoch: Option<u64>,
401    physical_generation: Option<ManifestGeneration>,
402    // Both origins exist exactly when the physical checkpoint exists. Store
403    // their values without repeating its presence bit in every reader pin.
404    graph_generation: u64,
405    adjacency_generation: u64,
406}
407
408/// Checkpoint, canonical graph and adjacency bases retained by live readers.
409/// Separate families avoid retaining unrelated files at an adjacency origin.
410#[derive(Debug, Clone, Default)]
411pub struct PhysicalGenerationPins {
412    checkpoints: std::collections::BTreeSet<u64>,
413    graphs: std::collections::BTreeSet<u64>,
414    adjacencies: std::collections::BTreeSet<u64>,
415    branch_wals: std::collections::BTreeSet<u64>,
416}
417
418impl PhysicalGenerationPins {
419    pub(crate) fn checkpoint_generations(&self) -> &std::collections::BTreeSet<u64> {
420        &self.checkpoints
421    }
422    pub(crate) fn graph_generations(&self) -> &std::collections::BTreeSet<u64> {
423        &self.graphs
424    }
425
426    pub(crate) fn adjacency_generations(&self) -> &std::collections::BTreeSet<u64> {
427        &self.adjacencies
428    }
429
430    pub(crate) fn retains_branch_wal(&self, generation: u64) -> bool {
431        self.checkpoints.contains(&generation) || self.branch_wals.contains(&generation)
432    }
433
434    /// Declare an explicitly owned branch-private WAL for reclamation only.
435    /// This does not acquire a lease/handle or retain other artifact families.
436    /// Ordinary API read snapshots own their visible tail in memory.
437    #[doc(hidden)]
438    pub fn with_branch_wal_generation(mut self, generation: u64) -> Self {
439        self.branch_wals.insert(generation);
440        self
441    }
442
443    pub fn from_views(views: impl IntoIterator<Item = PublishedReadView>) -> Self {
444        let mut pins = Self::default();
445        for view in views {
446            pins.checkpoints
447                .extend(view.physical_generation.map(|generation| generation.0));
448            pins.graphs
449                .extend(view.graph_generation().map(|generation| generation.0));
450            pins.adjacencies
451                .extend(view.adjacency_generation().map(|generation| generation.0));
452        }
453        pins
454    }
455}
456
457impl PublishedReadView {
458    #[doc(hidden)]
459    pub fn new(
460        visible_commit_epoch: u64,
461        checkpoint_commit_epoch: Option<u64>,
462        physical_generation: Option<ManifestGeneration>,
463    ) -> Self {
464        debug_assert_eq!(
465            checkpoint_commit_epoch.is_some(),
466            physical_generation.is_some(),
467            "checkpoint epoch and physical generation must be published together"
468        );
469        debug_assert!(
470            checkpoint_commit_epoch.is_none_or(|epoch| epoch <= visible_commit_epoch),
471            "checkpoint commit epoch must not exceed the visible commit epoch"
472        );
473        Self {
474            visible_commit_epoch,
475            checkpoint_commit_epoch,
476            physical_generation,
477            graph_generation: physical_generation.map_or(0, |generation| generation.0),
478            adjacency_generation: physical_generation.map_or(0, |generation| generation.0),
479        }
480    }
481
482    #[doc(hidden)]
483    pub fn with_graph_generation(mut self, generation: Option<ManifestGeneration>) -> Self {
484        debug_assert_eq!(self.physical_generation.is_some(), generation.is_some());
485        self.graph_generation = generation.map_or(0, |generation| generation.0);
486        self.adjacency_generation = self.graph_generation;
487        self
488    }
489
490    #[doc(hidden)]
491    pub fn with_adjacency_generation(mut self, generation: Option<ManifestGeneration>) -> Self {
492        debug_assert_eq!(self.physical_generation.is_some(), generation.is_some());
493        self.adjacency_generation = generation.map_or(0, |generation| generation.0);
494        self
495    }
496
497    /// Adjacency origin retained independently from the canonical graph bundle.
498    pub const fn adjacency_generation(self) -> Option<ManifestGeneration> {
499        match self.physical_generation {
500            Some(_) => Some(ManifestGeneration(self.adjacency_generation)),
501            None => None,
502        }
503    }
504
505    /// All physical bases that must remain alive for this read.
506    pub fn physical_generations(self) -> impl Iterator<Item = ManifestGeneration> {
507        [
508            self.physical_generation,
509            self.graph_generation(),
510            self.adjacency_generation()
511                .filter(|generation| Some(*generation) != self.graph_generation()),
512        ]
513        .into_iter()
514        .flatten()
515    }
516
517    pub const fn visible_commit_epoch(self) -> u64 {
518        self.visible_commit_epoch
519    }
520
521    pub const fn checkpoint_commit_epoch(self) -> Option<u64> {
522        self.checkpoint_commit_epoch
523    }
524
525    pub const fn physical_generation(self) -> Option<ManifestGeneration> {
526        self.physical_generation
527    }
528
529    /// Graph bundle retained by this view, which may precede the checkpoint
530    /// generation when a checkpoint carries unchanged graph artifacts.
531    pub const fn graph_generation(self) -> Option<ManifestGeneration> {
532        match self.physical_generation {
533            Some(_) => Some(ManifestGeneration(self.graph_generation)),
534            None => None,
535        }
536    }
537
538    pub const fn physical_base_is_current(self) -> bool {
539        matches!(
540            self.checkpoint_commit_epoch,
541            Some(checkpoint_commit_epoch) if checkpoint_commit_epoch == self.visible_commit_epoch
542        )
543    }
544
545    pub const fn has_delta_after_physical_generation(self) -> bool {
546        matches!(
547            self.checkpoint_commit_epoch,
548            Some(checkpoint_commit_epoch) if checkpoint_commit_epoch < self.visible_commit_epoch
549        )
550    }
551}
552
553// The extra family must not grow the original pin on 64-bit targets.
554#[cfg(target_pointer_width = "64")]
555const _: () = assert!(std::mem::size_of::<PublishedReadView>() <= 56);
556
557impl std::fmt::Debug for PublishedReadView {
558    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
559        formatter
560            .debug_struct("PublishedReadView")
561            .field("visible_commit_epoch", &self.visible_commit_epoch)
562            .field("checkpoint_commit_epoch", &self.checkpoint_commit_epoch)
563            .field("physical_generation", &self.physical_generation)
564            .field("graph_generation", &self.graph_generation())
565            .field("adjacency_generation", &self.adjacency_generation())
566            .finish()
567    }
568}
569
570#[cfg(test)]
571mod generation_identity_tests {
572    use super::*;
573
574    #[test]
575    fn compact_origins_preserve_absent_zero_and_independent_generations() {
576        let absent = PublishedReadView::new(0, None, None);
577        assert_eq!(absent.graph_generation(), None);
578        assert_eq!(absent.adjacency_generation(), None);
579        assert_eq!(absent.physical_generations().count(), 0);
580        let zero = PublishedReadView::new(0, Some(0), Some(ManifestGeneration(0)));
581        assert_eq!(zero.graph_generation(), Some(ManifestGeneration(0)));
582        assert_eq!(zero.adjacency_generation(), Some(ManifestGeneration(0)));
583        let mixed = PublishedReadView::new(9, Some(8), Some(ManifestGeneration(7)))
584            .with_graph_generation(Some(ManifestGeneration(5)))
585            .with_adjacency_generation(Some(ManifestGeneration(2)));
586        assert_eq!(
587            mixed
588                .physical_generations()
589                .map(|generation| generation.0)
590                .collect::<Vec<_>>(),
591            vec![7, 5, 2]
592        );
593        assert_eq!(format!("{mixed:?}"), concat!(
594            "PublishedReadView { visible_commit_epoch: 9, checkpoint_commit_epoch: Some(8), ",
595            "physical_generation: Some(ManifestGeneration(7)), graph_generation: Some(ManifestGeneration(5)), ",
596            "adjacency_generation: Some(ManifestGeneration(2)) }",
597        ));
598        let pins = PhysicalGenerationPins::from_views([absent, zero, mixed]);
599        assert_eq!(
600            pins.checkpoint_generations()
601                .iter()
602                .copied()
603                .collect::<Vec<_>>(),
604            vec![0, 7]
605        );
606        assert_eq!(
607            pins.graph_generations().iter().copied().collect::<Vec<_>>(),
608            vec![0, 5]
609        );
610        assert_eq!(
611            pins.adjacency_generations()
612                .iter()
613                .copied()
614                .collect::<Vec<_>>(),
615            vec![0, 2]
616        );
617    }
618}