1use std::collections::{BTreeMap, BTreeSet};
11use std::fmt;
12use uuid::Uuid;
13
14use crate::graph::assertion_handles::{AssertionHandleRepeat, AssertionHandles};
15use crate::graph::resource_content::ContentError;
16use crate::graph::{Graph, GraphStratum, NavigationIndexError};
17use crate::persistence::GraphSnapshot;
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum ResourceSnapshotError {
21 UnsupportedAssertionSchema {
22 schema: u32,
23 },
24 MixedAssertionFormat {
25 column: &'static str,
26 edge_index: usize,
27 },
28 MissingCanonicalAssertions {
29 column: &'static str,
30 edge_index: usize,
31 },
32 InvalidUuid {
33 column: &'static str,
34 index: usize,
35 role: &'static str,
36 value: String,
37 },
38 NonCanonicalUuid {
39 column: &'static str,
40 edge_index: usize,
41 role: &'static str,
42 value: String,
43 },
44 InvalidFacet {
45 resource_id: Uuid,
46 facet: String,
47 detail: String,
48 },
49 DuplicateFacet {
50 resource_id: Uuid,
51 facet: String,
52 },
53 ConflictingResource {
54 resource_id: Uuid,
55 first_index: usize,
56 index: usize,
57 },
58 MissingResource {
59 column: &'static str,
60 index: usize,
61 resource_id: Uuid,
62 },
63 MissingSurface {
64 column: &'static str,
65 index: usize,
66 surface_id: Uuid,
67 },
68 LegacySemanticAggregate {
69 edge_index: usize,
70 },
71 RepeatedAssertionHandle(AssertionHandleRepeat),
72 ConflictingShownResource {
73 surface_id: Uuid,
74 first_resource: Uuid,
75 resource_id: Uuid,
76 },
77 InvalidNavigation(NavigationIndexError),
78 InvalidSurfaceId {
79 index: usize,
80 value: String,
81 },
82 RepeatedSurfaceId {
83 surface_id: Uuid,
84 first_index: usize,
85 index: usize,
86 },
87 InvalidFacets(ContentError),
89}
90
91impl fmt::Display for ResourceSnapshotError {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 match self {
94 Self::UnsupportedAssertionSchema { schema } => {
95 write!(f, "unsupported assertion schema {schema}")
96 },
97 Self::MixedAssertionFormat { column, edge_index } => write!(
98 f,
99 "{column}[{edge_index}] mixes canonical assertions with legacy assertion data"
100 ),
101 Self::MissingCanonicalAssertions { column, edge_index } => write!(
102 f,
103 "{column}[{edge_index}] has legacy assertion data without canonical assertions"
104 ),
105 Self::InvalidUuid {
106 column,
107 index,
108 role,
109 value,
110 } => write!(f, "{column}[{index}] has invalid {role} UUID {value:?}"),
111 Self::NonCanonicalUuid {
112 column,
113 edge_index,
114 role,
115 value,
116 } => write!(
117 f,
118 "{column}[{edge_index}] has noncanonical {role} UUID {value:?}"
119 ),
120 Self::InvalidFacet {
121 resource_id,
122 facet,
123 detail,
124 } => write!(
125 f,
126 "resource {resource_id} facet {facet:?} has invalid JSON: {detail}"
127 ),
128 Self::DuplicateFacet { resource_id, facet } => {
129 write!(f, "resource {resource_id} repeats facet {facet:?}")
130 },
131 Self::ConflictingResource {
132 resource_id,
133 first_index,
134 index,
135 } => write!(
136 f,
137 "resources[{index}] conflicts with resources[{first_index}] for {resource_id}"
138 ),
139 Self::MissingResource {
140 column,
141 index,
142 resource_id,
143 } => write!(
144 f,
145 "{column}[{index}] references absent resource {resource_id}"
146 ),
147 Self::MissingSurface {
148 column,
149 index,
150 surface_id,
151 } => write!(
152 f,
153 "{column}[{index}] references absent surface {surface_id}"
154 ),
155 Self::LegacySemanticAggregate { edge_index } => write!(
156 f,
157 "resource_edges[{edge_index}] has semantic data without exact assertion handles"
158 ),
159 Self::RepeatedAssertionHandle(repeat) => fmt::Display::fmt(repeat, f),
160 Self::ConflictingShownResource {
161 surface_id,
162 first_resource,
163 resource_id,
164 } => write!(
165 f,
166 "surface {surface_id} shows conflicting resources {first_resource} and {resource_id}"
167 ),
168 Self::InvalidNavigation(error) => fmt::Display::fmt(error, f),
169 Self::InvalidSurfaceId { index, value } => {
170 write!(f, "nodes[{index}] has invalid surface UUID {value:?}")
171 },
172 Self::RepeatedSurfaceId {
173 surface_id,
174 first_index,
175 index,
176 } => write!(
177 f,
178 "nodes[{index}] repeats surface {surface_id} of nodes[{first_index}]"
179 ),
180 Self::InvalidFacets(error) => write!(f, "facets refused: {error}"),
181 }
182 }
183}
184
185impl std::error::Error for ResourceSnapshotError {}
186
187fn parse_id(
188 value: &str,
189 column: &'static str,
190 index: usize,
191 role: &'static str,
192) -> Result<Uuid, ResourceSnapshotError> {
193 Uuid::parse_str(value).map_err(|_| ResourceSnapshotError::InvalidUuid {
194 column,
195 index,
196 role,
197 value: value.to_owned(),
198 })
199}
200
201fn validate_snapshot(snapshot: &GraphSnapshot) -> Result<(), ResourceSnapshotError> {
203 snapshot
204 .navigation
205 .check_indices()
206 .map_err(ResourceSnapshotError::InvalidNavigation)?;
207 let surfaces = validate_surface_ids(snapshot)?;
208 validate_resource_columns(snapshot, &surfaces)
209}
210
211fn validate_surface_ids(snapshot: &GraphSnapshot) -> Result<BTreeSet<Uuid>, ResourceSnapshotError> {
215 let mut first_indices = BTreeMap::new();
216 for (index, node) in snapshot.nodes.iter().enumerate() {
217 let surface_id = Uuid::parse_str(&node.node_id).map_err(|_| {
218 ResourceSnapshotError::InvalidSurfaceId {
219 index,
220 value: node.node_id.clone(),
221 }
222 })?;
223 if let Some(first_index) = first_indices.insert(surface_id, index) {
224 return Err(ResourceSnapshotError::RepeatedSurfaceId {
225 surface_id,
226 first_index,
227 index,
228 });
229 }
230 }
231 Ok(first_indices.into_keys().collect())
232}
233
234fn validate_resource_columns(
235 snapshot: &GraphSnapshot,
236 surfaces: &BTreeSet<Uuid>,
237) -> Result<(), ResourceSnapshotError> {
238 if snapshot.assertion_schema > 1 {
239 return Err(ResourceSnapshotError::UnsupportedAssertionSchema {
240 schema: snapshot.assertion_schema,
241 });
242 }
243 for (column, edges) in [
244 ("edges", snapshot.edges.as_slice()),
245 ("resource_edges", snapshot.resource_edges.as_slice()),
246 ] {
247 for (edge_index, edge) in edges.iter().enumerate() {
248 if edge.assertions.is_some() && edge.has_legacy_assertion_data() {
249 return Err(ResourceSnapshotError::MixedAssertionFormat { column, edge_index });
250 }
251 if snapshot.assertion_schema == 1
252 && edge.assertions.is_none()
253 && edge.has_legacy_assertion_data()
254 {
255 return Err(ResourceSnapshotError::MissingCanonicalAssertions {
256 column,
257 edge_index,
258 });
259 }
260 }
261 }
262
263 let mut resources: BTreeMap<Uuid, (usize, &str, BTreeMap<&str, serde_json::Value>)> =
264 BTreeMap::new();
265 for (index, record) in snapshot.resources.iter().enumerate() {
266 let id = chartulary::resource_id_from_canonical_iri(&record.canonical_iri);
267 crate::graph::predicate_declarations::predicate_declarations_from_record(record).map_err(
268 |error| ResourceSnapshotError::InvalidFacet {
269 resource_id: id,
270 facet: crate::graph::predicate_declarations::PREDICATE_DECLARATIONS_FACET.into(),
271 detail: error.to_string(),
272 },
273 )?;
274 crate::graph::resource_content::validate_content_record(record).map_err(|error| {
275 ResourceSnapshotError::InvalidFacet {
276 resource_id: id,
277 facet: "semantic content".into(),
278 detail: error.to_string(),
279 }
280 })?;
281 let mut facets = BTreeMap::new();
282 for facet in &record.facets {
283 let value =
284 serde_json::from_str::<serde_json::Value>(&facet.value_json).map_err(|error| {
285 ResourceSnapshotError::InvalidFacet {
286 resource_id: id,
287 facet: facet.facet.clone(),
288 detail: error.to_string(),
289 }
290 })?;
291 if facets.insert(facet.facet.as_str(), value).is_some() {
292 return Err(ResourceSnapshotError::DuplicateFacet {
293 resource_id: id,
294 facet: facet.facet.clone(),
295 });
296 }
297 }
298 if let Some((first_index, first_iri, first_facets)) = resources.get(&id) {
299 if *first_iri != record.canonical_iri.as_str() || first_facets != &facets {
300 return Err(ResourceSnapshotError::ConflictingResource {
301 resource_id: id,
302 first_index: *first_index,
303 index,
304 });
305 }
306 } else {
307 resources.insert(id, (index, record.canonical_iri.as_str(), facets));
308 }
309 }
310
311 let mut handles = AssertionHandles::new();
312 let repeated = ResourceSnapshotError::RepeatedAssertionHandle;
313 if snapshot.assertion_schema == 1 {
314 for (index, edge) in snapshot.edges.iter().enumerate() {
315 if edge.retained_assertions().is_empty() {
316 continue;
317 }
318 let from = parse_id(&edge.from_node_id, "edges", index, "source")?;
319 let to = parse_id(&edge.to_node_id, "edges", index, "target")?;
320 for (role, value, id) in [
321 ("source", &edge.from_node_id, from),
322 ("target", &edge.to_node_id, to),
323 ] {
324 if value != &id.to_string() {
325 return Err(ResourceSnapshotError::NonCanonicalUuid {
326 column: "edges",
327 edge_index: index,
328 role,
329 value: value.clone(),
330 });
331 }
332 if !surfaces.contains(&id) {
333 return Err(ResourceSnapshotError::MissingSurface {
334 column: "edges",
335 index,
336 surface_id: id,
337 });
338 }
339 }
340 handles
341 .admit(GraphStratum::Surface, edge)
342 .map_err(repeated)?;
343 }
344 } else {
345 for edge in snapshot.edges.iter().filter(|edge| {
348 [&edge.from_node_id, &edge.to_node_id]
349 .into_iter()
350 .all(|id| {
351 Uuid::parse_str(id)
352 .ok()
353 .is_some_and(|id| surfaces.contains(&id))
354 })
355 }) {
356 handles.hold_legacy_surface(edge);
357 }
358 }
359 for (index, edge) in snapshot.resource_edges.iter().enumerate() {
360 let from = parse_id(&edge.from_node_id, "resource_edges", index, "source")?;
361 let to = parse_id(&edge.to_node_id, "resource_edges", index, "target")?;
362 for (role, value, id) in [
363 ("source", &edge.from_node_id, from),
364 ("target", &edge.to_node_id, to),
365 ] {
366 if value != &id.to_string() {
367 return Err(ResourceSnapshotError::NonCanonicalUuid {
368 column: "resource_edges",
369 edge_index: index,
370 role,
371 value: value.clone(),
372 });
373 }
374 }
375 for id in [from, to] {
376 if !resources.contains_key(&id) {
377 return Err(ResourceSnapshotError::MissingResource {
378 column: "resource_edges",
379 index,
380 resource_id: id,
381 });
382 }
383 }
384 if edge.assertions.is_none()
385 && edge.semantic.as_ref().is_some_and(|semantic| {
386 semantic.statements.is_empty()
387 && (!semantic.sub_kinds.is_empty() || semantic.predicate.is_some())
388 })
389 {
390 return Err(ResourceSnapshotError::LegacySemanticAggregate { edge_index: index });
391 }
392 handles
393 .admit(GraphStratum::Resource, edge)
394 .map_err(repeated)?;
395 }
396
397 let surface_literals: BTreeSet<_> = snapshot
398 .nodes
399 .iter()
400 .filter(|node| Uuid::parse_str(&node.node_id).is_ok())
401 .flat_map(|node| {
402 node.properties
403 .iter()
404 .map(|property| property.statement_id.as_str())
405 })
406 .collect();
407 for (handle, row) in handles.rows() {
408 if surface_literals.contains(handle) {
409 return Err(ResourceSnapshotError::InvalidFacet {
410 resource_id: Uuid::parse_str(&row.from_node_id)
411 .expect("admitted rows have validated endpoints"),
412 facet: crate::graph::resource_content::RESOURCE_PROPERTIES.into(),
413 detail: format!(
414 "resource assertion handle {handle:?} reuses an active surface literal"
415 ),
416 });
417 }
418 }
419 let mut literal_owners = BTreeMap::new();
420 for record in &snapshot.resources {
421 let resource = chartulary::resource_id_from_canonical_iri(&record.canonical_iri);
422 for facet in &record.facets {
423 if facet.facet != crate::graph::resource_content::RESOURCE_PROPERTIES {
424 continue;
425 }
426 let properties: Vec<crate::types::NodeProperty> =
427 serde_json::from_str(&facet.value_json).expect("typed content validated above");
428 for property in properties {
429 let error = || ResourceSnapshotError::InvalidFacet {
430 resource_id: resource,
431 facet: facet.facet.clone(),
432 detail: format!(
433 "literal assertion handle {:?} has conflicting ownership or payload",
434 property.statement_id
435 ),
436 };
437 if handles.holds(&property.statement_id)
438 || surface_literals.contains(property.statement_id.as_str())
439 {
440 return Err(error());
441 }
442 if let Some((owner, held)) = literal_owners.get(&property.statement_id) {
443 if *owner != resource || held != &property {
444 return Err(error());
445 }
446 } else {
447 literal_owners.insert(property.statement_id.clone(), (resource, property));
448 }
449 }
450 }
451 }
452
453 let mut shown = BTreeMap::new();
454 for (index, mapping) in snapshot.shown_resources.iter().enumerate() {
455 let surface = parse_id(&mapping.surface_id, "shown_resources", index, "surface")?;
456 let resource = parse_id(&mapping.resource_id, "shown_resources", index, "resource")?;
457 if !surfaces.contains(&surface) {
458 return Err(ResourceSnapshotError::MissingSurface {
459 column: "shown_resources",
460 index,
461 surface_id: surface,
462 });
463 }
464 if !resources.contains_key(&resource) {
465 return Err(ResourceSnapshotError::MissingResource {
466 column: "shown_resources",
467 index,
468 resource_id: resource,
469 });
470 }
471 if let Some(first_resource) = shown.insert(surface, resource)
472 && first_resource != resource
473 {
474 return Err(ResourceSnapshotError::ConflictingShownResource {
475 surface_id: surface,
476 first_resource,
477 resource_id: resource,
478 });
479 }
480 }
481 Ok(())
482}
483
484impl Graph {
485 pub fn try_from_snapshot(snapshot: &GraphSnapshot) -> Result<Self, ResourceSnapshotError> {
489 validate_snapshot(snapshot)?;
490 Ok(Self::from_snapshot_unchecked(snapshot))
491 }
492
493 pub fn try_from_recorded_snapshot(
497 snapshot: &GraphSnapshot,
498 ) -> Result<Self, ResourceSnapshotError> {
499 validate_snapshot(snapshot)?;
500 Ok(Self::from_recorded_snapshot_unchecked(snapshot))
501 }
502}
503
504#[cfg(test)]
505mod assertion_schema_tests {
506 use super::*;
507 use crate::persistence::{
508 PersistedEdge, PersistedSemanticEdgeData, PersistedSemanticStatement,
509 };
510 use crate::types::{AssertionBasis, GraphScope};
511 use euclid::default::Point2D;
512
513 fn base_snapshot() -> GraphSnapshot {
514 let mut graph = Graph::new();
515 graph.add_node("https://one.test/".into(), Point2D::new(0.0, 0.0));
516 graph.add_node("https://two.test/".into(), Point2D::new(1.0, 0.0));
517 graph.to_snapshot()
518 }
519
520 fn statement(id: &str, predicate: &str) -> PersistedSemanticStatement {
521 PersistedSemanticStatement {
522 statement_id: id.into(),
523 predicate: predicate.into(),
524 recognized_sub_kind: None,
525 label: None,
526 graph_scope: GraphScope::User,
527 provenance_iri: None,
528 asserted_at_ms: None,
529 first_asserted_ms: None,
530 withdrawn: None,
531 basis: AssertionBasis::default(),
532 }
533 }
534
535 fn canonical_edge(
536 from: &str,
537 to: &str,
538 assertions: Vec<PersistedSemanticStatement>,
539 ) -> PersistedEdge {
540 PersistedEdge {
541 from_node_id: from.into(),
542 to_node_id: to.into(),
543 families: Vec::new(),
544 semantic: None,
545 traversal: None,
546 containment: None,
547 arrangement: None,
548 imported: None,
549 provenance: None,
550 assertions: Some(assertions),
551 }
552 }
553
554 #[test]
555 fn schema_gate_rejects_unknown_and_mixed_formats_but_accepts_explicit_empty() {
556 let mut snapshot = base_snapshot();
557 snapshot.assertion_schema = 9;
558 assert!(matches!(
559 Graph::try_from_snapshot(&snapshot),
560 Err(ResourceSnapshotError::UnsupportedAssertionSchema { schema: 9 })
561 ));
562
563 let mut snapshot = base_snapshot();
564 let from = snapshot.nodes[0].node_id.clone();
565 let to = snapshot.nodes[1].node_id.clone();
566 snapshot.assertion_schema = 1;
567 let mut mixed = canonical_edge(&from, &to, vec![statement("x", "urn:p")]);
568 mixed.semantic = Some(PersistedSemanticEdgeData {
569 statements: Vec::new(),
570 sub_kinds: vec![crate::persistence::PersistedSemanticSubKind::UserGrouped],
571 predicate: None,
572 label: None,
573 agent_decay_progress: None,
574 });
575 snapshot.edges.push(mixed);
576 assert!(matches!(
577 Graph::try_from_snapshot(&snapshot),
578 Err(ResourceSnapshotError::MixedAssertionFormat {
579 column: "edges",
580 edge_index: 0
581 })
582 ));
583
584 let mut resource_mixed = base_snapshot();
585 resource_mixed.assertion_schema = 1;
586 let mut legacy_resource_edge = canonical_edge("bad-from", "bad-to", vec![]);
587 legacy_resource_edge.assertions = None;
588 legacy_resource_edge.semantic = Some(PersistedSemanticEdgeData {
589 statements: Vec::new(),
590 sub_kinds: vec![crate::persistence::PersistedSemanticSubKind::UserGrouped],
591 predicate: None,
592 label: None,
593 agent_decay_progress: None,
594 });
595 resource_mixed.resource_edges.push(legacy_resource_edge);
596 assert!(matches!(
597 Graph::try_from_snapshot(&resource_mixed),
598 Err(ResourceSnapshotError::MissingCanonicalAssertions {
599 column: "resource_edges",
600 edge_index: 0
601 })
602 ));
603
604 let mut empty = base_snapshot();
605 empty.assertion_schema = 1;
606 let from = empty.nodes[0].node_id.clone();
607 let to = empty.nodes[1].node_id.clone();
608 let edge = canonical_edge(&from, &to, Vec::new());
609 let encoded = serde_json::to_value(&edge).unwrap();
610 assert_eq!(encoded["assertions"], serde_json::json!([]));
611 empty.edges.push(edge);
612 assert!(Graph::try_from_snapshot(&empty).is_ok());
613 }
614
615 #[test]
616 fn canonical_schema_requires_assertions_and_valid_surface_endpoints() {
617 let mut legacy = base_snapshot();
618 legacy.assertion_schema = 1;
619 let from = legacy.nodes[0].node_id.clone();
620 let to = legacy.nodes[1].node_id.clone();
621 let mut old = canonical_edge(&from, &to, Vec::new());
622 old.assertions = None;
623 old.semantic = Some(PersistedSemanticEdgeData {
624 statements: Vec::new(),
625 sub_kinds: vec![crate::persistence::PersistedSemanticSubKind::UserGrouped],
626 predicate: None,
627 label: None,
628 agent_decay_progress: None,
629 });
630 legacy.edges.push(old);
631 assert!(matches!(
632 Graph::try_from_snapshot(&legacy),
633 Err(ResourceSnapshotError::MissingCanonicalAssertions {
634 column: "edges",
635 edge_index: 0
636 })
637 ));
638
639 let mut orphan = base_snapshot();
640 orphan.assertion_schema = 1;
641 orphan.edges.push(canonical_edge(
642 &orphan.nodes[0].node_id,
643 &Uuid::from_u128(99).to_string(),
644 vec![statement("x", "urn:p")],
645 ));
646 assert!(matches!(
647 Graph::try_from_snapshot(&orphan),
648 Err(ResourceSnapshotError::MissingSurface { .. })
649 ));
650
651 let mut legacy_orphan = orphan;
653 legacy_orphan.assertion_schema = 0;
654 assert!(Graph::try_from_snapshot(&legacy_orphan).is_ok());
655 }
656
657 #[test]
658 fn checked_load_refuses_an_unparseable_or_repeated_surface_id() {
659 for schema in [0, 1] {
660 let mut unparseable = base_snapshot();
661 unparseable.assertion_schema = schema;
662 unparseable.nodes[1].node_id = "not-a-uuid".into();
663 let mut repeated = base_snapshot();
664 repeated.assertion_schema = schema;
665 repeated.nodes[1].node_id = repeated.nodes[0].node_id.clone();
666 let first = Uuid::parse_str(&repeated.nodes[0].node_id).unwrap();
667
668 for load in [Graph::try_from_snapshot, Graph::try_from_recorded_snapshot] {
669 assert_eq!(
670 load(&unparseable).err(),
671 Some(ResourceSnapshotError::InvalidSurfaceId {
672 index: 1,
673 value: "not-a-uuid".into()
674 })
675 );
676 assert_eq!(
677 load(&repeated).err(),
678 Some(ResourceSnapshotError::RepeatedSurfaceId {
679 surface_id: first,
680 first_index: 0,
681 index: 1
682 })
683 );
684 }
685 }
686 }
687
688 #[test]
689 fn canonical_surface_assertion_handles_are_global_and_identical_copies_are_refused() {
690 let mut snapshot = base_snapshot();
691 snapshot.assertion_schema = 1;
692 let from = snapshot.nodes[0].node_id.clone();
693 let to = snapshot.nodes[1].node_id.clone();
694 let same = statement("stable-id", "urn:p");
695 snapshot
696 .edges
697 .push(canonical_edge(&from, &to, vec![same.clone()]));
698 assert!(Graph::try_from_snapshot(&snapshot).is_ok());
699
700 let mut identical = snapshot.clone();
701 identical
702 .edges
703 .push(canonical_edge(&from, &to, vec![same.clone()]));
704 let mut reversed = snapshot.clone();
705 reversed
706 .edges
707 .push(canonical_edge(&to, &from, vec![same.clone()]));
708 let mut changed = snapshot;
709 let mut claim = same;
710 claim.predicate = "urn:other".into();
711 changed.edges.push(canonical_edge(&from, &to, vec![claim]));
712 for repeated in [identical, reversed, changed] {
713 assert!(matches!(
714 Graph::try_from_snapshot(&repeated),
715 Err(ResourceSnapshotError::RepeatedAssertionHandle(_))
716 ));
717 }
718 }
719}