MCPcopy Create free account
hub / github.com/atomicdotdev/atomic / canonicalize_provenance_journal

Function canonicalize_provenance_journal

atomic-agent/src/event.rs:738–820  ·  view source on GitHub ↗

Deduplicate and causally order a complete turn journal. Ready events are ordered by generation, timestamp, then stable event ID, so process arrival order cannot affect replay. Causal parents always precede children even when clocks are tied or skewed.

(
    envelopes: Vec<ProvenanceJournalEnvelope>,
)

Source from the content-addressed store, hash-verified

736/// process arrival order cannot affect replay. Causal parents always precede
737/// children even when clocks are tied or skewed.
738pub fn canonicalize_provenance_journal(
739 envelopes: Vec<ProvenanceJournalEnvelope>,
740) -> Result<Vec<ProvenanceJournalEnvelope>, ProvenanceJournalError> {
741 use std::collections::{BTreeMap, BTreeSet};
742
743 let mut by_id = BTreeMap::<String, ProvenanceJournalEnvelope>::new();
744 for mut envelope in envelopes {
745 envelope.validate()?;
746 envelope.causal_parent_ids.sort();
747 envelope.causal_parent_ids.dedup();
748 match by_id.get(&envelope.event_id) {
749 Some(existing) if existing == &envelope => continue,
750 Some(_) => {
751 return Err(ProvenanceJournalError::ConflictingEventId(
752 envelope.event_id,
753 ))
754 }
755 None => {
756 by_id.insert(envelope.event_id.clone(), envelope);
757 }
758 }
759 }
760 let Some(first) = by_id.values().next() else {
761 return Ok(Vec::new());
762 };
763 if by_id
764 .values()
765 .any(|event| event.session_id != first.session_id || event.turn_number != first.turn_number)
766 {
767 return Err(ProvenanceJournalError::MixedTurnIdentity);
768 }
769
770 let mut indegree = BTreeMap::<String, usize>::new();
771 let mut children = BTreeMap::<String, Vec<String>>::new();
772 for envelope in by_id.values() {
773 indegree.insert(envelope.event_id.clone(), envelope.causal_parent_ids.len());
774 for parent in &envelope.causal_parent_ids {
775 if !by_id.contains_key(parent) {
776 return Err(ProvenanceJournalError::MissingCausalParent {
777 event_id: envelope.event_id.clone(),
778 parent_id: parent.clone(),
779 });
780 }
781 children
782 .entry(parent.clone())
783 .or_default()
784 .push(envelope.event_id.clone());
785 }
786 }
787
788 let mut ready = BTreeSet::<(u64, i64, String)>::new();
789 for envelope in by_id.values() {
790 if indegree[&envelope.event_id] == 0 {
791 ready.insert((
792 envelope.generation,
793 envelope.timestamp_ms,
794 envelope.event_id.clone(),
795 ));

Callers 1

Calls 10

sortMethod · 0.80
contains_keyMethod · 0.80
get_mutMethod · 0.80
getMethod · 0.65
validateMethod · 0.45
insertMethod · 0.45
cloneMethod · 0.45
nextMethod · 0.45
lenMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected