hawdb-storage 0.41.0

An embedded Rust graph database for local data-plane workloads
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
// Copyright 2026 Nowledge
//
// 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.

use crate::cache::ManifestGeneration;

/// Ownership of a query's admitted graph-read allocation. Implementations
/// release the reservation on Drop; storage retains it through consumption.
/// Standalone storage callers may use their own explicit allocation policy.
pub trait GraphReadAllocation {
    fn bytes(&self) -> usize;

    /// Reserve additional bytes atomically before allocation. Refusal leaves
    /// the existing reservation intact.
    fn grow(&mut self, bytes: usize) -> hawdb_core::Result<()>;

    /// Move an admitted read into retained operator state before insertion.
    /// Query allocators may atomically transfer to a separately bounded state
    /// account. Standalone allocators retain their existing explicit policy.
    fn retain_state(&mut self) -> hawdb_core::Result<()> {
        Ok(())
    }
}

/// A borrowed read policy. Work accounting never invokes payload admission:
/// payload callbacks can add fixed overhead, flush a batch, or request Stop.
pub struct GraphReadAllocator<'a, T = Box<dyn GraphReadAllocation>> {
    admit: &'a mut dyn FnMut(usize) -> hawdb_core::Result<T>,
    work: GraphReadWork<'a>,
    control: Option<&'a hawdb_core::RuntimeTaskContext>,
}

impl<'a, T> GraphReadAllocator<'a, T> {
    pub fn new(
        admit: &'a mut dyn FnMut(usize) -> hawdb_core::Result<T>,
        task_context: Option<&'a hawdb_core::RuntimeTaskContext>,
    ) -> Self {
        Self {
            admit,
            work: GraphReadWork(task_context.filter(|task| task.has_work_limit())),
            control: task_context,
        }
    }

    pub fn reserve(&mut self, bytes: usize) -> hawdb_core::Result<T> {
        (self.admit)(bytes)
    }

    pub(crate) fn work(&self) -> GraphReadWork<'a> {
        self.work
    }

    pub(crate) fn checkpoint(&self) -> hawdb_core::Result<()> {
        self.control.map_or(Ok(()), |task| {
            task.checkpoint()
                .map_err(hawdb_core::HawDBError::RuntimeTaskStopped)
        })
    }

    pub(crate) fn reborrow(&mut self) -> GraphReadAllocator<'_, T> {
        GraphReadAllocator {
            admit: self.admit,
            work: self.work,
            control: self.control,
        }
    }
}

#[derive(Clone, Copy)]
pub(crate) struct GraphReadWork<'a>(Option<&'a hawdb_core::RuntimeTaskContext>);

impl GraphReadWork<'_> {
    pub(crate) fn has_work_limit(self) -> bool {
        self.0.is_some()
    }

    pub(crate) fn check_work_limit(self) -> hawdb_core::Result<()> {
        self.0.map_or(Ok(()), |task| task.check_work_limit())
    }

    pub(crate) fn charge_work(self, units: usize) -> hawdb_core::Result<()> {
        self.0.map_or(Ok(()), |task| task.charge_work(units))
    }
}

/// None requests ordinary scan Stop before selected values are owned.
pub type ControlledGraphReadAllocator<'a> =
    GraphReadAllocator<'a, Option<Box<dyn GraphReadAllocation>>>;

/// A point read can be absent from the requested visible label set, or stop
/// normally before owning its payload. A successful read transfers its permit.
pub enum AdmittedNodeRead {
    Missing,
    Stopped,
    Node(AdmittedNodeRecord),
}

/// Relationship point reads transfer the permit acquired before ownership.
pub enum AdmittedRelationshipRead {
    Missing,
    Stopped,
    Relationship(AdmittedRelationshipRecord),
}

pub struct AdmittedRelationshipRecord {
    relationship: crate::RelRecord,
    allocation: Box<dyn GraphReadAllocation>,
}

impl AdmittedRelationshipRecord {
    pub(crate) fn new(
        relationship: crate::RelRecord,
        allocation: Box<dyn GraphReadAllocation>,
    ) -> Self {
        Self {
            relationship,
            allocation,
        }
    }

    pub fn clone_admitted(
        relationship: &crate::RelRecord,
        allocation: Box<dyn GraphReadAllocation>,
    ) -> hawdb_core::Result<Self> {
        if allocation.bytes() < hawdb_core::ids::relationship_allocation_bytes(relationship) {
            return Err(hawdb_core::HawDBError::Execution(
                "relationship admission returned an insufficient allocation permit".into(),
            ));
        }
        Ok(Self {
            relationship: relationship.clone(),
            allocation,
        })
    }

    /// Borrow the admitted record while its source allocation remains owned.
    pub fn relationship(&self) -> &crate::RelRecord {
        &self.relationship
    }

    /// Drops the properties `keep` rejects. The record only shrinks, so its
    /// allocation still covers it.
    pub fn retain_properties(&mut self, mut keep: impl FnMut(&str) -> bool) {
        self.relationship
            .properties
            .retain(|name, _| keep(name.as_str()));
    }

    pub fn into_parts(self) -> (crate::RelRecord, Box<dyn GraphReadAllocation>) {
        (self.relationship, self.allocation)
    }
}

/// Selected record and the reservation acquired before its values were owned.
/// Buffered consumers retain both until the record is consumed or dropped.
pub struct AdmittedProjectedNode {
    node: crate::ProjectedNodeRecord,
    allocation: Box<dyn GraphReadAllocation>,
}

impl AdmittedProjectedNode {
    pub(crate) fn new(
        node: crate::ProjectedNodeRecord,
        allocation: Box<dyn GraphReadAllocation>,
    ) -> Self {
        Self { node, allocation }
    }

    /// Custom readers admit the selected allocation before copying any values.
    pub fn clone_admitted(
        node: &crate::NodeRecord,
        properties: &std::collections::BTreeSet<String>,
        allocation: Box<dyn GraphReadAllocation>,
    ) -> hawdb_core::Result<Self> {
        if allocation.bytes() < hawdb_core::ids::projected_node_allocation_bytes(node, properties) {
            return Err(hawdb_core::HawDBError::Execution(
                "projected node admission returned an insufficient allocation permit".into(),
            ));
        }
        Ok(Self {
            node: hawdb_core::ids::project_node_record_ref(node, properties),
            allocation,
        })
    }

    pub fn into_parts(self) -> (crate::ProjectedNodeRecord, Box<dyn GraphReadAllocation>) {
        (self.node, self.allocation)
    }
}

/// Full node and the reservation acquired before any owned values were copied.
pub struct AdmittedNodeRecord {
    node: crate::NodeRecord,
    allocation: Box<dyn GraphReadAllocation>,
}

impl AdmittedNodeRecord {
    pub(crate) fn new(node: crate::NodeRecord, allocation: Box<dyn GraphReadAllocation>) -> Self {
        Self { node, allocation }
    }

    /// Custom resident readers can construct the admitted record directly
    /// from a borrowed source. Reject a short permit before cloning any Value.
    pub fn clone_admitted(
        node: &crate::NodeRecord,
        allocation: Box<dyn GraphReadAllocation>,
    ) -> hawdb_core::Result<Self> {
        if allocation.bytes() < hawdb_core::ids::node_allocation_bytes(node) {
            return Err(hawdb_core::HawDBError::Execution(
                "full node admission returned an insufficient allocation permit".into(),
            ));
        }
        Ok(Self {
            node: node.clone(),
            allocation,
        })
    }

    pub(crate) fn from_full_projection(input: AdmittedProjectedNode) -> Self {
        let (node, allocation) = input.into_parts();
        Self {
            node: crate::NodeRecord {
                id: node.id,
                labels: node.labels,
                properties: node.properties,
            },
            allocation,
        }
    }

    pub fn into_parts(self) -> (crate::NodeRecord, Box<dyn GraphReadAllocation>) {
        (self.node, self.allocation)
    }
}

/// Shared allocation policy for concurrently live graph-read collections.
pub struct GraphReadAdmission<'a> {
    admit: std::cell::RefCell<
        &'a mut dyn FnMut(usize) -> hawdb_core::Result<Box<dyn GraphReadAllocation>>,
    >,
}

impl<'a> GraphReadAdmission<'a> {
    pub fn new(
        admit: &'a mut dyn FnMut(usize) -> hawdb_core::Result<Box<dyn GraphReadAllocation>>,
    ) -> Self {
        Self {
            admit: std::cell::RefCell::new(admit),
        }
    }

    pub fn reserve(&self, bytes: usize) -> hawdb_core::Result<Box<dyn GraphReadAllocation>> {
        let allocation = (self.admit.borrow_mut())(bytes)?;
        if allocation.bytes() < bytes {
            return Err(hawdb_core::HawDBError::Execution(
                "graph read admission returned an insufficient allocation permit".into(),
            ));
        }
        Ok(allocation)
    }
}

/// A graph-read key set whose permit grows before a new key is inserted.
/// Each set owns a distinct permit, including simultaneously live AND/OR
/// candidates. Duplicate keys neither allocate tree nodes nor grow the permit.
pub struct AdmittedKeySet<T: Ord> {
    keys: std::collections::BTreeSet<T>,
    allocation: Box<dyn GraphReadAllocation>,
}

impl<T: Ord> AdmittedKeySet<T> {
    pub fn new(admission: &GraphReadAdmission<'_>) -> hawdb_core::Result<Self> {
        Ok(Self::with_allocation(admission.reserve(0)?))
    }

    pub(crate) fn with_allocation(allocation: Box<dyn GraphReadAllocation>) -> Self {
        Self {
            keys: std::collections::BTreeSet::new(),
            allocation,
        }
    }

    pub fn try_insert(&mut self, key: T) -> hawdb_core::Result<bool> {
        // Grow also carries the caller's task checkpoint. Repeated lookup
        // values must stay cancellable even when no new tree key is needed.
        self.allocation.grow(0)?;
        if self.keys.contains(&key) {
            return Ok(false);
        }
        self.allocation.retain_state()?;
        // Pinned std B-trees keep up to eleven keys plus node links. Cover
        // the first sparse node and conservative per-key tree overhead. These
        // read sets contain NodeId or borrowed Value keys, never owned Values.
        let key_bytes = std::mem::size_of::<T>();
        let bytes = self
            .keys
            .len()
            .saturating_add(1)
            .saturating_mul(64usize.saturating_add(key_bytes.saturating_mul(2)))
            .saturating_add(128usize.saturating_add(key_bytes.saturating_mul(11)));
        let additional = bytes.saturating_sub(self.allocation.bytes());
        self.allocation.grow(additional)?;
        if self.allocation.bytes() < bytes {
            return Err(hawdb_core::HawDBError::Execution(
                "graph read admission did not grow its allocation permit".into(),
            ));
        }
        Ok(self.keys.insert(key))
    }

    pub fn try_extend(&mut self, keys: impl IntoIterator<Item = T>) -> hawdb_core::Result<()> {
        for key in keys {
            self.try_insert(key)?;
        }
        Ok(())
    }
}

impl<T: Ord> std::ops::Deref for AdmittedKeySet<T> {
    type Target = std::collections::BTreeSet<T>;
    fn deref(&self) -> &Self::Target {
        &self.keys
    }
}

/// Capacity is admitted before a graph-read vector grows. Its permit can move
/// with the vector into a consumer iterator.
pub struct AdmittedVec<T> {
    values: Vec<T>,
    allocation: Box<dyn GraphReadAllocation>,
}

impl<T> AdmittedVec<T> {
    pub fn new(admission: &GraphReadAdmission<'_>) -> hawdb_core::Result<Self> {
        Ok(Self {
            values: Vec::new(),
            allocation: admission.reserve(0)?,
        })
    }

    pub fn try_push(&mut self, value: T) -> hawdb_core::Result<()> {
        if self.values.len() == self.values.capacity() {
            let capacity = self.values.capacity().saturating_mul(2).max(4);
            let bytes = capacity.saturating_mul(std::mem::size_of::<T>());
            self.allocation
                .grow(bytes.saturating_sub(self.allocation.bytes()))?;
            if self.allocation.bytes() < bytes {
                return Err(hawdb_core::HawDBError::Execution(
                    "graph read admission did not grow its allocation permit".into(),
                ));
            }
            self.values.reserve_exact(capacity - self.values.len());
        }
        self.values.push(value);
        Ok(())
    }

    pub fn into_parts(self) -> (Vec<T>, Box<dyn GraphReadAllocation>) {
        (self.values, self.allocation)
    }

    pub fn as_slice(&self) -> &[T] {
        &self.values
    }

    /// Mutate admitted elements without changing vector capacity or ownership.
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.values
    }

    pub fn clear(&mut self) {
        // The vector still owns its capacity; retain that allocation permit.
        self.values.clear();
    }

    /// Remove a consumed or displaced element, retaining admitted capacity.
    pub fn swap_remove(&mut self, index: usize) -> T {
        self.values.swap_remove(index)
    }
}

/// The immutable identity of one published database read.
///
/// The logical commit epoch controls visibility. The physical generation only
/// identifies the checkpoint base beneath that logical snapshot; later commits
/// may be represented by an immutable delta without changing the base.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct PublishedReadView {
    visible_commit_epoch: u64,
    checkpoint_commit_epoch: Option<u64>,
    physical_generation: Option<ManifestGeneration>,
    // Both origins exist exactly when the physical checkpoint exists. Store
    // their values without repeating its presence bit in every reader pin.
    graph_generation: u64,
    adjacency_generation: u64,
}

/// Checkpoint, canonical graph and adjacency bases retained by live readers.
/// Separate families avoid retaining unrelated files at an adjacency origin.
#[derive(Debug, Clone, Default)]
pub struct PhysicalGenerationPins {
    checkpoints: std::collections::BTreeSet<u64>,
    graphs: std::collections::BTreeSet<u64>,
    adjacencies: std::collections::BTreeSet<u64>,
    branch_wals: std::collections::BTreeSet<u64>,
}

impl PhysicalGenerationPins {
    pub(crate) fn checkpoint_generations(&self) -> &std::collections::BTreeSet<u64> {
        &self.checkpoints
    }
    pub(crate) fn graph_generations(&self) -> &std::collections::BTreeSet<u64> {
        &self.graphs
    }

    pub(crate) fn adjacency_generations(&self) -> &std::collections::BTreeSet<u64> {
        &self.adjacencies
    }

    pub(crate) fn retains_branch_wal(&self, generation: u64) -> bool {
        self.checkpoints.contains(&generation) || self.branch_wals.contains(&generation)
    }

    /// Declare an explicitly owned branch-private WAL for reclamation only.
    /// This does not acquire a lease/handle or retain other artifact families.
    /// Ordinary API read snapshots own their visible tail in memory.
    #[doc(hidden)]
    pub fn with_branch_wal_generation(mut self, generation: u64) -> Self {
        self.branch_wals.insert(generation);
        self
    }

    pub fn from_views(views: impl IntoIterator<Item = PublishedReadView>) -> Self {
        let mut pins = Self::default();
        for view in views {
            pins.checkpoints
                .extend(view.physical_generation.map(|generation| generation.0));
            pins.graphs
                .extend(view.graph_generation().map(|generation| generation.0));
            pins.adjacencies
                .extend(view.adjacency_generation().map(|generation| generation.0));
        }
        pins
    }
}

impl PublishedReadView {
    #[doc(hidden)]
    pub fn new(
        visible_commit_epoch: u64,
        checkpoint_commit_epoch: Option<u64>,
        physical_generation: Option<ManifestGeneration>,
    ) -> Self {
        debug_assert_eq!(
            checkpoint_commit_epoch.is_some(),
            physical_generation.is_some(),
            "checkpoint epoch and physical generation must be published together"
        );
        debug_assert!(
            checkpoint_commit_epoch.is_none_or(|epoch| epoch <= visible_commit_epoch),
            "checkpoint commit epoch must not exceed the visible commit epoch"
        );
        Self {
            visible_commit_epoch,
            checkpoint_commit_epoch,
            physical_generation,
            graph_generation: physical_generation.map_or(0, |generation| generation.0),
            adjacency_generation: physical_generation.map_or(0, |generation| generation.0),
        }
    }

    #[doc(hidden)]
    pub fn with_graph_generation(mut self, generation: Option<ManifestGeneration>) -> Self {
        debug_assert_eq!(self.physical_generation.is_some(), generation.is_some());
        self.graph_generation = generation.map_or(0, |generation| generation.0);
        self.adjacency_generation = self.graph_generation;
        self
    }

    #[doc(hidden)]
    pub fn with_adjacency_generation(mut self, generation: Option<ManifestGeneration>) -> Self {
        debug_assert_eq!(self.physical_generation.is_some(), generation.is_some());
        self.adjacency_generation = generation.map_or(0, |generation| generation.0);
        self
    }

    /// Adjacency origin retained independently from the canonical graph bundle.
    pub const fn adjacency_generation(self) -> Option<ManifestGeneration> {
        match self.physical_generation {
            Some(_) => Some(ManifestGeneration(self.adjacency_generation)),
            None => None,
        }
    }

    /// All physical bases that must remain alive for this read.
    pub fn physical_generations(self) -> impl Iterator<Item = ManifestGeneration> {
        [
            self.physical_generation,
            self.graph_generation(),
            self.adjacency_generation()
                .filter(|generation| Some(*generation) != self.graph_generation()),
        ]
        .into_iter()
        .flatten()
    }

    pub const fn visible_commit_epoch(self) -> u64 {
        self.visible_commit_epoch
    }

    pub const fn checkpoint_commit_epoch(self) -> Option<u64> {
        self.checkpoint_commit_epoch
    }

    pub const fn physical_generation(self) -> Option<ManifestGeneration> {
        self.physical_generation
    }

    /// Graph bundle retained by this view, which may precede the checkpoint
    /// generation when a checkpoint carries unchanged graph artifacts.
    pub const fn graph_generation(self) -> Option<ManifestGeneration> {
        match self.physical_generation {
            Some(_) => Some(ManifestGeneration(self.graph_generation)),
            None => None,
        }
    }

    pub const fn physical_base_is_current(self) -> bool {
        matches!(
            self.checkpoint_commit_epoch,
            Some(checkpoint_commit_epoch) if checkpoint_commit_epoch == self.visible_commit_epoch
        )
    }

    pub const fn has_delta_after_physical_generation(self) -> bool {
        matches!(
            self.checkpoint_commit_epoch,
            Some(checkpoint_commit_epoch) if checkpoint_commit_epoch < self.visible_commit_epoch
        )
    }
}

// The extra family must not grow the original pin on 64-bit targets.
#[cfg(target_pointer_width = "64")]
const _: () = assert!(std::mem::size_of::<PublishedReadView>() <= 56);

impl std::fmt::Debug for PublishedReadView {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PublishedReadView")
            .field("visible_commit_epoch", &self.visible_commit_epoch)
            .field("checkpoint_commit_epoch", &self.checkpoint_commit_epoch)
            .field("physical_generation", &self.physical_generation)
            .field("graph_generation", &self.graph_generation())
            .field("adjacency_generation", &self.adjacency_generation())
            .finish()
    }
}

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

    #[test]
    fn compact_origins_preserve_absent_zero_and_independent_generations() {
        let absent = PublishedReadView::new(0, None, None);
        assert_eq!(absent.graph_generation(), None);
        assert_eq!(absent.adjacency_generation(), None);
        assert_eq!(absent.physical_generations().count(), 0);
        let zero = PublishedReadView::new(0, Some(0), Some(ManifestGeneration(0)));
        assert_eq!(zero.graph_generation(), Some(ManifestGeneration(0)));
        assert_eq!(zero.adjacency_generation(), Some(ManifestGeneration(0)));
        let mixed = PublishedReadView::new(9, Some(8), Some(ManifestGeneration(7)))
            .with_graph_generation(Some(ManifestGeneration(5)))
            .with_adjacency_generation(Some(ManifestGeneration(2)));
        assert_eq!(
            mixed
                .physical_generations()
                .map(|generation| generation.0)
                .collect::<Vec<_>>(),
            vec![7, 5, 2]
        );
        assert_eq!(format!("{mixed:?}"), concat!(
            "PublishedReadView { visible_commit_epoch: 9, checkpoint_commit_epoch: Some(8), ",
            "physical_generation: Some(ManifestGeneration(7)), graph_generation: Some(ManifestGeneration(5)), ",
            "adjacency_generation: Some(ManifestGeneration(2)) }",
        ));
        let pins = PhysicalGenerationPins::from_views([absent, zero, mixed]);
        assert_eq!(
            pins.checkpoint_generations()
                .iter()
                .copied()
                .collect::<Vec<_>>(),
            vec![0, 7]
        );
        assert_eq!(
            pins.graph_generations().iter().copied().collect::<Vec<_>>(),
            vec![0, 5]
        );
        assert_eq!(
            pins.adjacency_generations()
                .iter()
                .copied()
                .collect::<Vec<_>>(),
            vec![0, 2]
        );
    }
}