Skip to main content

kernel/graph/
relation_read.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//! Relation reads across explicitly identified graph strata.
8
9use petgraph::Direction;
10use petgraph::visit::{EdgeRef, IntoEdgeReferences};
11use uuid::Uuid;
12
13use super::{EdgePayload, Graph, NodeKey, RelationKey, ResourceEdgeKey};
14
15impl Graph {
16    /// Read the owning store named by this relation handle.
17    pub fn get_relation(&self, key: RelationKey) -> Option<&EdgePayload> {
18        match key {
19            RelationKey::Surface(key) => self.get_edge(key),
20            RelationKey::Resource(key) => self.get_resource_edge(key),
21        }
22    }
23
24    pub(crate) fn get_relation_mut(&mut self, key: RelationKey) -> Option<&mut EdgePayload> {
25        match key {
26            RelationKey::Surface(key) => self.get_edge_mut(key),
27            RelationKey::Resource(key) => self.resources.edge_mut(key.raw()),
28        }
29    }
30
31    /// Read a resource edge without accepting a surface edge index.
32    pub fn get_resource_edge(&self, key: ResourceEdgeKey) -> Option<&EdgePayload> {
33        self.resources.edge(key.raw())
34    }
35
36    /// Find the first directed resource edge between resource identities.
37    pub fn find_resource_edge_key(&self, from: Uuid, to: Uuid) -> Option<ResourceEdgeKey> {
38        let (from, to) = (self.resources.key_of(&from)?, self.resources.key_of(&to)?);
39        self.resources
40            .inner()
41            .find_edge(from, to)
42            .map(ResourceEdgeKey::from_raw)
43    }
44
45    /// Every retained Resource edge, with a typed handle and stable endpoints.
46    /// This raw storage iterator includes tombstone-only buckets for history;
47    /// ordinary projected reads filter to held topology.
48    pub fn resource_relations(
49        &self,
50    ) -> impl Iterator<Item = (ResourceEdgeKey, Uuid, Uuid, &EdgePayload)> {
51        self.resources.inner().edge_references().map(|edge| {
52            (
53                ResourceEdgeKey::from_raw(edge.id()),
54                self.resources
55                    .node(edge.source())
56                    .expect("resource endpoint exists")
57                    .id(),
58                self.resources
59                    .node(edge.target())
60                    .expect("resource endpoint exists")
61                    .id(),
62                edge.weight(),
63            )
64        })
65    }
66
67    /// All retained Surface edges followed by retained edges between the
68    /// resources shown, including tombstone-only assertion history.
69    /// Parallel records and self-loops each appear once per directed pair.
70    pub fn retained_relations_between(
71        &self,
72        from: NodeKey,
73        to: NodeKey,
74    ) -> impl Iterator<Item = (RelationKey, &EdgePayload)> {
75        let surface_pair = self
76            .inner
77            .contains_node(from)
78            .then_some(from)
79            .zip(self.inner.contains_node(to).then_some(to));
80        let resource_pair = self
81            .shown_resource_id(from)
82            .zip(self.shown_resource_id(to))
83            .and_then(|(from, to)| self.resources.key_of(&from).zip(self.resources.key_of(&to)));
84        let surface = surface_pair.into_iter().flat_map(move |(from, to)| {
85            self.inner
86                .inner()
87                .edges_connecting(from, to)
88                .map(|edge| (RelationKey::Surface(edge.id()), edge.weight()))
89        });
90        let resource = resource_pair.into_iter().flat_map(move |(from, to)| {
91            self.resources
92                .inner()
93                .edges_connecting(from, to)
94                .map(|edge| {
95                    (
96                        RelationKey::Resource(ResourceEdgeKey::from_raw(edge.id())),
97                        edge.weight(),
98                    )
99                })
100        });
101        surface.chain(resource)
102    }
103
104    /// Directed held Surface edges followed by held edges between the
105    /// resources shown. Use `retained_relations_between` for explicit history.
106    pub fn projected_relations_between(
107        &self,
108        from: NodeKey,
109        to: NodeKey,
110    ) -> impl Iterator<Item = (RelationKey, &EdgePayload)> {
111        self.retained_relations_between(from, to)
112            .filter(|(_, payload)| payload.has_held_topology())
113    }
114
115    /// Outgoing relations lifted to every surface showing their target resource.
116    pub fn projected_outgoing_relations(
117        &self,
118        from: NodeKey,
119    ) -> impl Iterator<Item = (NodeKey, RelationKey, &EdgePayload)> {
120        self.projected_adjacent_relations(from, Direction::Outgoing)
121    }
122
123    /// Incoming relations lifted from every surface showing their source resource.
124    pub fn projected_incoming_relations(
125        &self,
126        to: NodeKey,
127    ) -> impl Iterator<Item = (NodeKey, RelationKey, &EdgePayload)> {
128        self.projected_adjacent_relations(to, Direction::Incoming)
129    }
130
131    fn projected_adjacent_relations(
132        &self,
133        surface: NodeKey,
134        direction: Direction,
135    ) -> impl Iterator<Item = (NodeKey, RelationKey, &EdgePayload)> {
136        let surface_key = self.inner.contains_node(surface).then_some(surface);
137        let resource_key = self
138            .shown_resource_id(surface)
139            .and_then(|id| self.resources.key_of(&id));
140        let direct = surface_key.into_iter().flat_map(move |surface| {
141            self.inner
142                .inner()
143                .edges_directed(surface, direction)
144                .filter(|edge| edge.weight().has_held_topology())
145                .map(move |edge| {
146                    let neighbor = match direction {
147                        Direction::Outgoing => edge.target(),
148                        Direction::Incoming => edge.source(),
149                    };
150                    (neighbor, RelationKey::Surface(edge.id()), edge.weight())
151                })
152        });
153        let lifted = resource_key
154            .into_iter()
155            .flat_map(move |resource| self.resources.inner().edges_directed(resource, direction))
156            .filter(|edge| edge.weight().has_held_topology())
157            .flat_map(move |edge| {
158                let neighbor = match direction {
159                    Direction::Outgoing => edge.target(),
160                    Direction::Incoming => edge.source(),
161                };
162                let id = self
163                    .resources
164                    .node(neighbor)
165                    .expect("resource endpoint exists")
166                    .id();
167                self.shown_resources
168                    .iter()
169                    .filter_map(move |(surface, resource)| {
170                        (*resource == id)
171                            .then(|| self.get_node_key_by_id(*surface))
172                            .flatten()
173                            .map(|surface| {
174                                (
175                                    surface,
176                                    RelationKey::Resource(ResourceEdgeKey::from_raw(edge.id())),
177                                    edge.weight(),
178                                )
179                            })
180                    })
181            });
182        direct.chain(lifted)
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189    use crate::graph::{EdgeAssertion, ResourceNode, SemanticStatement, SemanticSubKind};
190    use crate::persistence::PersistedResourceRecord;
191    use crate::types::GraphScope;
192    use euclid::default::Point2D;
193    use petgraph::stable_graph::EdgeIndex;
194
195    fn surface(graph: &mut Graph, iri: &str) -> NodeKey {
196        graph.add_node(iri.into(), Point2D::zero())
197    }
198
199    fn resource(graph: &mut Graph, iri: &str) -> Uuid {
200        let node = ResourceNode::for_term(iri);
201        assert!(graph.set_resource_record(
202            node.id(),
203            Some(PersistedResourceRecord {
204                canonical_iri: iri.into(),
205                facets: vec![],
206            })
207        ));
208        node.id()
209    }
210
211    fn payload(id: &str, predicate: &str) -> EdgePayload {
212        let mut payload = EdgePayload::new();
213        payload.push_persisted_semantic_statement(SemanticStatement {
214            statement_id: id.into(),
215            predicate: predicate.into(),
216            recognized_sub_kind: None,
217            label: None,
218            graph_scope: GraphScope::Default,
219            provenance_iri: Some("https://author.test/".into()),
220            asserted_at_ms: Some(17),
221            first_asserted_ms: Some(17),
222            withdrawn: None,
223            basis: Default::default(),
224        });
225        payload
226    }
227
228    fn pair(graph: &mut Graph, from: Uuid, to: Uuid, ids: &[&str], predicate: &str) {
229        let edges: Vec<_> = ids
230            .iter()
231            .map(|id| {
232                super::super::snapshot::persisted_edge_for_ids(from, to, &payload(id, predicate))
233            })
234            .collect();
235        assert!(graph.set_resource_edges_between(from, to, &edges));
236    }
237
238    #[test]
239    fn relation_read_equal_indices_select_only_the_named_store() {
240        let mut graph = Graph::new();
241        let a = surface(&mut graph, "https://surface.test/a");
242        let b = surface(&mut graph, "https://surface.test/b");
243        let surface_handle = graph
244            .assert_relation(
245                a,
246                b,
247                EdgeAssertion::Semantic {
248                    sub_kind: SemanticSubKind::UserGrouped,
249                    label: None,
250                },
251            )
252            .unwrap();
253        let RelationKey::Surface(surface_key) = surface_handle else {
254            panic!("surface writer handle")
255        };
256        let ra = resource(&mut graph, "https://resource.test/a");
257        let rb = resource(&mut graph, "https://resource.test/b");
258        pair(
259            &mut graph,
260            ra,
261            rb,
262            &["resource-cites"],
263            super::super::predicate_iri(SemanticSubKind::Cites),
264        );
265        let resource_key = graph.find_resource_edge_key(ra, rb).unwrap();
266        assert_eq!(surface_key.index(), 0);
267        assert_eq!(resource_key.raw().index(), 0);
268        assert!(
269            graph
270                .get_edge(surface_key)
271                .unwrap()
272                .semantic_statements()
273                .iter()
274                .any(|s| s.recognized_sub_kind == Some(SemanticSubKind::UserGrouped))
275        );
276        assert_eq!(
277            graph.get_relation(surface_handle),
278            graph.get_edge(surface_key)
279        );
280        assert_eq!(
281            graph.get_relation(RelationKey::Resource(resource_key)),
282            graph.get_resource_edge(resource_key)
283        );
284        assert_eq!(
285            graph
286                .get_resource_edge(resource_key)
287                .unwrap()
288                .semantic_statements()[0]
289                .statement_id,
290            "resource-cites"
291        );
292        assert_eq!(graph.find_edge_key(a, b), Some(surface_key));
293        let c = surface(&mut graph, "https://surface.test/c");
294        let RelationKey::Surface(surface_only) = graph
295            .assert_relation(
296                a,
297                c,
298                EdgeAssertion::Semantic {
299                    sub_kind: SemanticSubKind::UserGrouped,
300                    label: None,
301                },
302            )
303            .unwrap()
304        else {
305            panic!("surface writer handle")
306        };
307        assert!(graph.get_edge(surface_only).is_some());
308        let absent_resource = ResourceEdgeKey::from_raw(surface_only);
309        assert!(graph.get_resource_edge(absent_resource).is_none());
310        assert!(
311            graph
312                .get_relation(RelationKey::Resource(absent_resource))
313                .is_none()
314        );
315        assert!(graph.get_edge(EdgeIndex::new(99)).is_none());
316        assert_eq!(graph.resource_relations().count(), 1);
317    }
318
319    #[test]
320    fn relation_read_projection_preserves_parallel_direction_and_binding_fanout() {
321        let mut graph = Graph::new();
322        let a = surface(&mut graph, "https://surface.test/a");
323        let b = surface(&mut graph, "https://surface.test/b");
324        let alias = surface(&mut graph, "https://surface.test/alias");
325        let unbound = surface(&mut graph, "https://surface.test/unbound");
326        let ra = resource(&mut graph, "https://resource.test/a");
327        let rb = resource(&mut graph, "https://resource.test/b");
328        let iri = "https://schema.org/citation";
329        pair(&mut graph, ra, rb, &["forward-1", "forward-2"], iri);
330        pair(&mut graph, rb, ra, &["backward"], iri);
331        pair(&mut graph, ra, ra, &["self"], iri);
332        graph.assert_relation(
333            a,
334            b,
335            EdgeAssertion::Semantic {
336                sub_kind: SemanticSubKind::UserGrouped,
337                label: None,
338            },
339        );
340        assert_eq!(graph.projected_relations_between(a, b).count(), 1);
341        assert_eq!(graph.projected_outgoing_relations(unbound).count(), 0);
342        assert!(graph.set_shown_resource(graph.get_node(a).unwrap().id, Some(ra)));
343        assert!(graph.set_shown_resource(graph.get_node(b).unwrap().id, Some(rb)));
344        assert!(graph.set_shown_resource(graph.get_node(alias).unwrap().id, Some(rb)));
345        assert_eq!(graph.projected_relations_between(a, b).count(), 3);
346        assert_eq!(graph.projected_relations_between(a, alias).count(), 2);
347        assert_eq!(graph.projected_relations_between(b, a).count(), 1);
348        assert_eq!(graph.projected_relations_between(a, a).count(), 1);
349        let outgoing: Vec<_> = graph.projected_outgoing_relations(a).collect();
350        assert_eq!(outgoing.len(), 6); // direct + two parallel edges to two surfaces + self
351        assert_eq!(
352            outgoing
353                .iter()
354                .filter(|(neighbor, key, _)| *neighbor == alias
355                    && matches!(key, RelationKey::Resource(_)))
356                .count(),
357            2
358        );
359        assert_eq!(graph.projected_incoming_relations(b).count(), 3);
360        assert_eq!(graph.projected_incoming_relations(a).count(), 3); // two sources + self
361        assert!(graph.set_shown_resource(graph.get_node(alias).unwrap().id, None));
362        assert_eq!(graph.projected_outgoing_relations(a).count(), 4);
363        assert_eq!(graph.projected_relations_between(a, alias).count(), 0);
364        assert_eq!(graph.resource_relations().count(), 4);
365    }
366
367    #[test]
368    fn relation_read_display_role_uses_shown_content_with_surface_control() {
369        let mut graph = Graph::new();
370        let source = surface(&mut graph, "https://surface.test/source");
371        let target = surface(&mut graph, "urn:mere:bnode:document:_:author");
372        let legacy = surface(&mut graph, "urn:mere:bnode:document:_:publisher");
373        graph.assert_surface_semantic_statement(
374            source,
375            legacy,
376            super::super::SemanticStatementSpec {
377                predicate: "https://schema.org/publisher".into(),
378                ..Default::default()
379            },
380        );
381        assert_eq!(graph.node_display_label(legacy), "publisher");
382        let from = resource(&mut graph, "https://resource.test/page");
383        let to = resource(&mut graph, "urn:mere:bnode:document:_:author");
384        pair(
385            &mut graph,
386            from,
387            to,
388            &["author-role"],
389            "https://schema.org/author",
390        );
391        assert_eq!(graph.node_display_label(target), "node _:author");
392        assert!(graph.set_shown_resource(graph.get_node(source).unwrap().id, Some(from)));
393        assert!(graph.set_shown_resource(graph.get_node(target).unwrap().id, Some(to)));
394        assert_eq!(graph.node_display_label(target), "author");
395        assert_eq!(graph.node_display_label(legacy), "publisher");
396    }
397}