hawdb-storage 0.16.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
// Copyright 2026 Nowledge
// Licensed under the Apache License, Version 2.0.

//! Complete type scopes, independent of selected endpoint adjacency roots.

use super::*;

const MAX_WORK: usize = 65_536;
const MAX_METADATA_BYTES: usize = 64 * 1024;
const MAX_DEPTH: usize = 32;

struct Collector<'a> {
    store: &'a GraphStore,
    catalog: &'a Catalog,
    created: BTreeMap<RelId, &'a str>,
    last_kind: Option<&'a str>,
    work: usize,
    bytes: usize,
}

impl GraphStore {
    pub(super) fn extend_relationship_read_invalidations(
        &self,
        catalog: &Catalog,
        ops: &[WalOp],
        stamps: &mut VersionWriteSet,
    ) -> Result<()> {
        if stamps.contains_key(&VersionKey::Database) {
            return Ok(());
        }
        let mut collector = Collector {
            store: self,
            catalog,
            created: BTreeMap::new(),
            last_kind: None,
            work: 0,
            bytes: 0,
        };
        let result = collector.collect(ops, 0, stamps);
        self.poison_on_storage_error(&result);
        if !result? {
            record_stamp(stamps, VersionKey::ReadBarrier)?;
        }
        Ok(())
    }
}

impl<'a> Collector<'a> {
    fn visit(&mut self) -> bool {
        self.work += 1;
        self.work <= MAX_WORK
    }
    fn admit(&mut self, bytes: usize) -> bool {
        self.bytes = self.bytes.saturating_add(bytes);
        self.bytes <= MAX_METADATA_BYTES
    }
    fn stamp(&mut self, kind: &'a str, stamps: &mut VersionWriteSet) -> Result<bool> {
        if self.last_kind == Some(kind) {
            return Ok(true);
        }
        // Preflight before owning the name; no property values are copied.
        if !self.admit(
            2 * std::mem::size_of::<VersionKey>()
                + 2 * std::mem::size_of::<crate::version::VersionWrite>()
                + kind.len(),
        ) {
            return Ok(false);
        }
        record_stamp(stamps, VersionKey::ReadRelationshipDomain(None))?;
        record_stamp(
            stamps,
            VersionKey::ReadRelationshipDomain(Some(kind.into())),
        )?;
        self.last_kind = Some(kind);
        Ok(true)
    }
    fn existing_kind(&self, id: RelId) -> Result<Option<&'a str>> {
        if let Some(kind) = self.created.get(&id) {
            return Ok(Some(*kind));
        }
        if self.store.relationship_tombstones.contains(&id) {
            return Ok(None);
        }
        let kind = if let Some(rel) = self.store.relationships.get(&id) {
            Some(rel.rel_type)
        } else if let Some(reader) = &self.store.canonical_base {
            let result = reader
                .relationship_identity(id)
                .map_err(|error| HawDBError::StorageIntegrity(error.to_string()));
            self.store.poison_on_storage_error(&result);
            result?.map(|(_, _, kind)| kind)
        } else {
            None
        };
        let Some(kind) = kind else { return Ok(None) };
        self.catalog.rel_type_name(kind).map(Some).ok_or_else(|| {
            HawDBError::StorageIntegrity("relationship summary type is absent from catalog".into())
        })
    }
    fn collect(
        &mut self,
        ops: &'a [WalOp],
        depth: usize,
        stamps: &mut VersionWriteSet,
    ) -> Result<bool> {
        if depth > MAX_DEPTH {
            return Ok(false);
        }
        for op in ops {
            if !self.visit() {
                return Ok(false);
            }
            match op {
                WalOp::CreateRelationship { id, rel_type, .. } => {
                    if !self.admit(
                        std::mem::size_of::<RelId>()
                            + std::mem::size_of::<&str>()
                            + 3 * std::mem::size_of::<usize>(),
                    ) || !self.stamp(rel_type, stamps)?
                    {
                        return Ok(false);
                    }
                    // Borrow from the same immutable WAL input, including
                    // nested creates followed by property changes/deletes.
                    self.created.insert(*id, rel_type);
                }
                WalOp::SetRelationshipProperty { id, .. } | WalOp::DeleteRelationship { id } => {
                    if !self.visit() {
                        return Ok(false);
                    }
                    let Some(kind) = self.existing_kind(*id)? else {
                        return Ok(false);
                    };
                    if !self.stamp(kind, stamps)? {
                        return Ok(false);
                    }
                }
                WalOp::Batch(ops) if !self.collect(ops, depth + 1, stamps)? => {
                    return Ok(false);
                }
                _ => {}
            }
        }
        Ok(true)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mutation::{GraphMutation, MutationLimits, PropertyFilter};

    fn update(source: u64, target: u64) -> GraphMutation {
        GraphMutation::SetRelationshipProperty {
            source_label: "Memory".into(),
            filter: Some(PropertyFilter::IdEq {
                value: Value::Int(source as i64),
            }),
            rel_type: "HAS_LABEL".into(),
            target_label: "Label".into(),
            target_filter: Some(PropertyFilter::IdEq {
                value: Value::Int(target as i64),
            }),
            rel_filter: None,
            property: "weight".into(),
            value: Value::Int(1),
        }
    }

    #[test]
    fn type_scope_invalidates_without_becoming_a_shared_writer_intent() {
        let mut store = GraphStore::default();
        let mut catalog = Catalog::default();
        let a = store
            .create_node(&mut catalog, "Memory", BTreeMap::new())
            .unwrap();
        let b = store
            .create_node(&mut catalog, "Memory", BTreeMap::new())
            .unwrap();
        let x = store
            .create_node(&mut catalog, "Label", BTreeMap::new())
            .unwrap();
        let y = store
            .create_node(&mut catalog, "Label", BTreeMap::new())
            .unwrap();
        store
            .create_relationship(&mut catalog, a, x, "HAS_LABEL", BTreeMap::new())
            .unwrap();
        store
            .create_relationship(&mut catalog, b, y, "HAS_LABEL", BTreeMap::new())
            .unwrap();
        let mut read = store.capture_read_dependencies(8, 4096).unwrap();
        read.record(VersionKey::ReadRelationshipDomain(Some("HAS_LABEL".into())))
            .unwrap();
        let mut absent = store.capture_read_dependencies(8, 4096).unwrap();
        absent
            .record(VersionKey::ReadRelationshipDomain(Some("OTHER".into())))
            .unwrap();
        let mut first = store.begin_mutation_transaction(&catalog);
        let mut second = store.begin_mutation_transaction(&catalog);
        first
            .stage_mutation_with_limits(update(a.0, x.0), MutationLimits::default())
            .unwrap();
        second
            .stage_mutation_with_limits(update(b.0, y.0), MutationLimits::default())
            .unwrap();
        for transaction in [first, second] {
            store
                .commit_mutation_transaction_and_relational(
                    &mut catalog,
                    transaction,
                    RelationalTransaction::default(),
                    MutationLimits::default(),
                )
                .unwrap();
        }
        assert!(matches!(
            store.validate_read_dependencies(&read),
            Err(GraphReadDependencyError::Conflict(VersionConflict {
                key: VersionKey::ReadRelationshipDomain(_),
                ..
            }))
        ));
        store.validate_read_dependencies(&absent).unwrap();
    }

    #[test]
    fn nested_create_update_delete_uses_borrowed_names_without_property_ownership() {
        let store = GraphStore::default();
        let catalog = Catalog::default();
        let ops = vec![WalOp::Batch(vec![
            WalOp::CreateRelationship {
                id: RelId(4),
                source: NodeId(1),
                target: NodeId(2),
                rel_type: "HAS_LABEL".into(),
                properties: BTreeMap::from([(
                    "large".into(),
                    Value::String("x".repeat(1024 * 1024)),
                )]),
            },
            WalOp::SetRelationshipProperty {
                id: RelId(4),
                property: "weight".into(),
                value: Value::Int(1),
            },
            WalOp::DeleteRelationship { id: RelId(4) },
        ])];
        let mut stamps = VersionWriteSet::default();
        store
            .extend_relationship_read_invalidations(&catalog, &ops, &mut stamps)
            .unwrap();
        assert!(
            stamps.contains_key(&VersionKey::ReadRelationshipDomain(Some(
                "HAS_LABEL".into()
            )))
        );
        assert!(stamps.contains_key(&VersionKey::ReadRelationshipDomain(None)));
        assert!(!stamps.contains_key(&VersionKey::ReadBarrier));
        assert!(stamps.estimated_bytes() < 1024);
    }

    #[test]
    fn unknown_identity_and_unadmitted_name_use_the_shared_barrier() {
        for op in [
            WalOp::DeleteRelationship { id: RelId(99) },
            WalOp::CreateRelationship {
                id: RelId(4),
                source: NodeId(1),
                target: NodeId(2),
                rel_type: "x".repeat(MAX_METADATA_BYTES),
                properties: BTreeMap::new(),
            },
        ] {
            let store = GraphStore::default();
            let mut stamps = VersionWriteSet::default();
            store
                .extend_relationship_read_invalidations(&Catalog::default(), &[op], &mut stamps)
                .unwrap();
            assert!(stamps.contains_key(&VersionKey::ReadBarrier));
            assert_eq!(stamps.len(), 1);
        }
    }

    #[test]
    fn cold_identity_summary_does_not_materialize_relationship_properties() {
        let path = std::env::temp_dir().join(format!(
            "hawdb-rel-scope-cold-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let mut catalog = Catalog::default();
        let mut store = GraphStore::open_with_durability_and_replay_config(
            &path,
            &mut catalog,
            crate::config::DurabilityPolicy::SyncOnEveryWrite,
            crate::store::WalReplayConfig {
                residency_mode: crate::config::StorageResidencyMode::OutOfCore,
                ..Default::default()
            },
        )
        .unwrap();
        let a = store
            .create_node(&mut catalog, "Memory", BTreeMap::new())
            .unwrap();
        let b = store
            .create_node(&mut catalog, "Label", BTreeMap::new())
            .unwrap();
        let id = store
            .create_relationship(
                &mut catalog,
                a,
                b,
                "HAS_LABEL",
                BTreeMap::from([("body".into(), Value::String("x".repeat(1024 * 1024)))]),
            )
            .unwrap();
        store.checkpoint(&catalog).unwrap();
        assert!(store.relationships.is_empty());
        let mut stamps = VersionWriteSet::default();
        store
            .extend_relationship_read_invalidations(
                &catalog,
                &[WalOp::SetRelationshipProperty {
                    id,
                    property: "weight".into(),
                    value: Value::Int(1),
                }],
                &mut stamps,
            )
            .unwrap();
        assert!(
            stamps.contains_key(&VersionKey::ReadRelationshipDomain(Some(
                "HAS_LABEL".into()
            )))
        );
        assert!(store.relationships.is_empty());
        assert!(stamps.estimated_bytes() < 1024);
        drop(store);
        std::fs::remove_dir_all(path).unwrap();
    }

    #[test]
    fn failed_wal_never_installs_a_relationship_domain_stamp() {
        use crate::store::{set_wal_append_failpoint, WalAppendFailure};
        for failure in [
            WalAppendFailure::PartialWrite,
            WalAppendFailure::Rollback,
            WalAppendFailure::Sync,
        ] {
            let path = std::env::temp_dir().join(format!(
                "hawdb-rel-scope-wal-{}-{}",
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_nanos()
            ));
            let mut catalog = Catalog::default();
            let mut store = GraphStore::open(&path, &mut catalog).unwrap();
            let a = store
                .create_node(&mut catalog, "Memory", BTreeMap::new())
                .unwrap();
            let b = store
                .create_node(&mut catalog, "Label", BTreeMap::new())
                .unwrap();
            store
                .create_relationship(&mut catalog, a, b, "HAS_LABEL", BTreeMap::new())
                .unwrap();
            let mut read = store.capture_read_dependencies(8, 4096).unwrap();
            let key = VersionKey::ReadRelationshipDomain(Some("HAS_LABEL".into()));
            read.record(key.clone()).unwrap();
            let previous = store.version_index.stamp(&key);
            let epoch = store.commit_epoch();
            set_wal_append_failpoint(failure);
            assert!(store
                .commit_mutations(&mut catalog, vec![update(a.0, b.0)])
                .is_err());
            assert_eq!(store.version_index.stamp(&key), previous);
            assert_eq!(store.commit_epoch(), epoch);
            drop(read);
            drop(store);
            std::fs::remove_dir_all(path).unwrap();
        }
    }

    #[test]
    fn covered_row_keys_do_not_undo_a_previous_capture_refusal() {
        let store = GraphStore::default();
        let mut read = store.capture_read_dependencies(1, 4096).unwrap();
        let table = VersionKey::ReadRelationalTableDomain("rows".into());
        read.record(table.clone()).unwrap();
        assert!(read.record(VersionKey::GraphNode(NodeId(0))).is_err());
        assert!(read
            .record(VersionKey::RelationalRow {
                table: "rows".into(),
                primary_key: RelationalKey(vec![])
            })
            .is_err());
        read.record(table).unwrap();
        assert!(matches!(
            store.validate_read_dependencies(&read),
            Err(GraphReadDependencyError::CaptureRefused)
        ));
    }
}