Skip to main content

hawdb_storage/
consistency.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
15//! Graph statistics consistency and adjacency consolidation contracts.
16
17use crate::cow::NodeRecordRead;
18use crate::{
19    adjacency::{
20        AdjacencyDirection, AdjacencyGroupConsistencyMismatch, AdjacencyGroupKey, AdjacencyLayout,
21        AdjacencyPostingList,
22    },
23    cow::{CowSegment, CowSegmentedMap},
24    NodeId, RelId,
25};
26use hawdb_core::{BasicGraphStatistics, LabelId, RelTypeId, Value};
27use std::collections::{BTreeMap, BTreeSet};
28
29pub const DENSE_ADJACENCY_DEGREE_THRESHOLD: usize = 64;
30const MAX_ADJACENCY_CONSISTENCY_SAMPLES: usize = 32;
31
32type AdjacencyGroups = BTreeMap<AdjacencyGroupKey, BTreeSet<RelId>>;
33type NodePropertyIndex = CowSegmentedMap<(LabelId, String, Value), CowSegment<BTreeSet<NodeId>>>;
34type RelationshipPropertyIndex =
35    CowSegmentedMap<(RelTypeId, String, Value), CowSegment<BTreeSet<RelId>>>;
36
37pub fn adjacency_layout_for_degree(degree: usize) -> AdjacencyLayout {
38    if degree >= DENSE_ADJACENCY_DEGREE_THRESHOLD {
39        AdjacencyLayout::Dense
40    } else {
41        AdjacencyLayout::Sparse
42    }
43}
44
45pub fn adjacency_consolidation_plan(
46    candidates: &[AdjacencyConsolidationCandidate],
47) -> AdjacencyConsolidationPlan {
48    candidates.iter().fold(
49        AdjacencyConsolidationPlan::default(),
50        |mut plan, candidate| {
51            plan.group_count = plan.group_count.saturating_add(1);
52            plan.delta_entry_count = plan
53                .delta_entry_count
54                .saturating_add(candidate.delta_entry_count);
55            plan.estimated_entries = plan
56                .estimated_entries
57                .saturating_add(candidate.estimated_entries);
58            plan
59        },
60    )
61}
62
63pub fn maintained_adjacency_groups(
64    outgoing: &CowSegmentedMap<(NodeId, RelTypeId), AdjacencyPostingList>,
65    incoming: &CowSegmentedMap<(NodeId, RelTypeId), AdjacencyPostingList>,
66) -> AdjacencyGroups {
67    let mut groups = AdjacencyGroups::new();
68    for ((node_id, rel_type), rel_ids) in outgoing.iter() {
69        groups.insert(
70            AdjacencyGroupKey {
71                node_id: *node_id,
72                rel_type: *rel_type,
73                direction: AdjacencyDirection::Outgoing,
74            },
75            rel_ids
76                .iter_copied()
77                .map(|entry| entry.relationship_id)
78                .collect(),
79        );
80    }
81    for ((node_id, rel_type), rel_ids) in incoming.iter() {
82        groups.insert(
83            AdjacencyGroupKey {
84                node_id: *node_id,
85                rel_type: *rel_type,
86                direction: AdjacencyDirection::Incoming,
87            },
88            rel_ids
89                .iter_copied()
90                .map(|entry| entry.relationship_id)
91                .collect(),
92        );
93    }
94    groups
95}
96
97pub fn recompute_adjacency_groups(relationships: &crate::cow::CowRelMap) -> AdjacencyGroups {
98    let mut groups = AdjacencyGroups::new();
99    for relationship in relationships.values() {
100        groups
101            .entry(AdjacencyGroupKey {
102                node_id: relationship.source,
103                rel_type: relationship.rel_type,
104                direction: AdjacencyDirection::Outgoing,
105            })
106            .or_default()
107            .insert(relationship.id);
108        groups
109            .entry(AdjacencyGroupKey {
110                node_id: relationship.target,
111                rel_type: relationship.rel_type,
112                direction: AdjacencyDirection::Incoming,
113            })
114            .or_default()
115            .insert(relationship.id);
116    }
117    groups
118}
119
120pub fn compute_degree_statistics_from_adjacency(
121    nodes: &impl NodeRecordRead,
122    outgoing: &CowSegmentedMap<(NodeId, RelTypeId), AdjacencyPostingList>,
123    incoming: &CowSegmentedMap<(NodeId, RelTypeId), AdjacencyPostingList>,
124) -> BTreeMap<DegreeStatisticsKey, DegreeStatisticsEntry> {
125    compute_degree_statistics_from_groups(nodes, maintained_adjacency_groups(outgoing, incoming))
126}
127
128pub fn compute_degree_statistics_from_relationships(
129    nodes: &impl NodeRecordRead,
130    relationships: &crate::cow::CowRelMap,
131) -> BTreeMap<DegreeStatisticsKey, DegreeStatisticsEntry> {
132    compute_degree_statistics_from_groups(nodes, recompute_adjacency_groups(relationships))
133}
134
135fn compute_degree_statistics_from_groups(
136    nodes: &impl NodeRecordRead,
137    groups: AdjacencyGroups,
138) -> BTreeMap<DegreeStatisticsKey, DegreeStatisticsEntry> {
139    let rel_types = groups
140        .keys()
141        .map(|key| key.rel_type)
142        .collect::<BTreeSet<_>>();
143    let label_counts = label_counts_for_degree_statistics(nodes);
144    let mut statistics = BTreeMap::<DegreeStatisticsKey, DegreeStatisticsEntry>::new();
145    for (label_id, node_count) in &label_counts {
146        for rel_type in &rel_types {
147            for direction in [AdjacencyDirection::Outgoing, AdjacencyDirection::Incoming] {
148                statistics.insert(
149                    DegreeStatisticsKey {
150                        label_id: *label_id,
151                        rel_type: *rel_type,
152                        direction,
153                    },
154                    DegreeStatisticsEntry {
155                        node_count: *node_count,
156                        non_zero_node_count: 0,
157                        relationship_count: 0,
158                        max_degree: 0,
159                        dense_node_count: 0,
160                    },
161                );
162            }
163        }
164    }
165    for (group, rel_ids) in groups {
166        let Some(node) = nodes.get(&group.node_id) else {
167            continue;
168        };
169        let degree = rel_ids.len() as u64;
170        for label_id in &node.labels {
171            let entry = statistics
172                .entry(DegreeStatisticsKey {
173                    label_id: *label_id,
174                    rel_type: group.rel_type,
175                    direction: group.direction,
176                })
177                .or_insert(DegreeStatisticsEntry {
178                    node_count: label_counts.get(label_id).copied().unwrap_or_default(),
179                    non_zero_node_count: 0,
180                    relationship_count: 0,
181                    max_degree: 0,
182                    dense_node_count: 0,
183                });
184            entry.non_zero_node_count += 1;
185            entry.relationship_count += degree;
186            entry.max_degree = entry.max_degree.max(degree);
187            if rel_ids.len() >= DENSE_ADJACENCY_DEGREE_THRESHOLD {
188                entry.dense_node_count += 1;
189            }
190        }
191    }
192    statistics
193}
194
195fn label_counts_for_degree_statistics(nodes: &impl NodeRecordRead) -> BTreeMap<LabelId, u64> {
196    let mut label_counts = BTreeMap::new();
197    for node in nodes.values() {
198        for label_id in &node.labels {
199            *label_counts.entry(*label_id).or_default() += 1;
200        }
201    }
202    label_counts
203}
204
205pub fn adjacency_direction_sort_key(direction: AdjacencyDirection) -> u8 {
206    match direction {
207        AdjacencyDirection::Outgoing => 0,
208        AdjacencyDirection::Incoming => 1,
209    }
210}
211
212fn sample_relationship_ids(rel_ids: &BTreeSet<RelId>) -> Vec<RelId> {
213    rel_ids
214        .iter()
215        .copied()
216        .take(MAX_ADJACENCY_CONSISTENCY_SAMPLES)
217        .collect()
218}
219
220fn node_property_index_reference_count(index: &NodePropertyIndex) -> usize {
221    index.values().map(|node_ids| node_ids.len()).sum()
222}
223
224fn relationship_property_index_reference_count(index: &RelationshipPropertyIndex) -> usize {
225    index.values().map(|rel_ids| rel_ids.len()).sum()
226}
227
228fn property_index_mismatch_summary(
229    maintained: &NodePropertyIndex,
230    recomputed: &NodePropertyIndex,
231) -> (usize, usize, usize, Vec<(LabelId, String, Value)>) {
232    let mut missing_key_count = 0usize;
233    let mut extra_key_count = 0usize;
234    let mut mismatched_key_count = 0usize;
235    let mut mismatched_keys = Vec::new();
236    for key in maintained
237        .keys()
238        .chain(recomputed.keys())
239        .cloned()
240        .collect::<BTreeSet<_>>()
241    {
242        match (maintained.get(&key), recomputed.get(&key)) {
243            (Some(left), Some(right)) if left == right => {}
244            (Some(_), Some(_)) => mismatched_key_count += 1,
245            (Some(_), None) => extra_key_count += 1,
246            (None, Some(_)) => missing_key_count += 1,
247            (None, None) => {}
248        }
249        if maintained.get(&key) != recomputed.get(&key)
250            && mismatched_keys.len() < MAX_ADJACENCY_CONSISTENCY_SAMPLES
251        {
252            mismatched_keys.push(key);
253        }
254    }
255    (
256        missing_key_count,
257        extra_key_count,
258        mismatched_key_count,
259        mismatched_keys,
260    )
261}
262
263fn relationship_property_index_mismatch_summary(
264    maintained: &RelationshipPropertyIndex,
265    recomputed: &RelationshipPropertyIndex,
266) -> (usize, usize, usize, Vec<(RelTypeId, String, Value)>) {
267    let mut missing_key_count = 0usize;
268    let mut extra_key_count = 0usize;
269    let mut mismatched_key_count = 0usize;
270    let mut mismatched_keys = Vec::new();
271    for key in maintained
272        .keys()
273        .chain(recomputed.keys())
274        .cloned()
275        .collect::<BTreeSet<_>>()
276    {
277        match (maintained.get(&key), recomputed.get(&key)) {
278            (Some(left), Some(right)) if left == right => {}
279            (Some(_), Some(_)) => mismatched_key_count += 1,
280            (Some(_), None) => extra_key_count += 1,
281            (None, Some(_)) => missing_key_count += 1,
282            (None, None) => {}
283        }
284        if maintained.get(&key) != recomputed.get(&key)
285            && mismatched_keys.len() < MAX_ADJACENCY_CONSISTENCY_SAMPLES
286        {
287            mismatched_keys.push(key);
288        }
289    }
290    (
291        missing_key_count,
292        extra_key_count,
293        mismatched_key_count,
294        mismatched_keys,
295    )
296}
297
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct AdjacencyConsistencyReport {
300    pub ready: bool,
301    pub computed_at_commit_epoch: u64,
302    pub relationship_count: usize,
303    pub maintained_group_count: usize,
304    pub recomputed_group_count: usize,
305    pub dense_group_count: usize,
306    pub missing_group_count: usize,
307    pub extra_group_count: usize,
308    pub mismatched_group_count: usize,
309    pub dangling_relationship_count: usize,
310    pub mismatches: Vec<AdjacencyGroupConsistencyMismatch>,
311    pub dangling_relationship_ids: Vec<RelId>,
312}
313
314impl AdjacencyConsistencyReport {
315    pub fn new(
316        computed_at_commit_epoch: u64,
317        relationship_count: usize,
318        maintained: AdjacencyGroups,
319        recomputed: AdjacencyGroups,
320        relationships: &crate::cow::CowRelMap,
321    ) -> Self {
322        let mut missing_group_count = 0;
323        let mut extra_group_count = 0;
324        let mut mismatched_group_count = 0;
325        let mut mismatches = Vec::new();
326        let keys = maintained
327            .keys()
328            .chain(recomputed.keys())
329            .copied()
330            .collect::<BTreeSet<_>>();
331        for key in keys {
332            let maintained_ids = maintained.get(&key);
333            let recomputed_ids = recomputed.get(&key);
334            if maintained_ids == recomputed_ids {
335                continue;
336            }
337            match (maintained_ids, recomputed_ids) {
338                (None, Some(_)) => missing_group_count += 1,
339                (Some(_), None) => extra_group_count += 1,
340                (Some(_), Some(_)) => mismatched_group_count += 1,
341                (None, None) => {}
342            }
343            if mismatches.len() < MAX_ADJACENCY_CONSISTENCY_SAMPLES {
344                mismatches.push(AdjacencyGroupConsistencyMismatch {
345                    key,
346                    maintained_relationship_ids: maintained_ids
347                        .map(sample_relationship_ids)
348                        .unwrap_or_default(),
349                    recomputed_relationship_ids: recomputed_ids
350                        .map(sample_relationship_ids)
351                        .unwrap_or_default(),
352                });
353            }
354        }
355        let dangling_relationships = maintained
356            .values()
357            .flat_map(|rel_ids| rel_ids.iter().copied())
358            .filter(|rel_id| !relationships.contains_key(rel_id))
359            .collect::<BTreeSet<_>>();
360        let dangling_relationship_ids = dangling_relationships
361            .iter()
362            .copied()
363            .take(MAX_ADJACENCY_CONSISTENCY_SAMPLES)
364            .collect::<Vec<_>>();
365        let dangling_relationship_count = dangling_relationships.len();
366        let ready = missing_group_count == 0
367            && extra_group_count == 0
368            && mismatched_group_count == 0
369            && dangling_relationship_count == 0;
370        Self {
371            ready,
372            computed_at_commit_epoch,
373            relationship_count,
374            maintained_group_count: maintained.len(),
375            recomputed_group_count: recomputed.len(),
376            dense_group_count: maintained
377                .values()
378                .filter(|rel_ids| rel_ids.len() >= DENSE_ADJACENCY_DEGREE_THRESHOLD)
379                .count(),
380            missing_group_count,
381            extra_group_count,
382            mismatched_group_count,
383            dangling_relationship_count,
384            mismatches,
385            dangling_relationship_ids,
386        }
387    }
388}
389
390#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
391pub struct DegreeStatisticsKey {
392    pub label_id: LabelId,
393    pub rel_type: RelTypeId,
394    pub direction: AdjacencyDirection,
395}
396
397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398pub struct DegreeStatisticsEntry {
399    pub node_count: u64,
400    pub non_zero_node_count: u64,
401    pub relationship_count: u64,
402    pub max_degree: u64,
403    pub dense_node_count: u64,
404}
405
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct DegreeStatisticsConsistencyReport {
408    pub ready: bool,
409    pub computed_at_commit_epoch: u64,
410    pub maintained: BTreeMap<DegreeStatisticsKey, DegreeStatisticsEntry>,
411    pub recomputed: BTreeMap<DegreeStatisticsKey, DegreeStatisticsEntry>,
412    pub mismatched_keys: Vec<DegreeStatisticsKey>,
413}
414
415impl DegreeStatisticsConsistencyReport {
416    pub fn new(
417        computed_at_commit_epoch: u64,
418        maintained: BTreeMap<DegreeStatisticsKey, DegreeStatisticsEntry>,
419        recomputed: BTreeMap<DegreeStatisticsKey, DegreeStatisticsEntry>,
420    ) -> Self {
421        let mismatched_keys = maintained
422            .keys()
423            .chain(recomputed.keys())
424            .copied()
425            .collect::<BTreeSet<_>>()
426            .into_iter()
427            .filter(|key| maintained.get(key) != recomputed.get(key))
428            .take(MAX_ADJACENCY_CONSISTENCY_SAMPLES)
429            .collect::<Vec<_>>();
430        Self {
431            ready: mismatched_keys.is_empty(),
432            computed_at_commit_epoch,
433            maintained,
434            recomputed,
435            mismatched_keys,
436        }
437    }
438}
439
440#[derive(Debug, Clone, PartialEq, Eq)]
441pub struct DistinctValueStatisticsConsistencyReport {
442    pub ready: bool,
443    pub computed_at_commit_epoch: u64,
444    pub maintained_property_distinct_counts: BTreeMap<(LabelId, String), u64>,
445    pub recomputed_property_distinct_counts: BTreeMap<(LabelId, String), u64>,
446    pub maintained_rel_property_distinct_counts: BTreeMap<(RelTypeId, String), u64>,
447    pub recomputed_rel_property_distinct_counts: BTreeMap<(RelTypeId, String), u64>,
448    pub mismatched_property_keys: Vec<(LabelId, String)>,
449    pub mismatched_rel_property_keys: Vec<(RelTypeId, String)>,
450}
451
452impl DistinctValueStatisticsConsistencyReport {
453    pub fn new(
454        computed_at_commit_epoch: u64,
455        maintained_property_distinct_counts: BTreeMap<(LabelId, String), u64>,
456        recomputed_property_distinct_counts: BTreeMap<(LabelId, String), u64>,
457        maintained_rel_property_distinct_counts: BTreeMap<(RelTypeId, String), u64>,
458        recomputed_rel_property_distinct_counts: BTreeMap<(RelTypeId, String), u64>,
459    ) -> Self {
460        let mismatched_property_keys = maintained_property_distinct_counts
461            .keys()
462            .chain(recomputed_property_distinct_counts.keys())
463            .cloned()
464            .collect::<BTreeSet<_>>()
465            .into_iter()
466            .filter(|key| {
467                maintained_property_distinct_counts.get(key)
468                    != recomputed_property_distinct_counts.get(key)
469            })
470            .take(MAX_ADJACENCY_CONSISTENCY_SAMPLES)
471            .collect::<Vec<_>>();
472        let mismatched_rel_property_keys = maintained_rel_property_distinct_counts
473            .keys()
474            .chain(recomputed_rel_property_distinct_counts.keys())
475            .cloned()
476            .collect::<BTreeSet<_>>()
477            .into_iter()
478            .filter(|key| {
479                maintained_rel_property_distinct_counts.get(key)
480                    != recomputed_rel_property_distinct_counts.get(key)
481            })
482            .take(MAX_ADJACENCY_CONSISTENCY_SAMPLES)
483            .collect::<Vec<_>>();
484        Self {
485            ready: mismatched_property_keys.is_empty() && mismatched_rel_property_keys.is_empty(),
486            computed_at_commit_epoch,
487            maintained_property_distinct_counts,
488            recomputed_property_distinct_counts,
489            maintained_rel_property_distinct_counts,
490            recomputed_rel_property_distinct_counts,
491            mismatched_property_keys,
492            mismatched_rel_property_keys,
493        }
494    }
495}
496
497#[derive(Debug, Clone, PartialEq, Eq)]
498pub struct PropertyIndexConsistencyReport {
499    pub ready: bool,
500    pub computed_at_commit_epoch: u64,
501    pub node_index_entry_count: usize,
502    pub recomputed_node_index_entry_count: usize,
503    pub node_index_reference_count: usize,
504    pub recomputed_node_index_reference_count: usize,
505    pub missing_node_key_count: usize,
506    pub extra_node_key_count: usize,
507    pub mismatched_node_key_count: usize,
508    pub relationship_index_entry_count: usize,
509    pub recomputed_relationship_index_entry_count: usize,
510    pub relationship_index_reference_count: usize,
511    pub recomputed_relationship_index_reference_count: usize,
512    pub missing_relationship_key_count: usize,
513    pub extra_relationship_key_count: usize,
514    pub mismatched_relationship_key_count: usize,
515    pub mismatched_node_keys: Vec<(LabelId, String, Value)>,
516    pub mismatched_relationship_keys: Vec<(RelTypeId, String, Value)>,
517}
518
519impl PropertyIndexConsistencyReport {
520    pub fn new(
521        computed_at_commit_epoch: u64,
522        maintained_node_index: &NodePropertyIndex,
523        recomputed_node_index: &NodePropertyIndex,
524        maintained_relationship_index: &RelationshipPropertyIndex,
525        recomputed_relationship_index: &RelationshipPropertyIndex,
526    ) -> Self {
527        let (
528            missing_node_key_count,
529            extra_node_key_count,
530            mismatched_node_key_count,
531            mismatched_node_keys,
532        ) = property_index_mismatch_summary(maintained_node_index, recomputed_node_index);
533        let (
534            missing_relationship_key_count,
535            extra_relationship_key_count,
536            mismatched_relationship_key_count,
537            mismatched_relationship_keys,
538        ) = relationship_property_index_mismatch_summary(
539            maintained_relationship_index,
540            recomputed_relationship_index,
541        );
542        Self {
543            ready: missing_node_key_count == 0
544                && extra_node_key_count == 0
545                && mismatched_node_key_count == 0
546                && missing_relationship_key_count == 0
547                && extra_relationship_key_count == 0
548                && mismatched_relationship_key_count == 0,
549            computed_at_commit_epoch,
550            node_index_entry_count: maintained_node_index.len(),
551            recomputed_node_index_entry_count: recomputed_node_index.len(),
552            node_index_reference_count: node_property_index_reference_count(maintained_node_index),
553            recomputed_node_index_reference_count: node_property_index_reference_count(
554                recomputed_node_index,
555            ),
556            missing_node_key_count,
557            extra_node_key_count,
558            mismatched_node_key_count,
559            relationship_index_entry_count: maintained_relationship_index.len(),
560            recomputed_relationship_index_entry_count: recomputed_relationship_index.len(),
561            relationship_index_reference_count: relationship_property_index_reference_count(
562                maintained_relationship_index,
563            ),
564            recomputed_relationship_index_reference_count:
565                relationship_property_index_reference_count(recomputed_relationship_index),
566            missing_relationship_key_count,
567            extra_relationship_key_count,
568            mismatched_relationship_key_count,
569            mismatched_node_keys,
570            mismatched_relationship_keys,
571        }
572    }
573}
574
575#[derive(Debug, Clone, PartialEq, Eq)]
576pub struct BasicStatisticsConsistencyReport {
577    pub ready: bool,
578    pub computed_at_commit_epoch: u64,
579    pub incremental: BasicGraphStatistics,
580    pub recomputed: BasicGraphStatistics,
581    pub mismatched_fields: Vec<String>,
582}
583
584impl BasicStatisticsConsistencyReport {
585    pub fn new(incremental: BasicGraphStatistics, recomputed: BasicGraphStatistics) -> Self {
586        let mut mismatched_fields = Vec::new();
587        if incremental.computed_at_commit_epoch != recomputed.computed_at_commit_epoch {
588            mismatched_fields.push("computed_at_commit_epoch".to_string());
589        }
590        if incremental.node_count != recomputed.node_count {
591            mismatched_fields.push("node_count".to_string());
592        }
593        if incremental.relationship_count != recomputed.relationship_count {
594            mismatched_fields.push("relationship_count".to_string());
595        }
596        if incremental.label_counts != recomputed.label_counts {
597            mismatched_fields.push("label_counts".to_string());
598        }
599        if incremental.rel_type_counts != recomputed.rel_type_counts {
600            mismatched_fields.push("rel_type_counts".to_string());
601        }
602        Self {
603            ready: mismatched_fields.is_empty(),
604            computed_at_commit_epoch: incremental.computed_at_commit_epoch,
605            incremental,
606            recomputed,
607            mismatched_fields,
608        }
609    }
610}
611
612#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
613pub struct AdjacencyConsolidationPlan {
614    pub group_count: usize,
615    pub delta_entry_count: usize,
616    pub estimated_entries: usize,
617}
618
619#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
620pub struct AdjacencyConsolidationReport {
621    pub planned: AdjacencyConsolidationPlan,
622    pub consolidated_group_count: usize,
623    pub consolidated_delta_entry_count: usize,
624    pub consolidated_estimated_entries: usize,
625    pub remaining: AdjacencyConsolidationPlan,
626}
627
628#[derive(Debug, Clone, Copy)]
629pub struct AdjacencyConsolidationCandidate {
630    pub direction: AdjacencyDirection,
631    pub key: (NodeId, RelTypeId),
632    pub delta_entry_count: usize,
633    pub estimated_entries: usize,
634}