Skip to main content

kernel/graph/
assertion_write.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//! Placement of new assertions and exact access to already held handles.
8
9use petgraph::visit::{EdgeRef, IntoEdgeReferences};
10use uuid::Uuid;
11
12use super::{
13    CapturedDelta, EdgePayload, Graph, GraphStratum, NodeKey, PredicateDeclarationError,
14    RelationKey, ResourceEdgeKey, ResourceNode, SemanticStatement, SemanticStatementSpec,
15    StatementAssert,
16};
17use crate::time::unix_epoch_millis;
18use crate::types::AssertionWithdrawal;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum StatementWriteError {
22    MissingEndpoint,
23    SurfaceContextRequired,
24    Declaration(PredicateDeclarationError),
25    HandleCollision(String),
26    AmbiguousAssertion {
27        predicate: String,
28        statement_ids: Vec<String>,
29    },
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35    use crate::graph::{
36        Author, PredicateDeclarations, predicate_declarations::PREDICATE_DECLARATIONS_FACET,
37    };
38    use crate::persistence::{PersistedResourceFacet, PersistedResourceRecord};
39
40    fn spec(predicate: &str, source: &str) -> SemanticStatementSpec {
41        SemanticStatementSpec {
42            predicate: predicate.into(),
43            provenance_iri: Some(source.into()),
44            ..Default::default()
45        }
46    }
47
48    #[test]
49    fn nature_changes_keep_held_handles_and_route_only_new_assertions() {
50        let mut graph = Graph::new();
51        let a = graph.add_node_with_id(
52            Uuid::from_u128(100),
53            "https://example.org/a".into(),
54            Default::default(),
55        );
56        let b = graph.add_node_with_id(
57            Uuid::from_u128(101),
58            "https://example.org/b".into(),
59            Default::default(),
60        );
61        let predicate = "https://example.org/predicate#rel";
62        let (resource_key, first) = graph
63            .try_assert_semantic_statement(a, b, spec(predicate, "urn:author:first"))
64            .unwrap();
65        assert!(matches!(resource_key, RelationKey::Resource(_)));
66        graph
67            .declare_predicate(predicate, GraphStratum::Surface)
68            .unwrap();
69        let mut update = spec(predicate, "urn:author:first");
70        update.label = Some("updated".into());
71        let (held_key, updated) = graph.try_assert_semantic_statement(a, b, update).unwrap();
72        assert_eq!(held_key, resource_key);
73        assert_eq!(updated.statement_id, first.statement_id);
74        let (surface_key, second) = graph
75            .try_assert_semantic_statement(a, b, spec(predicate, "urn:author:second"))
76            .unwrap();
77        assert!(matches!(surface_key, RelationKey::Surface(_)));
78        graph
79            .declare_predicate(predicate, GraphStratum::Resource)
80            .unwrap();
81        let (legacy_key, legacy) = graph
82            .try_assert_semantic_statement_by_resource_ids(
83                graph.shown_resource_id(a).unwrap(),
84                graph.shown_resource_id(b).unwrap(),
85                spec(predicate, "urn:author:second"),
86            )
87            .unwrap();
88        assert_eq!(legacy_key, surface_key);
89        assert_eq!(legacy.statement_id, second.statement_id);
90
91        assert_eq!(
92            graph
93                .find_semantic_statement(&first.statement_id)
94                .unwrap()
95                .0,
96            resource_key
97        );
98        graph.update_node_url(a, "https://example.org/later".into());
99        graph.refresh_surface_resource(a);
100        assert!(graph.retract_assertion(&first.statement_id));
101        assert!(
102            graph
103                .find_semantic_statement(&first.statement_id)
104                .unwrap()
105                .1
106                .withdrawn
107                .is_some()
108        );
109        assert!(
110            graph
111                .find_held_semantic_statement(&first.statement_id)
112                .is_none()
113        );
114        assert!(
115            graph
116                .find_semantic_statement(&second.statement_id)
117                .is_some()
118        );
119        assert!(!graph.retract_assertion("absent"));
120        assert!(graph.retract_assertion(&second.statement_id));
121    }
122
123    #[test]
124    fn conflict_blocks_new_writes_atomically_with_existing_and_unaffected_controls() {
125        let mut graph = Graph::new();
126        let a = graph.add_node_with_id(
127            Uuid::from_u128(102),
128            "https://example.org/a".into(),
129            Default::default(),
130        );
131        let b = graph.add_node_with_id(
132            Uuid::from_u128(103),
133            "https://example.org/b".into(),
134            Default::default(),
135        );
136        let predicate = "urn:predicate:conflicted";
137        let (_, held) = graph
138            .try_assert_semantic_statement(a, b, spec(predicate, "urn:author:held"))
139            .unwrap();
140        graph
141            .declare_predicate(predicate, GraphStratum::Resource)
142            .unwrap();
143        graph
144            .write_as(Author::engine("other", "2"), |g| {
145                g.declare_predicate(predicate, GraphStratum::Surface)
146            })
147            .unwrap();
148        let mut declarations = graph.predicate_declarations(predicate).unwrap().unwrap();
149        declarations.selected = None;
150        let selected = declarations.variants[0].declaration_id.clone();
151        let record = PersistedResourceRecord {
152            canonical_iri: predicate.into(),
153            facets: vec![PersistedResourceFacet {
154                facet: PREDICATE_DECLARATIONS_FACET.into(),
155                value_json: serde_json::to_string(&declarations).unwrap(),
156            }],
157        };
158        assert!(graph.set_resource_record(ResourceNode::for_term(predicate).id(), Some(record)));
159        let before = serde_json::to_value(graph.to_snapshot()).unwrap();
160        assert!(matches!(
161            graph.try_assert_semantic_statement(a, b, spec(predicate, "urn:author:new")),
162            Err(StatementWriteError::Declaration(
163                PredicateDeclarationError::Conflict { .. }
164            ))
165        ));
166        assert_eq!(serde_json::to_value(graph.to_snapshot()).unwrap(), before);
167        assert!(matches!(
168            graph.try_assert_semantic_statement_by_resource_ids(
169                graph.shown_resource_id(a).unwrap(),
170                graph.shown_resource_id(b).unwrap(),
171                spec(predicate, "urn:author:new")
172            ),
173            Err(StatementWriteError::Declaration(
174                PredicateDeclarationError::Conflict { .. }
175            ))
176        ));
177        assert_eq!(serde_json::to_value(graph.to_snapshot()).unwrap(), before);
178        let (_, existing) = graph
179            .try_assert_semantic_statement(a, b, spec(predicate, "urn:author:held"))
180            .unwrap();
181        assert_eq!(existing.statement_id, held.statement_id);
182        assert!(!existing.changed);
183        assert!(
184            graph
185                .try_assert_semantic_statement(
186                    a,
187                    b,
188                    spec("urn:predicate:unaffected", "urn:author:new")
189                )
190                .is_ok()
191        );
192        graph
193            .select_predicate_declaration(predicate, &selected)
194            .unwrap();
195        assert!(
196            graph
197                .try_assert_semantic_statement(a, b, spec(predicate, "urn:author:new"))
198                .is_ok()
199        );
200        assert!(graph.retract_assertion(&held.statement_id));
201        // The conflict's full origin records survive every assertion operation.
202        let carried: PredicateDeclarations =
203            graph.predicate_declarations(predicate).unwrap().unwrap();
204        assert_eq!(carried.variants, declarations.variants);
205    }
206
207    #[test]
208    fn caller_selected_handle_cannot_change_claim_with_distinct_handle_control() {
209        let mut graph = Graph::new();
210        let a = graph.add_node_with_id(
211            Uuid::from_u128(104),
212            "https://example.org/a".into(),
213            Default::default(),
214        );
215        let b = graph.add_node_with_id(
216            Uuid::from_u128(105),
217            "https://example.org/b".into(),
218            Default::default(),
219        );
220        let (_, held) = graph
221            .try_assert_semantic_statement(a, b, spec("urn:predicate:original", "urn:author:held"))
222            .unwrap();
223        let mut other = SemanticStatement::new(
224            "urn:predicate:other".into(),
225            None,
226            None,
227            Default::default(),
228            Some("urn:author:held".into()),
229            None,
230        );
231        let distinct = other.statement_id.clone();
232        other.statement_id = held.statement_id.clone();
233        let before = serde_json::to_value(graph.to_snapshot()).unwrap();
234        assert_eq!(
235            graph.try_assert_persisted_semantic_statement(a, b, other.clone()),
236            Err(StatementWriteError::HandleCollision(
237                held.statement_id.clone()
238            ))
239        );
240        assert_eq!(serde_json::to_value(graph.to_snapshot()).unwrap(), before);
241        other.statement_id = distinct.clone();
242        assert!(
243            graph
244                .try_assert_persisted_semantic_statement(a, b, other)
245                .is_ok()
246        );
247        assert!(graph.find_semantic_statement(&distinct).is_some());
248        assert!(graph.find_semantic_statement(&held.statement_id).is_some());
249    }
250}
251
252#[cfg(test)]
253mod migrated_handle_tests {
254    use super::*;
255
256    #[test]
257    fn ambiguous_content_requires_exact_id_and_updates_reach_the_one_row() {
258        let mut graph = Graph::new();
259        let a = graph.add_node_with_id(
260            Uuid::from_u128(106),
261            "https://example.org/a".into(),
262            Default::default(),
263        );
264        let b = graph.add_node_with_id(
265            Uuid::from_u128(107),
266            "https://example.org/b".into(),
267            Default::default(),
268        );
269        let spec = SemanticStatementSpec {
270            predicate: "urn:predicate:ambiguous".into(),
271            provenance_iri: Some("urn:author:held".into()),
272            ..Default::default()
273        };
274        let (_, first) = graph
275            .try_assert_semantic_statement(a, b, spec.clone())
276            .unwrap();
277        let pair = (
278            graph.shown_resource_id(a).unwrap(),
279            graph.shown_resource_id(b).unwrap(),
280        );
281        let mut edges = graph.persisted_resource_edges_between(pair.0, pair.1);
282        let mut other = edges[0].retained_assertions()[0].clone();
283        other.statement_id = "second-exact-handle".into();
284        edges[0].assertions.as_mut().unwrap().push(other.clone());
285        assert!(graph.set_resource_edges_between(pair.0, pair.1, &edges));
286        assert!(Graph::try_from_snapshot(&graph.to_snapshot()).is_ok());
287        let before = serde_json::to_value(graph.to_snapshot()).unwrap();
288        assert!(
289            matches!(graph.try_assert_semantic_statement(a, b, spec.clone()), Err(StatementWriteError::AmbiguousAssertion { statement_ids, .. }) if statement_ids.len() == 2)
290        );
291        assert_eq!(serde_json::to_value(graph.to_snapshot()).unwrap(), before);
292        assert!(
293            matches!(graph.try_assert_semantic_statement_by_resource_ids(pair.0, pair.1, spec.clone()),
294            Err(StatementWriteError::AmbiguousAssertion { statement_ids, .. }) if statement_ids.len() == 2)
295        );
296        assert_eq!(serde_json::to_value(graph.to_snapshot()).unwrap(), before);
297        let mut precise = graph
298            .find_semantic_statement(&other.statement_id)
299            .unwrap()
300            .1
301            .clone();
302        precise.label = Some("precise edit".into());
303        precise.basis.note = Some("precise edit".into());
304        precise.asserted_at_ms = Some(99);
305        assert!(
306            graph
307                .try_assert_persisted_semantic_statement(a, b, precise)
308                .is_ok()
309        );
310        assert_eq!(
311            graph
312                .find_semantic_statement(&first.statement_id)
313                .unwrap()
314                .1
315                .label,
316            None
317        );
318        let copies: Vec<_> = graph
319            .resource_relations()
320            .flat_map(|(_, _, _, payload)| payload.semantic_statements().iter())
321            .filter(|statement| statement.statement_id == other.statement_id)
322            .collect();
323        assert_eq!(copies.len(), 1);
324        assert!(copies.iter().all(
325            |statement| statement.label.as_deref() == Some("precise edit")
326                && statement.asserted_at_ms == Some(99)
327        ));
328        assert!(Graph::try_from_snapshot(&graph.to_snapshot()).is_ok());
329        assert!(!graph.update_assertion_metadata(
330            &other.statement_id,
331            Some("precise edit".into()),
332            Some(99)
333        ));
334        assert!(!graph.update_assertion_metadata("absent", None, None));
335        assert!(graph.retract_assertion(&first.statement_id));
336        assert!(
337            graph
338                .find_semantic_statement(&first.statement_id)
339                .unwrap()
340                .1
341                .withdrawn
342                .is_some()
343        );
344        let withdrawn_copies: Vec<_> = graph
345            .resource_relations()
346            .flat_map(|(_, _, _, payload)| payload.semantic_statements().iter())
347            .filter(|statement| statement.statement_id == first.statement_id)
348            .collect();
349        assert_eq!(withdrawn_copies.len(), 1);
350        assert!(
351            withdrawn_copies
352                .iter()
353                .all(|statement| statement.withdrawn.is_some())
354        );
355        assert!(graph.find_semantic_statement(&other.statement_id).is_some());
356        assert!(Graph::try_from_snapshot(&graph.to_snapshot()).is_ok());
357        assert!(
358            graph.try_assert_semantic_statement(a, b, spec).is_ok(),
359            "the remaining content key is unambiguous"
360        );
361        let copies: Vec<_> = graph
362            .resource_relations()
363            .flat_map(|(_, _, _, payload)| payload.semantic_statements().iter())
364            .filter(|statement| statement.statement_id == other.statement_id)
365            .collect();
366        assert_eq!(copies.len(), 1);
367        assert!(
368            copies
369                .iter()
370                .all(|statement| statement.label.is_none() && statement.asserted_at_ms == Some(99))
371        );
372        assert!(Graph::try_from_snapshot(&graph.to_snapshot()).is_ok());
373    }
374}
375
376impl std::fmt::Display for StatementWriteError {
377    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378        match self {
379            Self::MissingEndpoint => f.write_str("assertion endpoint is absent"),
380            Self::SurfaceContextRequired => f.write_str("the predicate requires Surface endpoints"),
381            Self::Declaration(error) => error.fmt(f),
382            Self::HandleCollision(id) => {
383                write!(f, "assertion handle {id:?} belongs to another claim")
384            },
385            Self::AmbiguousAssertion {
386                predicate,
387                statement_ids,
388            } => write!(
389                f,
390                "predicate {predicate:?} requires an exact assertion handle among {statement_ids:?}"
391            ),
392        }
393    }
394}
395
396impl std::error::Error for StatementWriteError {}
397
398fn matches_spec(statement: &SemanticStatement, spec: &SemanticStatementSpec) -> bool {
399    statement.withdrawn.is_none()
400        && statement.predicate == spec.predicate
401        && statement.recognized_sub_kind == spec.recognized_sub_kind
402        && statement.graph_scope == spec.graph_scope
403        && statement.provenance_iri == spec.provenance_iri
404        && statement.basis.same_reason_as(&spec.basis)
405}
406
407impl Graph {
408    pub(crate) fn held_statement_by_resource_ids(
409        &self,
410        from: Uuid,
411        to: Uuid,
412        spec: &SemanticStatementSpec,
413    ) -> Result<Option<(RelationKey, String)>, StatementWriteError> {
414        let mut matches = std::collections::BTreeMap::new();
415        for (key, payload) in self
416            .resource_relations()
417            .filter(|(_, source, target, _)| *source == from && *target == to)
418            .map(|(key, _, _, payload)| (RelationKey::Resource(key), payload))
419            .chain(
420                self.inner
421                    .inner()
422                    .edge_references()
423                    .filter(|edge| {
424                        self.shown_resource_id(edge.source()) == Some(from)
425                            && self.shown_resource_id(edge.target()) == Some(to)
426                    })
427                    .map(|edge| (RelationKey::Surface(edge.id()), edge.weight())),
428            )
429        {
430            for statement in payload
431                .assertions()
432                .iter()
433                .filter(|statement| matches_spec(statement, spec))
434            {
435                matches.insert(statement.statement_id.clone(), key);
436            }
437        }
438        if matches.len() > 1 {
439            return Err(StatementWriteError::AmbiguousAssertion {
440                predicate: spec.predicate.clone(),
441                statement_ids: matches.into_keys().collect(),
442            });
443        }
444        Ok(matches.into_iter().next().map(|(id, key)| (key, id)))
445    }
446
447    /// Assert over held Resources without creating or selecting a Surface.
448    /// Held handles keep their recorded placement, even after a nature change.
449    pub fn try_assert_semantic_statement_by_resource_ids(
450        &mut self,
451        from: Uuid,
452        to: Uuid,
453        spec: SemanticStatementSpec,
454    ) -> Result<(RelationKey, StatementAssert), StatementWriteError> {
455        let mut spec = spec.normalized();
456        if self.resource(from).is_none() || self.resource(to).is_none() {
457            return Err(StatementWriteError::MissingEndpoint);
458        }
459        if spec.provenance_iri.is_none() {
460            spec.provenance_iri = Some(self.write_author().asserter_iri());
461        }
462        if let Some((key, id)) = self.held_statement_by_resource_ids(from, to, &spec)? {
463            let changed = self.update_assertion_metadata_if_requested(
464                &id,
465                spec.label,
466                spec.asserted_at_ms,
467                Some(spec.basis),
468            );
469            return Ok((
470                key,
471                StatementAssert {
472                    statement_id: id,
473                    changed,
474                },
475            ));
476        }
477        if self
478            .effective_predicate_stratum(&spec.predicate)
479            .map_err(StatementWriteError::Declaration)?
480            != GraphStratum::Resource
481        {
482            return Err(StatementWriteError::SurfaceContextRequired);
483        }
484        let key = match self.find_resource_edge_key(from, to) {
485            Some(key) => key,
486            None => ResourceEdgeKey::from_raw(self.resources.connect(
487                self.resources.key_of(&from).expect("held source"),
488                self.resources.key_of(&to).expect("held target"),
489                EdgePayload::new(),
490            )),
491        };
492        let key = RelationKey::Resource(key);
493        spec.asserted_at_ms.get_or_insert_with(unix_epoch_millis);
494        let asserted = self
495            .get_relation_mut(key)
496            .expect("resource bucket")
497            .assert_semantic_statement(spec);
498        if asserted.changed {
499            self.bump_revision();
500            self.capture_statement_bucket(key);
501        }
502        Ok((key, asserted))
503    }
504
505    pub(crate) fn literal_statement_exists(&self, statement_id: &str) -> bool {
506        self.resource_nodes().any(|resource| {
507            self.resource_properties(resource.id())
508                .iter()
509                .any(|property| property.statement_id == statement_id)
510        }) || self.nodes().any(|(key, _)| {
511            self.legacy_node_properties(key)
512                .into_iter()
513                .flatten()
514                .any(|property| property.statement_id == statement_id)
515        })
516    }
517
518    /// Locate any retained handle, including withdrawn history, independent of
519    /// current nature. Use `find_held_semantic_statement` for default reads.
520    pub fn find_semantic_statement(
521        &self,
522        statement_id: &str,
523    ) -> Option<(RelationKey, &SemanticStatement)> {
524        self.inner
525            .inner()
526            .edge_references()
527            .map(|edge| (RelationKey::Surface(edge.id()), edge.weight()))
528            .chain(
529                self.resource_relations()
530                    .map(|(key, _, _, payload)| (RelationKey::Resource(key), payload)),
531            )
532            .find_map(|(key, payload)| {
533                payload
534                    .assertions()
535                    .iter()
536                    .find(|statement| statement.statement_id == statement_id)
537                    .map(|statement| (key, statement))
538            })
539    }
540
541    pub fn find_held_semantic_statement(
542        &self,
543        statement_id: &str,
544    ) -> Option<(RelationKey, &SemanticStatement)> {
545        self.find_semantic_statement(statement_id)
546            .filter(|(_, statement)| statement.is_held())
547    }
548
549    fn prospective_resource_pair(&self, from: NodeKey, to: NodeKey) -> Option<(Uuid, Uuid)> {
550        let identity = |key| {
551            self.shown_resource_id(key).or_else(|| {
552                self.get_node(key)
553                    .map(|node| ResourceNode::new(node.url()).id())
554            })
555        };
556        Some((identity(from)?, identity(to)?))
557    }
558
559    fn semantic_owner_matches_pair(&self, owner: RelationKey, from: NodeKey, to: NodeKey) -> bool {
560        match owner {
561            RelationKey::Surface(key) => self.inner.inner().edge_endpoints(key) == Some((from, to)),
562            RelationKey::Resource(key) => {
563                let actual = self
564                    .resources
565                    .inner()
566                    .edge_endpoints(key.raw())
567                    .map(|(a, b)| {
568                        (
569                            self.resources.node(a).unwrap().id(),
570                            self.resources.node(b).unwrap().id(),
571                        )
572                    });
573                actual == self.prospective_resource_pair(from, to)
574            },
575        }
576    }
577
578    fn held_statement_on_pair(
579        &self,
580        from: NodeKey,
581        to: NodeKey,
582        spec: &SemanticStatementSpec,
583    ) -> Result<Option<RelationKey>, StatementWriteError> {
584        let resource_pair = self.prospective_resource_pair(from, to);
585        let mut matches = std::collections::BTreeMap::new();
586        for (key, payload) in self
587            .inner
588            .inner()
589            .edges_connecting(from, to)
590            .map(|edge| (RelationKey::Surface(edge.id()), edge.weight()))
591            .chain(
592                self.resource_relations()
593                    .filter(move |(_, source, target, _)| resource_pair == Some((*source, *target)))
594                    .map(|(key, _, _, payload)| (RelationKey::Resource(key), payload)),
595            )
596        {
597            for statement in payload
598                .assertions()
599                .iter()
600                .filter(|statement| matches_spec(statement, spec))
601            {
602                matches.insert(statement.statement_id.clone(), key);
603            }
604        }
605        if matches.len() > 1 {
606            return Err(StatementWriteError::AmbiguousAssertion {
607                predicate: spec.predicate.clone(),
608                statement_ids: matches.into_keys().collect(),
609            });
610        }
611        Ok(matches.into_values().next())
612    }
613
614    fn new_statement_bucket(
615        &mut self,
616        from: NodeKey,
617        to: NodeKey,
618        predicate: &str,
619    ) -> Result<RelationKey, StatementWriteError> {
620        if self.get_node(from).is_none() || self.get_node(to).is_none() {
621            return Err(StatementWriteError::MissingEndpoint);
622        }
623        // Resolve conflicts before creating records or changing any association.
624        let stratum = self
625            .effective_predicate_stratum(predicate)
626            .map_err(StatementWriteError::Declaration)?;
627        self.relation_bucket(from, to, stratum)
628    }
629
630    pub(crate) fn relation_bucket(
631        &mut self,
632        from: NodeKey,
633        to: NodeKey,
634        stratum: GraphStratum,
635    ) -> Result<RelationKey, StatementWriteError> {
636        if self.get_node(from).is_none() || self.get_node(to).is_none() {
637            return Err(StatementWriteError::MissingEndpoint);
638        }
639        match stratum {
640            GraphStratum::Surface => Ok(RelationKey::Surface(
641                self.find_edge_key(from, to)
642                    .unwrap_or_else(|| self.inner.connect(from, to, EdgePayload::new())),
643            )),
644            GraphStratum::Resource => {
645                let source_id = self
646                    .ensure_surface_resource(from)
647                    .ok_or(StatementWriteError::MissingEndpoint)?;
648                let target_id = self
649                    .ensure_surface_resource(to)
650                    .ok_or(StatementWriteError::MissingEndpoint)?;
651                let key = match self.find_resource_edge_key(source_id, target_id) {
652                    Some(key) => key,
653                    None => {
654                        let source = self.resources.key_of(&source_id).expect("bound resource");
655                        let target = self.resources.key_of(&target_id).expect("bound resource");
656                        ResourceEdgeKey::from_raw(self.resources.connect(
657                            source,
658                            target,
659                            EdgePayload::new(),
660                        ))
661                    },
662                };
663                Ok(RelationKey::Resource(key))
664            },
665        }
666    }
667
668    /// New assertions follow the stored declaration. Reassertions keep their handle's store.
669    /// A conflict or missing endpoint returns an error without partial writes.
670    pub fn try_assert_semantic_statement(
671        &mut self,
672        from: NodeKey,
673        to: NodeKey,
674        spec: SemanticStatementSpec,
675    ) -> Result<(RelationKey, StatementAssert), StatementWriteError> {
676        let spec = spec.normalized();
677        self.try_assert_semantic_statement_with_clock(from, to, spec, true)
678    }
679
680    /// Import without a carried ID: retain the source time if present, but do
681    /// not create chronology when the source supplied none. Content ensure
682    /// keeps repeated imports idempotent until the source provides identity.
683    pub fn try_import_semantic_statement(
684        &mut self,
685        from: NodeKey,
686        to: NodeKey,
687        spec: SemanticStatementSpec,
688    ) -> Result<(RelationKey, StatementAssert), StatementWriteError> {
689        let spec = spec.normalized();
690        self.try_assert_semantic_statement_with_clock(from, to, spec, false)
691    }
692
693    fn try_assert_semantic_statement_with_clock(
694        &mut self,
695        from: NodeKey,
696        to: NodeKey,
697        mut spec: SemanticStatementSpec,
698        stamp_new: bool,
699    ) -> Result<(RelationKey, StatementAssert), StatementWriteError> {
700        if self.get_node(from).is_none() || self.get_node(to).is_none() {
701            return Err(StatementWriteError::MissingEndpoint);
702        }
703        if spec.provenance_iri.is_none() {
704            spec.provenance_iri = Some(self.write_author().asserter_iri());
705        }
706        if let Some(key) = self.held_statement_on_pair(from, to, &spec)? {
707            let statement_id = self
708                .get_relation(key)
709                .expect("held bucket")
710                .assertions()
711                .iter()
712                .find(|statement| matches_spec(statement, &spec))
713                .expect("held statement")
714                .statement_id
715                .clone();
716            let changed = self.update_assertion_metadata_if_requested(
717                &statement_id,
718                spec.label,
719                spec.asserted_at_ms,
720                Some(spec.basis),
721            );
722            return Ok((
723                key,
724                StatementAssert {
725                    statement_id,
726                    changed,
727                },
728            ));
729        }
730        if stamp_new {
731            spec.asserted_at_ms.get_or_insert_with(unix_epoch_millis);
732        }
733        let key = self.new_statement_bucket(from, to, &spec.predicate)?;
734        let outcome = self
735            .get_relation_mut(key)
736            .expect("assertion bucket")
737            .assert_semantic_statement(spec);
738        if outcome.changed {
739            self.bump_revision();
740            self.capture_statement_bucket(key);
741        }
742        Ok((key, outcome))
743    }
744
745    /// Carried handles may update their claim, but cannot select a different claim or store.
746    pub fn try_assert_persisted_semantic_statement(
747        &mut self,
748        from: NodeKey,
749        to: NodeKey,
750        mut statement: SemanticStatement,
751    ) -> Result<RelationKey, StatementWriteError> {
752        statement.normalize_basis_compat();
753        if self.get_node(from).is_none() || self.get_node(to).is_none() {
754            return Err(StatementWriteError::MissingEndpoint);
755        }
756        if self.literal_statement_exists(&statement.statement_id) {
757            return Err(StatementWriteError::HandleCollision(statement.statement_id));
758        }
759        if statement.provenance_iri.is_none() {
760            statement.provenance_iri = Some(self.write_author().asserter_iri());
761        }
762        if let Some((owner, existing)) = self.find_semantic_statement(&statement.statement_id) {
763            let pair_matches = match owner {
764                RelationKey::Surface(key) => {
765                    self.inner.inner().edge_endpoints(key) == Some((from, to))
766                },
767                RelationKey::Resource(key) => {
768                    let actual = self
769                        .resources
770                        .inner()
771                        .edge_endpoints(key.raw())
772                        .map(|(a, b)| {
773                            (
774                                self.resources.node(a).unwrap().id(),
775                                self.resources.node(b).unwrap().id(),
776                            )
777                        });
778                    actual == self.prospective_resource_pair(from, to)
779                },
780            };
781            if !pair_matches || !existing.same_claim_as(&statement) {
782                return Err(StatementWriteError::HandleCollision(statement.statement_id));
783            }
784            if existing.withdrawn.is_some() {
785                // A stale exact-ID import is observed but cannot revive a
786                // tombstone. Causal history may still carry later events.
787                return Ok(owner);
788            }
789            let statement_id = statement.statement_id.clone();
790            let existing_first = existing.first_asserted_ms;
791            let existing_last = existing.asserted_at_ms;
792            self.update_assertion_record(
793                &statement_id,
794                statement.label,
795                statement.asserted_at_ms.or(existing_last),
796                existing_first,
797                statement.withdrawn.clone(),
798                statement.basis,
799            );
800            return Ok(owner);
801        }
802        let key = self.new_statement_bucket(from, to, &statement.predicate)?;
803        if self
804            .get_relation_mut(key)
805            .expect("assertion bucket")
806            .push_persisted_semantic_statement(statement)
807        {
808            self.bump_revision();
809            self.capture_statement_bucket(key);
810        }
811        Ok(key)
812    }
813
814    /// Edit one exact held assertion without selecting a content-key survivor.
815    pub fn update_assertion_metadata(
816        &mut self,
817        statement_id: &str,
818        label: Option<String>,
819        asserted_at_ms: Option<u64>,
820    ) -> bool {
821        let Some((_, statement)) = self.find_semantic_statement(statement_id) else {
822            return false;
823        };
824        if statement.withdrawn.is_some() {
825            return false;
826        }
827        let mut basis = statement.basis.clone();
828        basis.note = label.clone();
829        if statement.basis == basis && statement.asserted_at_ms == asserted_at_ms {
830            return false;
831        }
832        let owners: Vec<_> = self
833            .inner
834            .inner()
835            .edge_references()
836            .map(|edge| (RelationKey::Surface(edge.id()), edge.weight()))
837            .chain(
838                self.resource_relations()
839                    .map(|(key, _, _, payload)| (RelationKey::Resource(key), payload)),
840            )
841            .filter(|(_, payload)| {
842                payload
843                    .assertions()
844                    .iter()
845                    .any(|statement| statement.statement_id == statement_id)
846            })
847            .map(|(key, _)| key)
848            .collect();
849        for owner in &owners {
850            let semantic = &mut self.get_relation_mut(*owner).unwrap().assertions;
851            for statement in semantic
852                .statements
853                .iter_mut()
854                .filter(|statement| statement.statement_id == statement_id)
855            {
856                statement.label = label.clone();
857                statement.basis = basis.clone();
858                statement.asserted_at_ms = asserted_at_ms;
859            }
860            semantic.rebuild_compat();
861        }
862        self.bump_revision();
863        for owner in owners {
864            self.capture_statement_bucket(owner);
865        }
866        true
867    }
868
869    pub(crate) fn update_assertion_metadata_if_requested(
870        &mut self,
871        statement_id: &str,
872        label: Option<String>,
873        asserted_at_ms: Option<u64>,
874        basis: Option<crate::types::AssertionBasis>,
875    ) -> bool {
876        let Some((_, current)) = self.find_semantic_statement(statement_id) else {
877            return false;
878        };
879        let desired_basis = basis.unwrap_or_else(|| crate::types::AssertionBasis {
880            note: label.clone(),
881            ..Default::default()
882        });
883        if current.basis == desired_basis && asserted_at_ms.is_none() {
884            return false;
885        }
886        let Some((_, current)) = self.find_semantic_statement(statement_id) else {
887            return false;
888        };
889        self.update_assertion_record(
890            statement_id,
891            desired_basis.note.clone(),
892            asserted_at_ms.or(current.asserted_at_ms),
893            current.first_asserted_ms,
894            current.withdrawn.clone(),
895            desired_basis,
896        )
897    }
898
899    fn update_assertion_record(
900        &mut self,
901        statement_id: &str,
902        label: Option<String>,
903        asserted_at_ms: Option<u64>,
904        first_asserted_ms: Option<u64>,
905        withdrawn: Option<AssertionWithdrawal>,
906        basis: crate::types::AssertionBasis,
907    ) -> bool {
908        let owners = self.semantic_statement_owner_keys(statement_id);
909        if owners.is_empty() {
910            return false;
911        }
912        let mut changed_owners = Vec::new();
913        for owner in owners {
914            let Some(data) = self
915                .get_relation_mut(owner)
916                .map(|payload| &mut payload.assertions)
917            else {
918                continue;
919            };
920            let mut changed = false;
921            for statement in data
922                .statements
923                .iter_mut()
924                .filter(|statement| statement.statement_id == statement_id)
925            {
926                if statement.label == label
927                    && statement.asserted_at_ms == asserted_at_ms
928                    && statement.first_asserted_ms == first_asserted_ms
929                    && statement.withdrawn == withdrawn
930                    && statement.basis == basis
931                {
932                    continue;
933                }
934                statement.label = label.clone();
935                statement.asserted_at_ms = asserted_at_ms;
936                statement.first_asserted_ms = first_asserted_ms;
937                statement.withdrawn = withdrawn.clone();
938                statement.basis = basis.clone();
939                changed = true;
940            }
941            if changed {
942                data.rebuild_compat();
943                changed_owners.push(owner);
944            }
945        }
946        if changed_owners.is_empty() {
947            return false;
948        }
949        self.bump_revision();
950        for owner in changed_owners {
951            self.capture_statement_bucket(owner);
952        }
953        true
954    }
955
956    fn semantic_statement_owner_keys(&self, statement_id: &str) -> Vec<RelationKey> {
957        self.inner
958            .inner()
959            .edge_references()
960            .map(|edge| (RelationKey::Surface(edge.id()), edge.weight()))
961            .chain(
962                self.resource_relations()
963                    .map(|(key, _, _, payload)| (RelationKey::Resource(key), payload)),
964            )
965            .filter(|(_, payload)| {
966                payload
967                    .assertions()
968                    .iter()
969                    .any(|statement| statement.statement_id == statement_id)
970            })
971            .map(|(key, _)| key)
972            .collect()
973    }
974
975    /// Ensure an assertion by its L13 reason key. Method version and note may
976    /// update on the same ID; a changed method IRI or evidence set creates a
977    /// new independently withdrawable assertion.
978    pub fn try_assert_semantic_reason(
979        &mut self,
980        from: NodeKey,
981        to: NodeKey,
982        mut spec: SemanticStatementSpec,
983    ) -> Result<(RelationKey, StatementAssert), StatementWriteError> {
984        spec.asserted_at_ms.get_or_insert_with(unix_epoch_millis);
985        self.try_assert_semantic_statement(from, to, spec)
986    }
987
988    /// Confirm one exact held ID. Missing caller time is stamped once here;
989    /// an unknown or withdrawn ID is never selected by matching its content.
990    pub fn reconfirm_semantic_assertion(
991        &mut self,
992        statement_id: &str,
993        label: Option<String>,
994        asserted_at_ms: Option<u64>,
995    ) -> bool {
996        let Some((key, current)) = self.find_semantic_statement(statement_id) else {
997            return false;
998        };
999        if current.withdrawn.is_some() {
1000            return false;
1001        }
1002        self.update_assertion_record(
1003            statement_id,
1004            label.clone(),
1005            Some(asserted_at_ms.unwrap_or_else(unix_epoch_millis)),
1006            current.first_asserted_ms,
1007            None,
1008            crate::types::AssertionBasis {
1009                note: label,
1010                ..current.basis.clone()
1011            },
1012        )
1013    }
1014
1015    /// Apply an exact-ID withdrawal. Unknown IDs are explicitly unapplied;
1016    /// callers with causal event streams must defer/reject until admitted.
1017    pub fn withdraw_semantic_assertion(
1018        &mut self,
1019        statement_id: &str,
1020        at_ms: Option<u64>,
1021        by: Option<String>,
1022    ) -> bool {
1023        let actor = by.or_else(|| Some(self.write_author().asserter_iri()));
1024        self.withdraw_semantic_assertion_record(
1025            statement_id,
1026            AssertionWithdrawal {
1027                at_ms: Some(at_ms.unwrap_or_else(unix_epoch_millis)),
1028                by: actor,
1029            },
1030        )
1031    }
1032
1033    /// Import/replay path: preserve missing time and never synthesize the
1034    /// clock. It returns false for unknown IDs so an event is not acknowledged.
1035    pub fn apply_imported_semantic_withdrawal(
1036        &mut self,
1037        statement_id: &str,
1038        at_ms: Option<u64>,
1039        by: Option<String>,
1040    ) -> bool {
1041        self.withdraw_semantic_assertion_record(statement_id, AssertionWithdrawal { at_ms, by })
1042    }
1043
1044    /// Apply an imported exact-ID withdrawal only when its authored pair owns
1045    /// the assertion. Source events with no carried time remain undated.
1046    pub fn apply_imported_semantic_withdrawal_for_pair(
1047        &mut self,
1048        from: NodeKey,
1049        to: NodeKey,
1050        statement_id: &str,
1051        at_ms: Option<u64>,
1052        by: Option<String>,
1053    ) -> bool {
1054        let Some((owner, _)) = self.find_semantic_statement(statement_id) else {
1055            return false;
1056        };
1057        self.semantic_owner_matches_pair(owner, from, to)
1058            && self.apply_imported_semantic_withdrawal(statement_id, at_ms, by)
1059    }
1060
1061    /// Authored pair-checked exact-ID withdrawal. It records the current time
1062    /// and configured writer only after verifying the owning bucket.
1063    pub fn withdraw_semantic_assertion_for_pair(
1064        &mut self,
1065        from: NodeKey,
1066        to: NodeKey,
1067        statement_id: &str,
1068    ) -> bool {
1069        let Some((owner, _)) = self.find_semantic_statement(statement_id) else {
1070            return false;
1071        };
1072        self.semantic_owner_matches_pair(owner, from, to)
1073            && self.withdraw_semantic_assertion(statement_id, None, None)
1074    }
1075
1076    fn withdraw_semantic_assertion_record(
1077        &mut self,
1078        statement_id: &str,
1079        withdrawal: AssertionWithdrawal,
1080    ) -> bool {
1081        let owners = self.semantic_statement_owner_keys(statement_id);
1082        let mut changed_owners = Vec::new();
1083        for owner in owners {
1084            let Some(data) = self
1085                .get_relation_mut(owner)
1086                .map(|payload| &mut payload.assertions)
1087            else {
1088                continue;
1089            };
1090            let mut changed = false;
1091            for statement in data.statements.iter_mut().filter(|statement| {
1092                statement.statement_id == statement_id && statement.withdrawn.is_none()
1093            }) {
1094                statement.withdrawn = Some(withdrawal.clone());
1095                changed = true;
1096            }
1097            if changed {
1098                data.rebuild_compat();
1099                changed_owners.push(owner);
1100            }
1101        }
1102        if changed_owners.is_empty() {
1103            return false;
1104        }
1105        self.bump_revision();
1106        for owner in changed_owners {
1107            self.capture_statement_bucket(owner);
1108        }
1109        true
1110    }
1111
1112    pub(crate) fn capture_statement_bucket(&self, key: RelationKey) {
1113        match key {
1114            RelationKey::Surface(key) => {
1115                if let Some((from, to)) = self.inner.inner().edge_endpoints(key) {
1116                    self.capture_semantic_pair(from, to);
1117                }
1118            },
1119            RelationKey::Resource(key) => {
1120                if let Some((from, to)) = self.resources.inner().edge_endpoints(key.raw()) {
1121                    self.capture_resource_pair(
1122                        self.resources.node(from).expect("resource endpoint").id(),
1123                        self.resources.node(to).expect("resource endpoint").id(),
1124                    );
1125                }
1126            },
1127        }
1128    }
1129
1130    pub(crate) fn capture_resource_pair(&self, from: Uuid, to: Uuid) {
1131        self.record_delta(&CapturedDelta::ReplaySetResourceEdgesByIds {
1132            from_resource_id: from.to_string(),
1133            to_resource_id: to.to_string(),
1134            edges: self.persisted_resource_edges_between(from, to),
1135        });
1136    }
1137
1138    /// All-family aliases retain exact owner, ID, basis and lifecycle admission.
1139    pub fn find_assertion(&self, id: &str) -> Option<(RelationKey, &SemanticStatement)> {
1140        self.find_semantic_statement(id)
1141    }
1142    pub fn find_held_assertion(&self, id: &str) -> Option<(RelationKey, &SemanticStatement)> {
1143        self.find_held_semantic_statement(id)
1144    }
1145    pub fn try_assert_relation_statement(
1146        &mut self,
1147        from: NodeKey,
1148        to: NodeKey,
1149        spec: SemanticStatementSpec,
1150    ) -> Result<(RelationKey, StatementAssert), StatementWriteError> {
1151        self.try_assert_semantic_statement(from, to, spec)
1152    }
1153    pub fn try_assert_persisted_relation_statement(
1154        &mut self,
1155        from: NodeKey,
1156        to: NodeKey,
1157        statement: SemanticStatement,
1158    ) -> Result<RelationKey, StatementWriteError> {
1159        self.try_assert_persisted_semantic_statement(from, to, statement)
1160    }
1161
1162    /// Compatibility spelling for authored exact-ID withdrawal.
1163    pub fn retract_assertion(&mut self, statement_id: &str) -> bool {
1164        self.withdraw_semantic_assertion(statement_id, None, None)
1165    }
1166}