Skip to main content

kernel/graph/
resource_pair_bounds.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//! Bounded live capture of a resource pair for exact replacement.
8
9use std::collections::BTreeSet;
10use std::io::{self, Write};
11
12use serde::ser::{SerializeSeq, SerializeStruct};
13use serde::{Serialize, Serializer};
14use uuid::Uuid;
15
16use super::{EdgeFamily, EdgePayload, Graph, SemanticStatement};
17use crate::graph::edge_data::TraversalData;
18use crate::persistence::PersistedEdge;
19use crate::types::GraphScope;
20
21/// A bounded pair capture refused without returning any partial rows.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ResourceEdgesBoundError {
24    MissingEndpoint,
25    EdgeLimitExceeded,
26    ByteLimitExceeded,
27    Serialization,
28}
29
30impl std::fmt::Display for ResourceEdgesBoundError {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        let message = match self {
33            Self::MissingEndpoint => "resource pair endpoint missing",
34            Self::EdgeLimitExceeded => "resource pair edge limit exceeded",
35            Self::ByteLimitExceeded => "resource pair byte limit exceeded",
36            Self::Serialization => "resource pair serialization failed",
37        };
38        f.write_str(message)
39    }
40}
41
42impl std::error::Error for ResourceEdgesBoundError {}
43
44impl Graph {
45    /// Capture all live rows for a directed resource pair, including session
46    /// assertions omitted from durable snapshots. This is suitable for exact
47    /// replacement, not a substitute for a durable graph snapshot.
48    ///
49    /// `max_edges` limits pair rows. `max_bytes` independently limits each of
50    /// the raw payload and returned row JSON arrays, including array framing.
51    /// Both limits are checked before cloning any persisted rows. Pair lookup
52    /// scans source adjacency metadata; unrelated payloads are not serialized.
53    pub fn persisted_resource_edges_between_bounded(
54        &self,
55        from: Uuid,
56        to: Uuid,
57        max_edges: usize,
58        max_bytes: usize,
59    ) -> Result<Vec<PersistedEdge>, ResourceEdgesBoundError> {
60        let (Some(source), Some(target)) =
61            (self.resources.key_of(&from), self.resources.key_of(&to))
62        else {
63            return Err(ResourceEdgesBoundError::MissingEndpoint);
64        };
65        let pair = || self.resources.inner().edges_connecting(source, target);
66        let mut count = 0usize;
67        for _ in pair() {
68            if count == max_edges {
69                return Err(ResourceEdgesBoundError::EdgeLimitExceeded);
70            }
71            count += 1;
72        }
73
74        measure_array(pair().map(|edge| edge.weight()), max_bytes)?;
75        measure_array(
76            pair().map(|edge| BorrowedEdge::new(from, to, edge.weight())),
77            max_bytes,
78        )?;
79
80        Ok(pair()
81            .map(|edge| {
82                let payload = edge.weight();
83                let mut persisted = super::snapshot::persisted_edge_for_ids(from, to, payload);
84                persisted.assertions = Some(
85                    payload
86                        .assertions()
87                        .iter()
88                        .map(super::snapshot::to::persisted_assertion)
89                        .collect(),
90                );
91                persisted
92            })
93            .collect())
94    }
95}
96
97struct BoundedWriter {
98    bytes: usize,
99    limit: usize,
100    exceeded: bool,
101}
102
103impl Write for BoundedWriter {
104    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
105        match self.bytes.checked_add(buffer.len()) {
106            Some(total) if total <= self.limit => {
107                self.bytes = total;
108                Ok(buffer.len())
109            },
110            _ => {
111                self.exceeded = true;
112                Err(io::Error::other("byte limit exceeded"))
113            },
114        }
115    }
116    fn flush(&mut self) -> io::Result<()> {
117        Ok(())
118    }
119}
120
121fn measure_array<I, T>(items: I, limit: usize) -> Result<(), ResourceEdgesBoundError>
122where
123    I: IntoIterator<Item = T>,
124    T: Serialize,
125{
126    let mut writer = BoundedWriter {
127        bytes: 0,
128        limit,
129        exceeded: false,
130    };
131    let result = (|| -> Result<(), serde_json::Error> {
132        writer.write_all(b"[").map_err(serde_json::Error::io)?;
133        let mut first = true;
134        for item in items {
135            if !first {
136                writer.write_all(b",").map_err(serde_json::Error::io)?;
137            }
138            first = false;
139            serde_json::to_writer(&mut writer, &item)?;
140        }
141        writer.write_all(b"]").map_err(serde_json::Error::io)?;
142        Ok(())
143    })();
144    match result {
145        Ok(()) => Ok(()),
146        Err(_) if writer.exceeded => Err(ResourceEdgesBoundError::ByteLimitExceeded),
147        Err(_) => Err(ResourceEdgesBoundError::Serialization),
148    }
149}
150
151// Borrow the live data while matching PersistedEdge's JSON shape. The parity
152// test detects any change in the canonical conversion or serialized shape.
153#[derive(Serialize)]
154pub(super) struct BorrowedEdge<'a> {
155    from_node_id: String,
156    to_node_id: String,
157    families: BTreeSet<EdgeFamily>,
158    semantic: Option<()>,
159    traversal: Option<&'a TraversalData>,
160    containment: Option<()>,
161    arrangement: Option<()>,
162    imported: Option<()>,
163    provenance: Option<()>,
164    assertions: BorrowedAssertions<'a>,
165}
166
167impl<'a> BorrowedEdge<'a> {
168    pub(super) fn new(from: Uuid, to: Uuid, payload: &'a EdgePayload) -> Self {
169        Self {
170            from_node_id: from.to_string(),
171            to_node_id: to.to_string(),
172            families: payload.families(),
173            semantic: None,
174            traversal: payload.traversal_data(),
175            containment: None,
176            arrangement: None,
177            imported: None,
178            provenance: None,
179            assertions: BorrowedAssertions(payload.assertions()),
180        }
181    }
182}
183
184struct BorrowedAssertions<'a>(&'a [SemanticStatement]);
185
186impl Serialize for BorrowedAssertions<'_> {
187    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
188        let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
189        for statement in self.0 {
190            seq.serialize_element(&BorrowedStatement(statement))?;
191        }
192        seq.end()
193    }
194}
195
196struct BorrowedStatement<'a>(&'a SemanticStatement);
197
198impl Serialize for BorrowedStatement<'_> {
199    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
200        let statement = self.0;
201        let mut state = serializer.serialize_struct("PersistedSemanticStatement", 10)?;
202        state.serialize_field("statement_id", &statement.statement_id)?;
203        state.serialize_field("predicate", &statement.predicate)?;
204        if statement.recognized_sub_kind.is_some() {
205            state.serialize_field("recognized_sub_kind", &statement.recognized_sub_kind)?;
206        }
207        if statement.label.is_some() {
208            state.serialize_field("label", &statement.label)?;
209        }
210        if statement.graph_scope != GraphScope::Default {
211            state.serialize_field("graph_scope", &statement.graph_scope)?;
212        }
213        if statement.provenance_iri.is_some() {
214            state.serialize_field("provenance_iri", &statement.provenance_iri)?;
215        }
216        if statement.asserted_at_ms.is_some() {
217            state.serialize_field("asserted_at_ms", &statement.asserted_at_ms)?;
218        }
219        if statement.first_asserted_ms.is_some() || statement.asserted_at_ms.is_some() {
220            state.serialize_field("first_asserted_ms", &statement.first_asserted_ms)?;
221        }
222        if statement.withdrawn.is_some() {
223            state.serialize_field("withdrawn", &statement.withdrawn)?;
224        }
225        if !statement.basis.is_empty() || statement.label.is_some() {
226            state.serialize_field("basis", &statement.basis)?;
227        }
228        state.end()
229    }
230}