Skip to main content

kernel/graph/
assertion_handles.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! The one rule for assertion handles over persisted edge rows: a handle
8//! names one assertion on one row, across both strata. A repeat is refused
9//! whether or not the copy is identical. Checked load and both freezes ask
10//! here; none of them decides legality on its own.
11
12use super::GraphStratum;
13use crate::persistence::PersistedEdge;
14use std::collections::BTreeMap;
15use std::fmt;
16
17/// The row that holds a handle, as a refusal names it.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct HandleRow {
20    pub stratum: GraphStratum,
21    pub from: String,
22    pub to: String,
23}
24
25impl HandleRow {
26    fn of(stratum: GraphStratum, row: &PersistedEdge) -> Self {
27        Self {
28            stratum,
29            from: row.from_node_id.clone(),
30            to: row.to_node_id.clone(),
31        }
32    }
33}
34
35/// A handle that appears a second time.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct AssertionHandleRepeat {
38    pub statement_id: String,
39    pub first: HandleRow,
40    pub again: HandleRow,
41}
42
43impl fmt::Display for AssertionHandleRepeat {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        let site = |row: &HandleRow| format!("{:?} pair {} -> {}", row.stratum, row.from, row.to);
46        write!(
47            f,
48            "assertion handle {:?} repeats: held on {} and again on {}; one handle means one row",
49            self.statement_id,
50            site(&self.first),
51            site(&self.again)
52        )
53    }
54}
55
56impl std::error::Error for AssertionHandleRepeat {}
57
58/// Handles held so far, each with the row that holds it.
59#[derive(Default)]
60pub struct AssertionHandles<'a> {
61    held: BTreeMap<&'a str, (GraphStratum, &'a PersistedEdge)>,
62    legacy: BTreeMap<&'a str, &'a PersistedEdge>,
63}
64
65impl<'a> AssertionHandles<'a> {
66    pub fn new() -> Self {
67        Self::default()
68    }
69
70    /// Hold every handle of `row`; the first one already held is refused.
71    pub fn admit(
72        &mut self,
73        stratum: GraphStratum,
74        row: &'a PersistedEdge,
75    ) -> Result<(), AssertionHandleRepeat> {
76        for statement in row.retained_assertions() {
77            let id = statement.statement_id.as_str();
78            let first = self
79                .held
80                .get(id)
81                .copied()
82                .or_else(|| self.legacy.get(id).map(|row| (GraphStratum::Surface, *row)));
83            if let Some((first, first_row)) = first {
84                return Err(AssertionHandleRepeat {
85                    statement_id: id.to_owned(),
86                    first: HandleRow::of(first, first_row),
87                    again: HandleRow::of(stratum, row),
88                });
89            }
90            self.held.insert(id, (stratum, row));
91        }
92        Ok(())
93    }
94
95    /// Schema 0 Surface rows predate canonical handles, so repeats among them
96    /// stay loadable. Rows admitted later still may not reuse their handles.
97    pub fn hold_legacy_surface(&mut self, row: &'a PersistedEdge) {
98        for statement in row.retained_assertions() {
99            self.legacy
100                .entry(statement.statement_id.as_str())
101                .or_insert(row);
102        }
103    }
104
105    pub fn holds(&self, handle: &str) -> bool {
106        self.held.contains_key(handle) || self.legacy.contains_key(handle)
107    }
108
109    /// Admitted handles with their rows, in handle order.
110    pub fn rows(&self) -> impl Iterator<Item = (&'a str, &'a PersistedEdge)> + '_ {
111        self.held.iter().map(|(handle, (_, row))| (*handle, *row))
112    }
113}
114
115/// Refuse the first handle that repeats across `rows`.
116pub fn validate_assertion_handles<'a>(
117    rows: impl IntoIterator<Item = (GraphStratum, &'a PersistedEdge)>,
118) -> Result<(), AssertionHandleRepeat> {
119    let mut handles = AssertionHandles::new();
120    rows.into_iter()
121        .try_for_each(|(stratum, row)| handles.admit(stratum, row))
122}