hawdb 0.37.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// 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 super::*;
use hawdb_analytics::{
    LouvainProcedureOptions, PageRankProcedureOptions, ProjectedGraph, ProjectionLayout,
    ProjectionMemoryBudget, ProjectionScanControl, ProjectionSource,
};
use hawdb_core::{HawDBError, RelTypeId};
use hawdb_executor::store::{GraphExecutionRead, ScanControl};
use hawdb_storage::{NodeRecord, RelId, RelRecord};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

const NODE_COUNT: u64 = 6;
const SELECTORS: [(&str, &[&str], &[&str]); 5] = [
    ("all", &[], &[]),
    ("selected", &["Memory"], &["LINK"]),
    ("other", &["Memory", "Source"], &["OTHER"]),
    ("no_edges", &["Memory"], &["MissingType"]),
    ("no_nodes", &["MissingLabel"], &["LINK"]),
];

#[derive(Clone)]
struct Edge {
    source: u64,
    target: u64,
    kind: &'static str,
    weight: i64,
}

struct Fixture {
    db: Option<Database>,
    path: PathBuf,
    mode: StorageResidencyMode,
    edges: BTreeMap<u64, Edge>,
    next_edge: u64,
}

impl Fixture {
    fn new(mode: StorageResidencyMode, seed: u64) -> Self {
        static NEXT: AtomicU64 = AtomicU64::new(0);
        let path = loop {
            let path = std::env::temp_dir().join(format!(
                "hawdb-projection-{mode:?}-{seed}-{}-{}",
                std::process::id(),
                NEXT.fetch_add(1, Ordering::Relaxed),
            ));
            match std::fs::create_dir(&path) {
                Ok(()) => break path,
                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
                Err(error) => panic!("create projection fixture directory: {error}"),
            }
        };
        let db = Database::open_with_config(
            &path,
            DatabaseConfig {
                storage_residency_mode: mode,
                ..DatabaseConfig::default()
            },
        )
        .unwrap();
        let mut fixture = Self {
            db: Some(db),
            path,
            mode,
            edges: BTreeMap::new(),
            next_edge: 0,
        };
        for id in 0..NODE_COUNT {
            fixture
                .db()
                .query(&format!("CREATE (:{} {{id: {id}}})", node_label(id)))
                .unwrap();
        }
        // Preserve a canonical edge, a duplicate, a self-loop, another type,
        // and an edge crossing the selected node-label boundary.
        for (source, target, kind) in [
            (0, 1, "LINK"),
            (1, 2, "LINK"),
            (0, 1, "LINK"),
            (2, 2, "LINK"),
            (3, 4, "OTHER"),
            (2, 5, "LINK"),
        ] {
            fixture.append(source, target, kind);
        }
        for (name, labels, types) in SELECTORS {
            fixture
                .db()
                .query(&format!(
                    "CALL project_graph('{name}', {}, {})",
                    names(labels),
                    names(types)
                ))
                .unwrap();
        }
        fixture.db().checkpoint().unwrap();
        fixture.reopen(false);
        fixture
    }

    fn db(&mut self) -> &mut Database {
        self.db.as_mut().unwrap()
    }

    fn reopen(&mut self, read_only: bool) {
        drop(self.db.take());
        let db = Database::open_with_config(
            &self.path,
            DatabaseConfig {
                storage_residency_mode: self.mode,
                read_only,
                recovery_mode: hawdb_storage::config::RecoveryMode::Strict,
                ..DatabaseConfig::default()
            },
        )
        .unwrap();
        assert_eq!(
            db.storage_residency_report().unwrap().out_of_core,
            self.mode == StorageResidencyMode::OutOfCore
        );
        self.db = Some(db);
    }

    fn append(&mut self, source: u64, target: u64, kind: &'static str) {
        let id = self.next_edge;
        self.db().query(&format!(
            "MATCH (s:{} {{id: {source}}}), (t:{} {{id: {target}}}) CREATE (s)-[:{kind} {{rid: {id}, weight: 1}}]->(t)",
            node_label(source), node_label(target)
        )).unwrap();
        self.edges.insert(
            id,
            Edge {
                source,
                target,
                kind,
                weight: 1,
            },
        );
        self.next_edge += 1;
    }

    fn update(&mut self, id: u64, weight: i64) {
        let edge = self.edges[&id].clone();
        self.db()
            .query(&format!(
                "MATCH (s:{})-[r:{} {{rid: {id}}}]->(t:{}) SET r.weight = {weight}",
                node_label(edge.source),
                edge.kind,
                node_label(edge.target)
            ))
            .unwrap();
        self.edges.get_mut(&id).unwrap().weight = weight;
    }

    fn delete(&mut self, id: u64) {
        let edge = self.edges[&id].clone();
        self.db()
            .query(&format!(
                "MATCH (s:{})-[r:{} {{rid: {id}}}]->(t:{}) DELETE r",
                node_label(edge.source),
                edge.kind,
                node_label(edge.target)
            ))
            .unwrap();
        self.edges.remove(&id);
    }

    fn records(&self) -> Vec<RelRecord> {
        let catalog = &self.db.as_ref().unwrap().runtime.get().unwrap().catalog;
        self.edges
            .iter()
            .map(|(&id, edge)| RelRecord {
                id: RelId(id),
                source: NodeId(edge.source),
                target: NodeId(edge.target),
                rel_type: catalog.rel_type_id(edge.kind).unwrap(),
                properties: BTreeMap::from([
                    ("rid".to_string(), Value::Int(id as i64)),
                    ("weight".to_string(), Value::Int(edge.weight)),
                ]),
            })
            .collect()
    }

    fn source(&self, labels: &[&str], types: &[&str]) -> OracleSource {
        let ids: BTreeSet<_> = (0..NODE_COUNT)
            .filter(|&id| labels.is_empty() || labels.contains(&node_label(id)))
            .map(NodeId)
            .collect();
        let relationships = self
            .records()
            .into_iter()
            .filter(|record| {
                ids.contains(&record.source)
                    && ids.contains(&record.target)
                    && (types.is_empty() || types.contains(&self.edges[&record.id.0].kind))
            })
            .collect();
        OracleSource {
            nodes: ids
                .into_iter()
                .map(|id| NodeRecord {
                    id,
                    labels: BTreeSet::new(),
                    properties: BTreeMap::new(),
                })
                .collect(),
            relationships,
        }
    }

    fn verify(&mut self, selector: usize, receipt: &str) {
        let before = frontier(&self.path);
        let epoch = self.db().commit_epoch();
        let expected = self.records();
        let db = self.db.as_ref().unwrap();
        for rel_type in [
            None,
            db.runtime.get().unwrap().catalog.rel_type_id("LINK"),
            db.runtime.get().unwrap().catalog.rel_type_id("OTHER"),
            Some(RelTypeId(u32::MAX)),
        ] {
            let selected: Vec<_> = expected
                .iter()
                .filter(|record| rel_type.is_none_or(|kind| kind == record.rel_type))
                .cloned()
                .collect();
            let mut actual = Vec::new();
            let control = GraphExecutionRead::visit_relationships_owned(
                &db.runtime.get().unwrap().store,
                rel_type,
                &mut |record| {
                    actual.push(record);
                    Ok(ScanControl::Continue)
                },
            )
            .unwrap();
            assert_eq!(control, ScanControl::Continue, "{receipt}");
            assert_eq!(actual, selected, "{receipt}");
            for fail in [false, true] {
                let mut prefix = Vec::new();
                let result = GraphExecutionRead::visit_relationships_owned(
                    &db.runtime.get().unwrap().store,
                    rel_type,
                    &mut |record| {
                        prefix.push(record);
                        if fail {
                            Err(HawDBError::Semantic(
                                "relationship callback sentinel".into(),
                            ))
                        } else {
                            Ok(ScanControl::Stop)
                        }
                    },
                );
                assert_eq!(
                    prefix,
                    selected.iter().take(1).cloned().collect::<Vec<_>>(),
                    "{receipt}"
                );
                match (selected.is_empty(), fail, result) {
                    (true, _, Ok(ScanControl::Continue))
                    | (false, false, Ok(ScanControl::Stop)) => {}
                    (false, true, Err(HawDBError::Semantic(message))) => {
                        assert_eq!(message, "relationship callback sentinel", "{receipt}");
                    }
                    (_, _, result) => panic!("unexpected callback result {result:?}: {receipt}"),
                }
            }
        }

        let (name, labels, types) = SELECTORS[selector % SELECTORS.len()];
        // The oracle selects records directly from the mutation model. It
        // never scans GraphStore or calls the executor's projection adapter.
        let source = self.source(labels, types);
        let outgoing = source.project(ProjectionLayout::Outgoing);
        let undirected = source.project(ProjectionLayout::Undirected);
        let expected_rank: Vec<BTreeMap<String, Value>> = outgoing
            .page_rank_procedure_with_context(
                PageRankProcedureOptions {
                    damping: 0.5,
                    iterations: 3,
                    ..PageRankProcedureOptions::default()
                },
                None,
            )
            .unwrap()
            .into_iter()
            .map(|score| {
                BTreeMap::from([
                    ("node".into(), Value::Int(score.node.0 as i64)),
                    ("pagerank_score".into(), Value::Float(score.score)),
                ])
            })
            .collect();
        let expected_communities: Vec<BTreeMap<String, Value>> = undirected
            .louvain_procedure_with_context(
                LouvainProcedureOptions {
                    max_iterations: 3,
                    max_levels: 2,
                    hierarchy: true,
                    ..LouvainProcedureOptions::default()
                },
                None,
            )
            .unwrap()
            .into_iter()
            .map(|row| {
                BTreeMap::from([
                    ("node".into(), Value::Int(row.node.0 as i64)),
                    ("level".into(), Value::Int(row.level as i64)),
                    ("louvain_id".into(), Value::Int(row.community.0 as i64)),
                ])
            })
            .collect();
        let rank = self.db().query(&format!(
            "CALL page_rank('{name}', dampingFactor := 0.5, maxIterations := 3) RETURN node, pagerank_score"
        )).unwrap().rows.into_rows();
        let communities = self.db().query(&format!(
            "CALL louvain('{name}', maxIterations := 3, maxLevels := 2) RETURN node, level, louvain_id"
        )).unwrap().rows.into_rows();
        assert_eq!(rank, expected_rank, "{receipt}, selector={name}");
        assert_eq!(
            communities, expected_communities,
            "{receipt}, selector={name}"
        );
        assert_eq!(self.db().commit_epoch(), epoch, "{receipt}");
        assert_eq!(frontier(&self.path), before, "{receipt}");
        let out_of_core = self.mode == StorageResidencyMode::OutOfCore;
        assert_eq!(
            self.db().storage_residency_report().unwrap().out_of_core,
            out_of_core
        );
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        drop(self.db.take());
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

fn node_label(id: u64) -> &'static str {
    if id < 4 {
        "Memory"
    } else {
        "Source"
    }
}

fn names(names: &[&str]) -> String {
    format!(
        "[{}]",
        names
            .iter()
            .map(|name| format!("'{name}'"))
            .collect::<Vec<_>>()
            .join(", ")
    )
}

fn frontier(path: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
    let hawdb_storage::branch_project::ProjectManifest::Branch(selector) =
        hawdb_storage::branch_project::inspect_project_manifest(path).unwrap()
    else {
        panic!("projection fixture must use the durable main branch")
    };
    let branch = path
        .join("branches")
        .join(selector.main_branch_id().as_uuid().to_string());
    let head = hawdb_storage::branch_head::read_branch_head(&branch.join("branch.head")).unwrap();
    // Queries must preserve the actual branch publication and private WAL.
    // Legacy bootstrap files left at the project root are no longer its frontier.
    let mut files = vec![
        path.join("manifest.hawdb"),
        path.join("branches/catalog.hawdb"),
        branch.join("branch.head"),
    ];
    files.extend(
        std::fs::read_dir(&branch)
            .unwrap()
            .map(|entry| entry.unwrap())
            .filter(|entry| entry.file_name().to_string_lossy().starts_with("wal."))
            .map(|entry| entry.path()),
    );
    let result: BTreeMap<_, _> = files
        .into_iter()
        .map(|file| {
            (
                file.strip_prefix(path).unwrap().to_path_buf(),
                std::fs::read(&file).unwrap(),
            )
        })
        .collect();
    assert!(result.contains_key(Path::new("manifest.hawdb")));
    let active_wal = branch.join(hawdb_storage::artifact_files::wal_generation_file(
        head.active_wal.generation,
    ));
    assert!(
        result.contains_key(active_wal.strip_prefix(path).unwrap()),
        "frontier must include the selected branch's actual WAL generation"
    );
    result
}

struct OracleSource {
    nodes: Vec<NodeRecord>,
    relationships: Vec<RelRecord>,
}

impl OracleSource {
    fn project(&self, layout: ProjectionLayout) -> ProjectedGraph {
        ProjectedGraph::try_from_store_with_node_filter_and_layout(
            self,
            None,
            |_| true,
            layout,
            ProjectionMemoryBudget::unlimited(),
        )
        .unwrap()
    }
}

impl ProjectionSource for OracleSource {
    fn visit_projection_nodes(
        &self,
        visitor: &mut dyn FnMut(NodeRecord) -> ProjectionScanControl,
    ) -> std::result::Result<ProjectionScanControl, String> {
        for node in &self.nodes {
            if visitor(node.clone()) == ProjectionScanControl::Stop {
                return Ok(ProjectionScanControl::Stop);
            }
        }
        Ok(ProjectionScanControl::Continue)
    }

    fn visit_projection_relationships(
        &self,
        visitor: &mut dyn FnMut(RelRecord) -> ProjectionScanControl,
    ) -> std::result::Result<ProjectionScanControl, String> {
        for relationship in &self.relationships {
            if visitor(relationship.clone()) == ProjectionScanControl::Stop {
                return Ok(ProjectionScanControl::Stop);
            }
        }
        Ok(ProjectionScanControl::Continue)
    }
}

fn next_random(state: &mut u64) -> u64 {
    *state = state.wrapping_add(0x9e3779b97f4a7c15);
    let mut value = *state;
    value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
    value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb);
    value ^ (value >> 31)
}

fn campaign(seeds: std::ops::Range<u64>) {
    let first_seed = seeds.start;
    let seed_count = seeds.end - seeds.start;
    let mut checks = 0;
    for seed in seeds {
        for mode in [
            StorageResidencyMode::Materialized,
            StorageResidencyMode::OutOfCore,
        ] {
            let mut fixture = Fixture::new(mode, seed);
            for selector in 0..SELECTORS.len() {
                fixture.verify(selector, &format!("seed={seed} mode={mode:?} canonical"));
                checks += 1;
            }
            let mut random = seed;
            for step in 0..18 {
                match step % 3 {
                    0 => {
                        let source = next_random(&mut random) % NODE_COUNT;
                        let target = next_random(&mut random) % NODE_COUNT;
                        let kind = if next_random(&mut random) & 1 == 0 {
                            "LINK"
                        } else {
                            "OTHER"
                        };
                        fixture.append(source, target, kind);
                    }
                    1 => {
                        let position = if step == 1 {
                            0
                        } else {
                            next_random(&mut random) as usize % fixture.edges.len()
                        };
                        let id = *fixture.edges.keys().nth(position).unwrap();
                        fixture.update(id, step as i64 + 10);
                    }
                    _ => {
                        let position = if step == 2 {
                            1
                        } else {
                            next_random(&mut random) as usize % fixture.edges.len()
                        };
                        let id = *fixture.edges.keys().nth(position).unwrap();
                        fixture.delete(id);
                    }
                }
                let receipt = format!("seed={seed} mode={mode:?} step={step}");
                fixture.verify(step, &receipt);
                checks += 1;
                if step % 6 == 2 {
                    // Reopen with a nonempty WAL before any checkpoint can
                    // hide an incorrect base/delta merge during replay.
                    fixture.reopen(false);
                    fixture.verify(step, &format!("{receipt} wal-replay"));
                    checks += 1;
                }
                if step % 6 == 5 {
                    fixture.db().checkpoint().unwrap();
                    fixture.reopen(false);
                    fixture.verify(step, &format!("{receipt} checkpoint"));
                    checks += 1;
                }
            }
            fixture.append(0, 2, "LINK");
            for _ in 0..2 {
                fixture.reopen(true);
                fixture.verify(
                    1,
                    &format!("seed={seed} mode={mode:?} read-only-wal-replay"),
                );
                checks += 1;
            }
        }
    }
    eprintln!(
        "graph-projection-residency-v1 first_seed={first_seed} seeds={seed_count} state_checks={checks}"
    );
}

#[test]
fn projected_graph_residency_differential_smoke() {
    campaign(0..2);
}

#[test]
#[ignore = "explicit local graph projection residency campaign"]
fn projected_graph_residency_differential_campaign() {
    campaign(0..32);
}

// Keep the complete campaign above available for direct Cargo replay. Bazel
// executes both halves separately so every seed retains its full state machine
// without placing all 32 durable fixtures under one test-process timeout.
#[test]
#[ignore = "explicit local graph projection residency campaign, seeds 0..16"]
fn projected_graph_residency_differential_campaign_first_half() {
    campaign(0..16);
}

#[test]
#[ignore = "explicit local graph projection residency campaign, seeds 16..32"]
fn projected_graph_residency_differential_campaign_second_half() {
    campaign(16..32);
}

#[test]
fn projected_graph_registration_and_admission_include_canonical_edges() {
    for mode in [
        StorageResidencyMode::Materialized,
        StorageResidencyMode::OutOfCore,
    ] {
        let mut fixture = Fixture::new(mode, 0);
        let output = fixture
            .db()
            .query("CALL project_graph('fresh', ['Memory'], ['LINK'])")
            .unwrap();
        assert_eq!(output.rows[0].get("node_count"), Some(&Value::Int(4)));
        assert_eq!(output.rows[0].get("edge_count"), Some(&Value::Int(3)));
        for (algorithm, layout) in [
            ("page_rank", ProjectionLayout::Outgoing),
            ("louvain", ProjectionLayout::Undirected),
        ] {
            let bytes = fixture
                .source(&["Memory"], &["LINK"])
                .project(layout)
                .memory_estimate()
                .estimated_bytes;
            let runtime = fixture.db.as_ref().unwrap().runtime.get().unwrap();
            let resident_error = hawdb_executor::analytics::try_projected_graph_with_node_filter(
                &runtime.catalog,
                &runtime.store,
                &["Memory".into()],
                &["LINK".into()],
                |_| true,
                layout,
                ProjectionMemoryBudget::new(std::num::NonZeroUsize::new(bytes - 1).unwrap()),
            )
            .unwrap_err();
            assert!(resident_error.to_string().contains(&format!(
                "requires an estimated {bytes} bytes for 4 nodes and 4 relationships"
            )));
            drop(runtime);
            drop(fixture.db.take());
            let mut config = DatabaseConfig {
                storage_residency_mode: mode,
                read_only: true,
                recovery_mode: crate::RecoveryMode::Strict,
                ..DatabaseConfig::default()
            };
            config.execution_memory.blocking_operator_bytes =
                std::num::NonZeroUsize::new(bytes - 1).unwrap();
            fixture.db = Some(Database::open_with_config(&fixture.path, config).unwrap());
            let before = frontier(&fixture.path);
            let epoch = fixture.db().commit_epoch();
            let error = fixture
                .db()
                .query(&format!("CALL {algorithm}('selected')"))
                .unwrap_err();
            // Reads use the query allowance; retained streaming state and
            // its key grants still obey the one-below projection allowance.
            let message = error.to_string();
            assert!(
                message.contains("GraphAlgorithm")
                    && (message.contains(&format!("blocking_operator_bytes {}", bytes - 1))
                        || (message.contains("blocking_state")
                            && message.contains(&format!("{}-byte budget", bytes - 1)))),
                "{mode:?} {algorithm}: {error}"
            );
            assert_eq!(fixture.db().commit_epoch(), epoch);
            assert_eq!(frontier(&fixture.path), before);
        }
    }
}

#[test]
fn projected_graph_relationship_corruption_fails_without_partial_results() {
    for algorithm in ["page_rank", "louvain"] {
        let mut fixture = Fixture::new(StorageResidencyMode::OutOfCore, 0);
        // Publish a fresh generation without reopening: startup may have
        // cached verified segments, which must not mask this injected read error.
        fixture.db().checkpoint().unwrap();
        let before = frontier(&fixture.path);
        let epoch = fixture.db().commit_epoch();
        // Canonical relationship segments follow the node segments. Corrupt
        // only the final relationship payload, leaving the header/length intact.
        let generation = fixture
            .db()
            .storage_residency_report()
            .unwrap()
            .canonical_generation
            .unwrap();
        let canonical = super::super::active_storage_root(&fixture.path)
            .join(format!("canonical.{generation}.hawdb"));
        let mut bytes = std::fs::read(&canonical).unwrap();
        *bytes.last_mut().unwrap() ^= 0xff;
        std::fs::write(canonical, bytes).unwrap();
        let mut nodes = 0;
        GraphExecutionRead::visit_nodes_owned(
            &fixture.db().runtime.get().unwrap().store,
            None,
            &mut |_| {
                nodes += 1;
                Ok(ScanControl::Continue)
            },
        )
        .unwrap();
        assert_eq!(nodes, NODE_COUNT);
        let error = fixture
            .db()
            .query(&format!("CALL {algorithm}('selected')"))
            .unwrap_err();
        assert!(
            error.to_string().contains("content digest verification"),
            "{error}"
        );
        assert_eq!(
            fixture
                .db()
                .storage_residency_report()
                .unwrap()
                .segment_cache_digest_mismatch_count,
            1
        );
        assert_eq!(fixture.db().commit_epoch(), epoch);
        assert_eq!(frontier(&fixture.path), before);
    }
}