use std::cell::RefCell;
use std::collections::BTreeMap;
use std::sync::Arc;
use chartulary::stemma::TransitionKind;
use euclid::default::Point2D;
use rkyv::{Archive, Deserialize, Serialize};
use uuid::Uuid;
use super::apply::{GraphDelta, GraphDeltaResult, apply_graph_delta};
use super::{
Coupling, CouplingResponse, EdgeAssertion, Field, FieldDefinition, FieldExtent, FieldId,
FieldLifecycle, FrameLayoutHint, Graph, NavigationTrigger, NodeSelector, RelationSelector,
};
use crate::persistence::{
PersistedCoupling, PersistedCouplingResponse, PersistedEdge, PersistedField,
PersistedFieldExtent, PersistedFieldLifecycle, PersistedNodeSelector, PersistedResourceRecord,
};
use crate::types::{
BadgeIcon, ClassificationScheme, ClassificationStatus, ImageRef, ImageRole, ImportRecord,
NodeClassification, NodeDerivation, NodeProperty,
};
mod edge_assertion_compat;
mod replay_outcome;
pub(crate) use replay_outcome::replay_outcomes_onto;
pub use replay_outcome::{Malformed, Replay, Unwritable};
#[cfg(test)]
mod decay_compat_tests;
#[cfg(test)]
mod replay_outcome_tests;
#[derive(
Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
)]
pub enum CapturedDelta {
ReplayAddNodeWithIdIfMissing {
id: String,
url: String,
position: [f32; 2],
},
ReplayAssertRelationByIds {
from_id: String,
to_id: String,
#[serde(with = "edge_assertion_compat")]
#[rkyv(with = edge_assertion_compat::Rkyv)]
assertion: EdgeAssertion,
},
ReplayRemoveNodeById {
node_id: String,
},
ReplayRetractRelationsByIds {
from_id: String,
to_id: String,
selector: RelationSelector,
},
ReplayAppendTraversalByIds {
from_id: String,
to_id: String,
trigger: NavigationTrigger,
timestamp_ms: u64,
},
ReplaySetNodeTitleById {
node_id: String,
title: String,
},
ReplaySetNodeUrlById {
node_id: String,
new_url: String,
},
ReplaySetNodeImageById {
node_id: String,
role: ImageRole,
image: ImageRef,
},
ReplaySetNodeThumbnailById {
node_id: String,
png_bytes: Vec<u8>,
width: u32,
height: u32,
},
ReplaySetNodeFaviconById {
node_id: String,
rgba: Vec<u8>,
width: u32,
height: u32,
},
ReplaySetNodeMimeHintById {
node_id: String,
mime_hint: Option<String>,
},
ReplaySetNodeNestedById {
node_id: String,
nested: Option<String>,
},
ReplaySetNodePinnedById {
node_id: String,
is_pinned: bool,
},
ReplaySetNodeFacetById {
node_id: String,
facet: String,
value_json: String,
},
ReplayRemoveNodeFacetById {
node_id: String,
facet: String,
},
ReplayInsertNodeTagById {
node_id: String,
tag: String,
},
ReplayRemoveNodeTagById {
node_id: String,
tag: String,
},
ReplaySetNodeBodyById {
node_id: String,
body: Option<String>,
},
ReplayNavigateNodeById {
node_id: String,
url: String,
transition: TransitionKind,
timestamp_ms: u64,
last_session_visited: u64,
},
ReplayBranchHistoryByIds {
child_id: String,
parent_id: String,
},
ReplayNodeHistoryBackById {
node_id: String,
timestamp_ms: u64,
},
ReplayNodeHistoryForwardById {
node_id: String,
timestamp_ms: u64,
},
ReplayAppendNodePropertyById {
node_id: String,
property: NodeProperty,
},
ReplayAddNodeClassificationById {
node_id: String,
classification: NodeClassification,
},
ReplayRemoveNodeClassificationById {
node_id: String,
scheme: ClassificationScheme,
value: String,
},
ReplaySetNodeClassificationStatusById {
node_id: String,
scheme: ClassificationScheme,
value: String,
status: ClassificationStatus,
},
ReplaySetNodePrimaryClassificationById {
node_id: String,
scheme: ClassificationScheme,
value: String,
},
ReplayRecordNodeDerivationById {
node_id: String,
derivation: NodeDerivation,
},
ReplaySetNodeTagIconOverrideById {
node_id: String,
tag: String,
icon: Option<BadgeIcon>,
},
ReplaySetEdgeSemanticPredicateByIds {
from_id: String,
to_id: String,
predicate: Option<String>,
},
ReplayAssertSemanticPredicateByIds {
from_id: String,
to_id: String,
predicate: String,
},
ReplayAppendFrameLayoutHintById {
node_id: String,
hint: FrameLayoutHint,
},
ReplayRemoveFrameLayoutHintById {
node_id: String,
hint_index: usize,
},
ReplayMoveFrameLayoutHintById {
node_id: String,
from_index: usize,
to_index: usize,
},
ReplaySetFrameSplitOfferSuppressedById {
node_id: String,
suppressed: bool,
},
ReplayUpdateNodeHistoryById {
node_id: String,
entries: Vec<String>,
current_index: usize,
},
ReplaySetImportRecords {
import_records: Vec<ImportRecord>,
},
ReplaySetEdgesByIds {
from_id: String,
to_id: String,
edges: Vec<PersistedEdge>,
},
ReplayTouchNodeLastVisitedById {
node_id: String,
timestamp_ms: u64,
},
ReplayAddField {
field: PersistedField,
},
ReplayRetireFieldById {
field_id: String,
},
ReplayRemoveFieldById {
field_id: String,
},
ReplayAddCoupling {
coupling: PersistedCoupling,
},
ReplaySetFieldCouplingStrengthByFieldId {
field_id: String,
strength: f32,
},
ReplayActivateFieldById {
field_id: String,
},
ReplayRetractCouplingById {
coupling_id: String,
},
ReplaySetNodeContentById {
node_id: String,
content: Option<[u8; 32]>,
},
ReplaySetResourceRecordById {
resource_id: String,
record: Option<PersistedResourceRecord>,
},
ReplaySetResourceEdgesByIds {
from_resource_id: String,
to_resource_id: String,
edges: Vec<PersistedEdge>,
},
ReplaySetShownResourceById {
surface_id: String,
resource_id: Option<String>,
},
}
impl CapturedDelta {
pub fn replay(&self) -> Replay {
Replay::Apply(match self {
Self::ReplayAddNodeWithIdIfMissing { id, url, position } => {
GraphDelta::ReplayAddNodeWithIdIfMissing {
id: parse_uuid(id),
url: url.clone(),
position: Point2D::new(position[0], position[1]),
}
},
Self::ReplayAssertRelationByIds {
from_id,
to_id,
assertion,
} => GraphDelta::ReplayAssertRelationByIds {
from_id: parse_uuid(from_id),
to_id: parse_uuid(to_id),
assertion: assertion.clone(),
asserter_iri: super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into(),
},
Self::ReplayRemoveNodeById { node_id } => GraphDelta::ReplayRemoveNodeById {
node_id: parse_uuid(node_id),
},
Self::ReplayRetractRelationsByIds {
from_id,
to_id,
selector,
} => GraphDelta::ReplayRetractRelationsByIds {
from_id: parse_uuid(from_id),
to_id: parse_uuid(to_id),
selector: *selector,
},
Self::ReplayAppendTraversalByIds {
from_id,
to_id,
trigger,
timestamp_ms,
} => GraphDelta::ReplayAppendTraversalByIds {
from_id: parse_uuid(from_id),
to_id: parse_uuid(to_id),
trigger: *trigger,
timestamp_ms: *timestamp_ms,
},
Self::ReplaySetNodeTitleById { node_id, title } => GraphDelta::ReplaySetNodeTitleById {
node_id: parse_uuid(node_id),
title: title.clone(),
},
Self::ReplaySetNodeUrlById { node_id, new_url } => GraphDelta::ReplaySetNodeUrlById {
node_id: parse_uuid(node_id),
new_url: new_url.clone(),
},
Self::ReplaySetNodeImageById {
node_id,
role,
image,
} => GraphDelta::ReplaySetNodeImageById {
node_id: parse_uuid(node_id),
role: *role,
image: *image,
},
Self::ReplaySetNodeThumbnailById { .. } | Self::ReplaySetNodeFaviconById { .. } => {
return Replay::Skip;
},
Self::ReplaySetNodeMimeHintById { node_id, mime_hint } => {
GraphDelta::ReplaySetNodeMimeHintById {
node_id: parse_uuid(node_id),
mime_hint: mime_hint.clone(),
}
},
Self::ReplaySetNodeContentById { node_id, content } => {
GraphDelta::ReplaySetNodeContentById {
node_id: parse_uuid(node_id),
content: content.map(muniment::Hash::from_bytes),
}
},
Self::ReplaySetNodeNestedById { node_id, nested } => {
GraphDelta::ReplaySetNodeNestedById {
node_id: parse_uuid(node_id),
nested: nested.clone(),
}
},
Self::ReplaySetNodePinnedById { node_id, is_pinned } => {
GraphDelta::ReplaySetNodePinnedById {
node_id: parse_uuid(node_id),
is_pinned: *is_pinned,
}
},
Self::ReplaySetNodeFacetById {
node_id,
facet,
value_json,
} => {
let value = match serde_json::from_str(value_json) {
Ok(value) => value,
Err(error) => return Replay::Malformed(Malformed::new(node_id, facet, error)),
};
GraphDelta::ReplaySetNodeFacetById {
node_id: parse_uuid(node_id),
facet: facet.clone(),
value,
}
},
Self::ReplayRemoveNodeFacetById { node_id, facet } => {
GraphDelta::ReplayRemoveNodeFacetById {
node_id: parse_uuid(node_id),
facet: facet.clone(),
}
},
Self::ReplayInsertNodeTagById { node_id, tag } => GraphDelta::ReplayInsertNodeTagById {
node_id: parse_uuid(node_id),
tag: tag.clone(),
},
Self::ReplayRemoveNodeTagById { node_id, tag } => GraphDelta::ReplayRemoveNodeTagById {
node_id: parse_uuid(node_id),
tag: tag.clone(),
},
Self::ReplaySetNodeBodyById { node_id, body } => GraphDelta::ReplaySetNodeBodyById {
node_id: parse_uuid(node_id),
body: body.clone(),
},
Self::ReplayNavigateNodeById {
node_id,
url,
transition,
timestamp_ms,
last_session_visited,
} => GraphDelta::ReplayNavigateNodeById {
node_id: parse_uuid(node_id),
url: url.clone(),
transition: *transition,
timestamp_ms: *timestamp_ms,
last_session_visited: *last_session_visited,
},
Self::ReplayBranchHistoryByIds {
child_id,
parent_id,
} => GraphDelta::ReplayBranchHistoryByIds {
child_id: parse_uuid(child_id),
parent_id: parse_uuid(parent_id),
},
Self::ReplayNodeHistoryBackById {
node_id,
timestamp_ms,
} => GraphDelta::ReplayNodeHistoryBackById {
node_id: parse_uuid(node_id),
timestamp_ms: *timestamp_ms,
},
Self::ReplayNodeHistoryForwardById {
node_id,
timestamp_ms,
} => GraphDelta::ReplayNodeHistoryForwardById {
node_id: parse_uuid(node_id),
timestamp_ms: *timestamp_ms,
},
Self::ReplayAppendNodePropertyById { node_id, property } => {
GraphDelta::ReplayAppendNodePropertyById {
node_id: parse_uuid(node_id),
property: property.clone(),
}
},
Self::ReplayAddNodeClassificationById {
node_id,
classification,
} => GraphDelta::ReplayAddNodeClassificationById {
node_id: parse_uuid(node_id),
classification: classification.clone(),
},
Self::ReplayRemoveNodeClassificationById {
node_id,
scheme,
value,
} => GraphDelta::ReplayRemoveNodeClassificationById {
node_id: parse_uuid(node_id),
scheme: scheme.clone(),
value: value.clone(),
},
Self::ReplaySetNodeClassificationStatusById {
node_id,
scheme,
value,
status,
} => GraphDelta::ReplaySetNodeClassificationStatusById {
node_id: parse_uuid(node_id),
scheme: scheme.clone(),
value: value.clone(),
status: status.clone(),
},
Self::ReplaySetNodePrimaryClassificationById {
node_id,
scheme,
value,
} => GraphDelta::ReplaySetNodePrimaryClassificationById {
node_id: parse_uuid(node_id),
scheme: scheme.clone(),
value: value.clone(),
},
Self::ReplayRecordNodeDerivationById {
node_id,
derivation,
} => GraphDelta::ReplayRecordNodeDerivationById {
node_id: parse_uuid(node_id),
derivation: derivation.clone(),
},
Self::ReplaySetNodeTagIconOverrideById { node_id, tag, icon } => {
GraphDelta::ReplaySetNodeTagIconOverrideById {
node_id: parse_uuid(node_id),
tag: tag.clone(),
icon: icon.clone(),
}
},
Self::ReplaySetEdgeSemanticPredicateByIds {
from_id,
to_id,
predicate,
} => GraphDelta::ReplaySetEdgeSemanticPredicateByIds {
from_id: parse_uuid(from_id),
to_id: parse_uuid(to_id),
predicate: predicate.clone(),
asserter_iri: super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into(),
},
Self::ReplayAssertSemanticPredicateByIds {
from_id,
to_id,
predicate,
} => GraphDelta::ReplayAssertSemanticPredicateByIds {
from_id: parse_uuid(from_id),
to_id: parse_uuid(to_id),
predicate: predicate.clone(),
asserter_iri: super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into(),
},
Self::ReplayAppendFrameLayoutHintById { node_id, hint } => {
GraphDelta::ReplayAppendFrameLayoutHintById {
node_id: parse_uuid(node_id),
hint: hint.clone(),
}
},
Self::ReplayRemoveFrameLayoutHintById {
node_id,
hint_index,
} => GraphDelta::ReplayRemoveFrameLayoutHintById {
node_id: parse_uuid(node_id),
hint_index: *hint_index,
},
Self::ReplayMoveFrameLayoutHintById {
node_id,
from_index,
to_index,
} => GraphDelta::ReplayMoveFrameLayoutHintById {
node_id: parse_uuid(node_id),
from_index: *from_index,
to_index: *to_index,
},
Self::ReplaySetFrameSplitOfferSuppressedById {
node_id,
suppressed,
} => GraphDelta::ReplaySetFrameSplitOfferSuppressedById {
node_id: parse_uuid(node_id),
suppressed: *suppressed,
},
Self::ReplayUpdateNodeHistoryById {
node_id,
entries,
current_index,
} => GraphDelta::ReplayUpdateNodeHistoryById {
node_id: parse_uuid(node_id),
entries: entries.clone(),
current_index: *current_index,
},
Self::ReplaySetImportRecords { import_records } => GraphDelta::ReplaySetImportRecords {
import_records: import_records.clone(),
},
Self::ReplaySetEdgesByIds {
from_id,
to_id,
edges,
} => GraphDelta::ReplaySetEdgesByIds {
from_id: parse_uuid(from_id),
to_id: parse_uuid(to_id),
edges: edges.clone(),
},
Self::ReplaySetResourceRecordById {
resource_id,
record,
} => GraphDelta::ReplaySetResourceRecordById {
resource_id: parse_uuid(resource_id),
record: record.clone(),
},
Self::ReplaySetResourceEdgesByIds {
from_resource_id,
to_resource_id,
edges,
} => GraphDelta::ReplaySetResourceEdgesByIds {
from_resource_id: parse_uuid(from_resource_id),
to_resource_id: parse_uuid(to_resource_id),
edges: edges.clone(),
},
Self::ReplaySetShownResourceById {
surface_id,
resource_id,
} => GraphDelta::ReplaySetShownResourceById {
surface_id: parse_uuid(surface_id),
resource_id: resource_id.as_deref().map(parse_uuid),
},
Self::ReplayTouchNodeLastVisitedById {
node_id,
timestamp_ms,
} => GraphDelta::ReplayTouchNodeLastVisitedById {
node_id: parse_uuid(node_id),
timestamp_ms: *timestamp_ms,
},
Self::ReplayAddField { field } => GraphDelta::ReplayAddField {
field: field.clone(),
},
Self::ReplayRetireFieldById { field_id } => GraphDelta::ReplayRetireFieldById {
field_id: field_id.clone(),
},
Self::ReplayRemoveFieldById { field_id } => GraphDelta::ReplayRemoveFieldById {
field_id: field_id.clone(),
},
Self::ReplayAddCoupling { coupling } => GraphDelta::ReplayAddCoupling {
coupling: coupling.clone(),
},
Self::ReplaySetFieldCouplingStrengthByFieldId { field_id, strength } => {
GraphDelta::ReplaySetFieldCouplingStrengthByFieldId {
field_id: field_id.clone(),
strength: *strength,
}
},
Self::ReplayActivateFieldById { field_id } => GraphDelta::ReplayActivateFieldById {
field_id: field_id.clone(),
},
Self::ReplayRetractCouplingById { coupling_id } => {
GraphDelta::ReplayRetractCouplingById {
coupling_id: coupling_id.clone(),
}
},
})
}
pub fn replay_as(&self, author: &super::Author) -> Replay {
let mut replay = self.replay();
if let Replay::Apply(
GraphDelta::ReplayAssertRelationByIds { asserter_iri, .. }
| GraphDelta::ReplayAssertSemanticPredicateByIds { asserter_iri, .. }
| GraphDelta::ReplaySetEdgeSemanticPredicateByIds { asserter_iri, .. },
) = &mut replay
{
*asserter_iri = author.asserter_iri();
}
replay
}
}
fn parse_uuid(id: &str) -> Uuid {
Uuid::parse_str(id).expect("captured stable ids should always parse")
}
pub(crate) fn persisted_field_from_field(field: &Field) -> PersistedField {
PersistedField {
id: field.id.as_uuid().to_string(),
name: field.name.clone(),
definition_json: serde_json::to_string(&field.definition).unwrap_or_default(),
extent: match &field.extent {
FieldExtent::Global => PersistedFieldExtent::Global,
FieldExtent::Region {
min_x,
min_y,
max_x,
max_y,
} => PersistedFieldExtent::Region {
min_x: *min_x,
min_y: *min_y,
max_x: *max_x,
max_y: *max_y,
},
FieldExtent::AttachedToNode(id) => PersistedFieldExtent::AttachedToNode(id.to_string()),
FieldExtent::Polygon { points } => PersistedFieldExtent::Polygon {
points: points.clone(),
},
},
lifecycle: match field.lifecycle {
FieldLifecycle::Active => PersistedFieldLifecycle::Active,
FieldLifecycle::Retired => PersistedFieldLifecycle::Retired,
},
}
}
pub(crate) fn field_from_persisted(pfield: &PersistedField) -> Option<Field> {
let id = Uuid::parse_str(&pfield.id).ok()?;
let definition = serde_json::from_str::<FieldDefinition>(&pfield.definition_json).ok()?;
let extent = match &pfield.extent {
PersistedFieldExtent::Global => FieldExtent::Global,
PersistedFieldExtent::Region {
min_x,
min_y,
max_x,
max_y,
} => FieldExtent::Region {
min_x: *min_x,
min_y: *min_y,
max_x: *max_x,
max_y: *max_y,
},
PersistedFieldExtent::AttachedToNode(s) => Uuid::parse_str(s)
.map(FieldExtent::AttachedToNode)
.unwrap_or(FieldExtent::Global),
PersistedFieldExtent::Polygon { points } => FieldExtent::Polygon {
points: points.clone(),
},
};
let mut field = Field::new(FieldId::from_uuid(id), definition).with_extent(extent);
if let Some(name) = &pfield.name {
field = field.with_name(name.clone());
}
field.lifecycle = match pfield.lifecycle {
PersistedFieldLifecycle::Active => FieldLifecycle::Active,
PersistedFieldLifecycle::Retired => FieldLifecycle::Retired,
};
Some(field)
}
pub(crate) fn persisted_coupling_from_coupling(coupling: &Coupling) -> PersistedCoupling {
PersistedCoupling {
id: coupling.id.as_uuid().to_string(),
field_id: coupling.field.as_uuid().to_string(),
selector: match &coupling.selector {
NodeSelector::All => PersistedNodeSelector::All,
NodeSelector::Tagged(tag) => PersistedNodeSelector::Tagged(tag.clone()),
NodeSelector::Kind(kind) => PersistedNodeSelector::Kind(kind.clone()),
NodeSelector::NotTagged(tag) => PersistedNodeSelector::NotTagged(tag.clone()),
},
response: match &coupling.response {
CouplingResponse::AttractToMin => PersistedCouplingResponse::AttractToMin,
CouplingResponse::RepelFromMax => PersistedCouplingResponse::RepelFromMax,
CouplingResponse::AlignVelocity => PersistedCouplingResponse::AlignVelocity,
CouplingResponse::FlowAdvect => PersistedCouplingResponse::FlowAdvect,
CouplingResponse::DampenInside { factor } => {
PersistedCouplingResponse::DampenInside { factor: *factor }
},
CouplingResponse::ContainmentWall => PersistedCouplingResponse::ContainmentWall,
CouplingResponse::Open { predicate } => PersistedCouplingResponse::Open {
predicate: predicate.clone(),
},
},
strength: coupling.strength,
}
}
pub(crate) fn coupling_from_persisted(pcoupling: &PersistedCoupling) -> Option<Coupling> {
let cid = Uuid::parse_str(&pcoupling.id).ok()?;
let fid = Uuid::parse_str(&pcoupling.field_id).ok()?;
let selector = match &pcoupling.selector {
PersistedNodeSelector::All => NodeSelector::All,
PersistedNodeSelector::Tagged(tag) => NodeSelector::Tagged(tag.clone()),
PersistedNodeSelector::Kind(kind) => NodeSelector::Kind(kind.clone()),
PersistedNodeSelector::NotTagged(tag) => NodeSelector::NotTagged(tag.clone()),
};
let response = match &pcoupling.response {
PersistedCouplingResponse::AttractToMin => CouplingResponse::AttractToMin,
PersistedCouplingResponse::RepelFromMax => CouplingResponse::RepelFromMax,
PersistedCouplingResponse::AlignVelocity => CouplingResponse::AlignVelocity,
PersistedCouplingResponse::FlowAdvect => CouplingResponse::FlowAdvect,
PersistedCouplingResponse::DampenInside { factor } => {
CouplingResponse::DampenInside { factor: *factor }
},
PersistedCouplingResponse::ContainmentWall => CouplingResponse::ContainmentWall,
PersistedCouplingResponse::Open { predicate } => CouplingResponse::Open {
predicate: predicate.clone(),
},
};
Some(Coupling::new(
super::CouplingId::from_uuid(cid),
FieldId::from_uuid(fid),
selector,
response,
pcoupling.strength,
))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct GraphTableStats {
pub node_count: usize,
pub edge_count: usize,
pub relation_count: usize,
pub field_count: usize,
pub coupling_count: usize,
pub history_owner_count: usize,
pub history_entry_count: usize,
pub history_visit_count: usize,
}
impl Graph {
pub fn table_stats(&self) -> GraphTableStats {
GraphTableStats {
node_count: self.node_count(),
edge_count: self.edge_count(),
relation_count: self.relations().count(),
field_count: self.fields().count(),
coupling_count: self.couplings().count(),
history_owner_count: self.nav.owner_count(),
history_entry_count: self.nav.entry_count(),
history_visit_count: self.nav.visit_count(),
}
}
}
pub fn replay_captured_deltas<I>(deltas: I) -> Graph
where
I: IntoIterator<Item = CapturedDelta>,
{
let mut graph = Graph::new();
replay_captured_deltas_onto(&mut graph, deltas);
graph
}
pub fn replay_captured_deltas_onto<I>(graph: &mut Graph, deltas: I)
where
I: IntoIterator<Item = CapturedDelta>,
{
let _ = replay_outcomes_onto(
graph,
deltas.into_iter().map(|delta| delta.replay()),
OnRefusal::Drop,
);
}
pub fn replay_captured_deltas_onto_checked<I>(
graph: &mut Graph,
deltas: I,
) -> Result<(), ReplayRefused>
where
I: IntoIterator<Item = CapturedDelta>,
{
replay_outcomes_onto(
graph,
deltas.into_iter().map(|delta| delta.replay()),
OnRefusal::Stop,
)
}
pub fn replay_captured_deltas_as_onto<I>(graph: &mut Graph, author: &super::Author, deltas: I)
where
I: IntoIterator<Item = CapturedDelta>,
{
let _ = replay_outcomes_onto(
graph,
deltas.into_iter().map(|delta| delta.replay_as(author)),
OnRefusal::Drop,
);
}
pub(crate) struct ReplayAttribution(
BTreeMap<String, String>,
super::legacy_family_attribution::LegacyFamilyAttribution,
);
impl ReplayAttribution {
pub(crate) fn from_baseline(graph: &Graph) -> Self {
let mut attribution = Self(
BTreeMap::new(),
super::legacy_family_attribution::LegacyFamilyAttribution::from_baseline(graph),
);
attribution.observe_graph(graph);
attribution
}
fn observe_graph(&mut self, graph: &Graph) {
for edge in graph
.inner
.inner()
.edge_weights()
.chain(graph.resources.inner().edge_weights())
{
for statement in edge.assertions() {
if statement.statement_id.starts_with(
super::legacy_family_attribution::LEGACY_FAMILY_ASSERTION_ID_PREFIX,
) {
continue;
}
self.0
.entry(statement.statement_id.clone())
.or_insert_with(|| {
statement
.provenance_iri
.clone()
.unwrap_or_else(|| super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into())
});
}
}
}
pub(crate) fn repair_checkpoint(&self, graph: &mut Graph) {
let changed = self.repair_edges(&mut graph.inner) | self.repair_edges(&mut graph.resources);
if changed {
graph.bump_revision();
}
self.1.repair_checkpoint(graph);
}
fn repair_edges<N: chartulary::Identified>(
&self,
graph: &mut chartulary::Graph<N, super::EdgePayload>,
) -> bool {
let unknown = super::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI;
let keys: Vec<_> = graph.inner().edge_indices().collect();
let mut changed = false;
for key in keys {
if let Some(payload) = graph.edge_mut(key) {
let semantic = &mut payload.assertions;
for statement in &mut semantic.statements {
if statement.statement_id.starts_with(
super::legacy_family_attribution::LEGACY_FAMILY_ASSERTION_ID_PREFIX,
) {
continue;
}
if statement
.provenance_iri
.as_deref()
.is_none_or(|source| source == unknown)
&& let Some(source) = self.0.get(&statement.statement_id)
&& statement.provenance_iri.as_deref() != Some(source.as_str())
{
statement.provenance_iri = Some(source.clone());
changed = true;
}
}
}
}
changed
}
pub(crate) fn replay(&mut self, delta: &CapturedDelta, author: &super::Author) -> Replay {
let mut delta = match delta.replay_as(author) {
Replay::Apply(delta) => delta,
other => return other,
};
if let GraphDelta::ReplaySetEdgesByIds { edges, .. }
| GraphDelta::ReplaySetResourceEdgesByIds { edges, .. } = &mut delta
{
for edge in edges {
for statement in edge.retained_assertions_mut() {
if statement.statement_id.starts_with(
super::legacy_family_attribution::LEGACY_FAMILY_ASSERTION_ID_PREFIX,
) {
continue;
}
let original =
self.0
.entry(statement.statement_id.clone())
.or_insert_with(|| {
statement
.provenance_iri
.clone()
.unwrap_or_else(|| author.asserter_iri())
});
if statement.provenance_iri.is_none() {
statement.provenance_iri = Some(original.clone());
}
}
}
}
Replay::Apply(delta)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReplayRefused {
pub position: usize,
pub reason: super::resource_content::ContentError,
}
impl std::fmt::Display for ReplayRefused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"replayed entry {} refused: {}",
self.position, self.reason
)
}
}
impl std::error::Error for ReplayRefused {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum OnRefusal {
Stop,
Drop,
}
pub(crate) fn replay_attributed_deltas_onto<'a, I>(
graph: &mut Graph,
attribution: &mut ReplayAttribution,
entries: I,
on_refusal: OnRefusal,
) -> Result<(), ReplayRefused>
where
I: IntoIterator<Item = &'a super::journal::AttributedDelta>,
{
replay_quietly(graph, |graph| {
for (position, entry) in entries.into_iter().enumerate() {
let delta = match attribution.replay(&entry.delta, &entry.author) {
Replay::Apply(delta) => delta,
Replay::Skip => continue,
Replay::Malformed(bad) if on_refusal == OnRefusal::Stop => {
return Err(bad.refused_at(position));
},
Replay::Malformed(_) => continue,
};
let legacy_assertion = matches!(
delta,
GraphDelta::ReplayAssertRelationByIds { .. }
| GraphDelta::ReplayAssertSemanticPredicateByIds { .. }
| GraphDelta::ReplaySetEdgeSemanticPredicateByIds { .. }
);
if let GraphDeltaResult::Refused(reason) = apply_graph_delta(graph, delta)
&& on_refusal == OnRefusal::Stop
{
return Err(ReplayRefused { position, reason });
}
attribution.1.observe_delta(graph, entry);
if legacy_assertion {
attribution.observe_graph(graph);
}
}
Ok(())
})
}
pub(crate) fn replay_graph_deltas_onto<I>(
graph: &mut Graph,
deltas: I,
on_refusal: OnRefusal,
) -> Result<(), ReplayRefused>
where
I: IntoIterator<Item = GraphDelta>,
{
replay_outcomes_onto(graph, deltas.into_iter().map(Replay::Apply), on_refusal)
}
fn replay_quietly<R>(graph: &mut Graph, edit: impl FnOnce(&mut Graph) -> R) -> R {
let _quiet = QuietThread::begin();
let recorder = graph.recorder.0.take();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
graph.without_pending_derivation(edit)
}));
graph.recorder.0 = recorder;
match result {
Ok(result) => result,
Err(panic) => std::panic::resume_unwind(panic),
}
}
type CaptureHook = dyn Fn(&CapturedDelta) + Send + Sync + 'static;
pub type DeltaRecorder = Arc<CaptureHook>;
#[derive(Default)]
pub(crate) struct Recorder(pub(crate) Option<DeltaRecorder>);
impl Clone for Recorder {
fn clone(&self) -> Self {
Self(None)
}
}
thread_local! {
static CAPTURE_HOOK: RefCell<Option<Arc<CaptureHook>>> = RefCell::new(None);
}
pub fn set_captured_delta_hook(hook: Option<Arc<CaptureHook>>) {
CAPTURE_HOOK.with(|slot| *slot.borrow_mut() = hook);
}
struct QuietThread(Option<Arc<CaptureHook>>);
impl QuietThread {
fn begin() -> Self {
Self(CAPTURE_HOOK.with(|slot| slot.borrow_mut().take()))
}
}
impl Drop for QuietThread {
fn drop(&mut self) {
let hook = self.0.take();
CAPTURE_HOOK.with(|slot| *slot.borrow_mut() = hook);
}
}
pub fn with_isolated_capture<R>(edit: impl FnOnce() -> R) -> R {
let _quiet = QuietThread::begin();
edit()
}
impl Graph {
pub(crate) fn record_delta(&self, delta: &CapturedDelta) {
if let Some(recorder) = &self.recorder.0 {
recorder(delta);
}
CAPTURE_HOOK.with(|slot| {
if let Some(hook) = slot.borrow().as_ref() {
hook(delta);
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
use crate::graph::{
ContainmentSubKind, Coupling, CouplingId, CouplingResponse, EdgeAssertion, Field,
FieldDefinition, FieldExtent, FieldId, Graph, NavigationTrigger, NodeSelector,
ProvenanceSubKind, RelationKind, ScalarField, SemanticSubKind, SharedNavigationMemory,
};
use crate::types::{
BadgeIcon, ClassificationProvenance, ClassificationScheme, ClassificationStatus,
FrameLayoutHint, ImportRecordMembership, NodeClassification, NodeDerivation,
NodeImportProvenance, NodeProperty, SplitOrientation,
};
fn point(x: f32, y: f32) -> Point2D<f32> {
Point2D::new(x, y)
}
fn sample_field(id: FieldId) -> Field {
Field::new(id, FieldDefinition::Scalar(ScalarField::Const(1.0)))
.with_name("focus")
.with_extent(FieldExtent::Region {
min_x: -10.0,
min_y: -20.0,
max_x: 30.0,
max_y: 40.0,
})
}
fn sample_coupling(id: CouplingId, field: FieldId) -> Coupling {
Coupling::new(
id,
field,
NodeSelector::Kind("paper".into()),
CouplingResponse::DampenInside { factor: 0.3 },
1.5,
)
}
#[test]
fn structural_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplayAssertRelationByIds {
from_id: Uuid::from_u128(1).to_string(),
to_id: Uuid::from_u128(2).to_string(),
assertion: EdgeAssertion::Semantic {
sub_kind: SemanticSubKind::Hyperlink,
label: Some("next".into()),
},
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn arbitrary_facets_use_the_same_capture_and_replay_spine() {
let captured = Arc::new(Mutex::new(Vec::<CapturedDelta>::new()));
let sink = captured.clone();
set_captured_delta_hook(Some(Arc::new(move |delta| {
sink.lock().expect("capture sink").push(delta.clone());
})));
let id = Uuid::from_u128(0xfac7);
let mut graph = Graph::new();
let key = crate::graph::apply::add_node(
&mut graph,
Some(id),
"mere://facet-test".into(),
point(0.0, 0.0),
);
let value = serde_json::json!({"portable": true});
let _ = apply_graph_delta(
&mut graph,
GraphDelta::SetNodeFacet {
key,
facet: "example.portable/v1".into(),
value: value.clone(),
},
);
let _ = apply_graph_delta(
&mut graph,
GraphDelta::SetNodeFacet {
key,
facet: "example.portable/v1".into(),
value: value.clone(),
},
);
let _ = apply_graph_delta(
&mut graph,
GraphDelta::RemoveNodeFacet {
key,
facet: "example.portable/v1".into(),
},
);
set_captured_delta_hook(None);
let captured = captured.lock().expect("capture sink");
let [added, stamp, resource, shown, set, removed] = captured.as_slice() else {
panic!("expected add, visit, resource, shown, one facet set and remove: {captured:?}");
};
let resource_id = chartulary::resource_id("mere://facet-test").to_string();
assert!(
matches!(added, CapturedDelta::ReplayAddNodeWithIdIfMissing {
id: node_id, .. } if node_id == &id.to_string())
);
assert!(
matches!(stamp, CapturedDelta::ReplayTouchNodeLastVisitedById {
node_id, .. } if node_id == &id.to_string())
);
assert!(
matches!(resource, CapturedDelta::ReplaySetResourceRecordById {
resource_id: captured_id, record: Some(record) }
if captured_id == &resource_id && record.canonical_iri == "mere://facet-test"
&& record.facets.is_empty())
);
assert!(matches!(shown, CapturedDelta::ReplaySetShownResourceById {
surface_id, resource_id: Some(captured_id) }
if surface_id == &id.to_string() && captured_id == &resource_id));
assert!(matches!(set, CapturedDelta::ReplaySetNodeFacetById {
node_id, facet, value_json } if node_id == &id.to_string()
&& facet == "example.portable/v1"
&& serde_json::from_str::<serde_json::Value>(value_json).unwrap() == value));
assert!(matches!(removed, CapturedDelta::ReplayRemoveNodeFacetById {
node_id, facet } if node_id == &id.to_string() && facet == "example.portable/v1"));
let set_projection = replay_captured_deltas(captured[..captured.len() - 1].iter().cloned());
assert_eq!(
set_projection
.facets()
.get(&id, &chartulary::FacetId::new("example.portable/v1"),),
Some(&value)
);
let removed_projection = replay_captured_deltas(captured.iter().cloned());
assert!(
removed_projection
.facets()
.get(&id, &chartulary::FacetId::new("example.portable/v1"),)
.is_none()
);
assert_eq!(
set_projection.to_snapshot().resources,
graph.to_snapshot().resources
);
assert_eq!(
set_projection.to_snapshot().shown_resources,
graph.to_snapshot().shown_resources
);
assert_eq!(
removed_projection.to_snapshot().resources,
graph.to_snapshot().resources
);
assert_eq!(
removed_projection.to_snapshot().shown_resources,
graph.to_snapshot().shown_resources
);
}
#[test]
fn traversal_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplayAppendTraversalByIds {
from_id: Uuid::from_u128(3).to_string(),
to_id: Uuid::from_u128(4).to_string(),
trigger: NavigationTrigger::Redirect,
timestamp_ms: 12_345,
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn node_content_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplaySetNodeContentById {
node_id: Uuid::from_u128(5).to_string(),
content: Some([7; 32]),
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn node_enrichment_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplayAddNodeClassificationById {
node_id: Uuid::from_u128(6).to_string(),
classification: NodeClassification {
scheme: ClassificationScheme::ContentKind,
value: "article".into(),
label: Some("Article".into()),
confidence: 1.0,
provenance: ClassificationProvenance::UserAuthored,
status: ClassificationStatus::Accepted,
primary: true,
},
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn classification_admin_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplaySetNodeClassificationStatusById {
node_id: Uuid::from_u128(61).to_string(),
scheme: ClassificationScheme::ContentKind,
value: "article".into(),
status: ClassificationStatus::Verified,
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn tag_presentation_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplaySetNodeTagIconOverrideById {
node_id: Uuid::from_u128(62).to_string(),
tag: "paper".into(),
icon: Some(BadgeIcon::Lucide("file-text".into())),
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn node_media_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplaySetNodeImageById {
node_id: Uuid::from_u128(7).to_string(),
role: ImageRole::Preview,
image: ImageRef::new([4u8; 32], 2, 2),
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn a_legacy_inline_image_record_still_decodes_and_is_skipped_on_replay() {
let delta = CapturedDelta::ReplaySetNodeThumbnailById {
node_id: Uuid::from_u128(7).to_string(),
png_bytes: vec![1, 2, 3, 4],
width: 2,
height: 2,
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta, "an old journal entry still reads");
assert!(
matches!(restored.replay(), Replay::Skip),
"it has no live delta: the pixels are dropped, not restored"
);
}
#[test]
fn navigation_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplayNavigateNodeById {
node_id: Uuid::from_u128(8).to_string(),
url: "https://example.test/two".into(),
transition: TransitionKind::UrlTyped,
timestamp_ms: 123,
last_session_visited: 77,
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn semantic_edge_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplaySetEdgeSemanticPredicateByIds {
from_id: Uuid::from_u128(81).to_string(),
to_id: Uuid::from_u128(82).to_string(),
predicate: Some("https://schema.org/author".into()),
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn field_layer_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplayAddField {
field: persisted_field_from_field(&sample_field(FieldId::from_uuid(Uuid::from_u128(
9,
)))),
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn field_admin_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplayRetractCouplingById {
coupling_id: Uuid::from_u128(91).to_string(),
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn last_visited_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplayTouchNodeLastVisitedById {
node_id: Uuid::from_u128(93).to_string(),
timestamp_ms: 1_763_573_400_123,
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn frame_history_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplayUpdateNodeHistoryById {
node_id: Uuid::from_u128(10).to_string(),
entries: vec!["https://a.test".into(), "https://b.test".into()],
current_index: 1,
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn import_records_captured_delta_round_trips_through_postcard() {
let delta = CapturedDelta::ReplaySetImportRecords {
import_records: vec![ImportRecord {
record_id: "import-record:seed".into(),
source_id: "import:seed".into(),
source_label: "Seed import".into(),
imported_at_secs: 1_763_500_800,
memberships: vec![ImportRecordMembership {
node_id: Uuid::from_u128(10).to_string(),
suppressed: false,
}],
}],
};
let bytes = postcard::to_allocvec(&delta).expect("encode");
let restored: CapturedDelta = postcard::from_bytes(&bytes).expect("decode");
assert_eq!(restored, delta);
}
#[test]
fn replay_captured_deltas_rebuilds_relation_traversal_media_navigation_field_enrichment_and_frame_history_state()
{
let a_id = Uuid::from_u128(11);
let b_id = Uuid::from_u128(12);
let c_id = Uuid::from_u128(13);
let field_id = FieldId::from_uuid(Uuid::from_u128(14));
let coupling_id = CouplingId::from_uuid(Uuid::from_u128(15));
let deltas = vec![
CapturedDelta::ReplayAddNodeWithIdIfMissing {
id: a_id.to_string(),
url: "https://a.test".into(),
position: [1.0, 2.0],
},
CapturedDelta::ReplayAddNodeWithIdIfMissing {
id: b_id.to_string(),
url: "https://b.test".into(),
position: [3.0, 4.0],
},
CapturedDelta::ReplayAddNodeWithIdIfMissing {
id: c_id.to_string(),
url: "https://c.test".into(),
position: [5.0, 6.0],
},
CapturedDelta::ReplayAssertRelationByIds {
from_id: a_id.to_string(),
to_id: b_id.to_string(),
assertion: EdgeAssertion::Containment {
sub_kind: ContainmentSubKind::CollectionMember,
},
},
CapturedDelta::ReplayAppendTraversalByIds {
from_id: a_id.to_string(),
to_id: b_id.to_string(),
trigger: NavigationTrigger::LinkClick,
timestamp_ms: 6_789,
},
CapturedDelta::ReplaySetNodeTitleById {
node_id: a_id.to_string(),
title: "Alpha".into(),
},
CapturedDelta::ReplaySetNodeUrlById {
node_id: a_id.to_string(),
new_url: "https://a.test/next".into(),
},
CapturedDelta::ReplaySetNodeImageById {
node_id: a_id.to_string(),
role: ImageRole::Preview,
image: ImageRef::new([7u8; 32], 1, 1),
},
CapturedDelta::ReplaySetNodeImageById {
node_id: a_id.to_string(),
role: ImageRole::Favicon,
image: ImageRef::new([9u8; 32], 1, 1),
},
CapturedDelta::ReplaySetNodeMimeHintById {
node_id: a_id.to_string(),
mime_hint: Some("text/html".into()),
},
CapturedDelta::ReplaySetNodePinnedById {
node_id: a_id.to_string(),
is_pinned: true,
},
CapturedDelta::ReplayInsertNodeTagById {
node_id: a_id.to_string(),
tag: "research".into(),
},
CapturedDelta::ReplayRemoveNodeTagById {
node_id: a_id.to_string(),
tag: "research".into(),
},
CapturedDelta::ReplaySetNodeBodyById {
node_id: a_id.to_string(),
body: Some("body".into()),
},
CapturedDelta::ReplayTouchNodeLastVisitedById {
node_id: a_id.to_string(),
timestamp_ms: 1_763_573_400_123,
},
CapturedDelta::ReplayInsertNodeTagById {
node_id: a_id.to_string(),
tag: "paper".into(),
},
CapturedDelta::ReplaySetNodeTagIconOverrideById {
node_id: a_id.to_string(),
tag: "paper".into(),
icon: Some(BadgeIcon::Lucide("file-text".into())),
},
CapturedDelta::ReplayNavigateNodeById {
node_id: b_id.to_string(),
url: "https://b.test/one".into(),
transition: TransitionKind::UrlTyped,
timestamp_ms: 111,
last_session_visited: 77,
},
CapturedDelta::ReplayNavigateNodeById {
node_id: b_id.to_string(),
url: "https://b.test/two".into(),
transition: TransitionKind::UrlTyped,
timestamp_ms: 222,
last_session_visited: 77,
},
CapturedDelta::ReplayNodeHistoryBackById {
node_id: b_id.to_string(),
timestamp_ms: 333,
},
CapturedDelta::ReplayNodeHistoryForwardById {
node_id: b_id.to_string(),
timestamp_ms: 444,
},
CapturedDelta::ReplayBranchHistoryByIds {
child_id: c_id.to_string(),
parent_id: b_id.to_string(),
},
CapturedDelta::ReplayNavigateNodeById {
node_id: c_id.to_string(),
url: "https://c.test/branched".into(),
transition: TransitionKind::UrlTyped,
timestamp_ms: 555,
last_session_visited: 77,
},
CapturedDelta::ReplayAddField {
field: persisted_field_from_field(&sample_field(field_id)),
},
CapturedDelta::ReplayAddCoupling {
coupling: persisted_coupling_from_coupling(&sample_coupling(coupling_id, field_id)),
},
CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId {
field_id: field_id.as_uuid().to_string(),
strength: 2.0,
},
CapturedDelta::ReplayRetireFieldById {
field_id: field_id.as_uuid().to_string(),
},
CapturedDelta::ReplayActivateFieldById {
field_id: field_id.as_uuid().to_string(),
},
CapturedDelta::ReplayRetractCouplingById {
coupling_id: coupling_id.as_uuid().to_string(),
},
CapturedDelta::ReplayAddCoupling {
coupling: persisted_coupling_from_coupling(&sample_coupling(coupling_id, field_id)),
},
CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId {
field_id: field_id.as_uuid().to_string(),
strength: 2.0,
},
CapturedDelta::ReplayAppendNodePropertyById {
node_id: a_id.to_string(),
property: NodeProperty::new(
"https://schema.org/datePublished".into(),
"2026-07-02".into(),
),
},
CapturedDelta::ReplayAddNodeClassificationById {
node_id: a_id.to_string(),
classification: NodeClassification {
scheme: ClassificationScheme::ContentKind,
value: "article".into(),
label: Some("Article".into()),
confidence: 1.0,
provenance: ClassificationProvenance::UserAuthored,
status: ClassificationStatus::Accepted,
primary: true,
},
},
CapturedDelta::ReplayAddNodeClassificationById {
node_id: a_id.to_string(),
classification: NodeClassification {
scheme: ClassificationScheme::ContentKind,
value: "essay".into(),
label: Some("Essay".into()),
confidence: 0.6,
provenance: ClassificationProvenance::AgentSuggested,
status: ClassificationStatus::Suggested,
primary: false,
},
},
CapturedDelta::ReplayAddNodeClassificationById {
node_id: a_id.to_string(),
classification: NodeClassification {
scheme: ClassificationScheme::ContentKind,
value: "draft".into(),
label: Some("Draft".into()),
confidence: 0.3,
provenance: ClassificationProvenance::AgentSuggested,
status: ClassificationStatus::Suggested,
primary: false,
},
},
CapturedDelta::ReplaySetNodeClassificationStatusById {
node_id: a_id.to_string(),
scheme: ClassificationScheme::ContentKind,
value: "article".into(),
status: ClassificationStatus::Verified,
},
CapturedDelta::ReplaySetNodePrimaryClassificationById {
node_id: a_id.to_string(),
scheme: ClassificationScheme::ContentKind,
value: "essay".into(),
},
CapturedDelta::ReplayRemoveNodeClassificationById {
node_id: a_id.to_string(),
scheme: ClassificationScheme::ContentKind,
value: "draft".into(),
},
CapturedDelta::ReplayRecordNodeDerivationById {
node_id: a_id.to_string(),
derivation: NodeDerivation {
sub_kind: ProvenanceSubKind::ExtractedFrom,
source_node: Uuid::from_u128(99).to_string(),
source_graph: Some("graph:test".into()),
},
},
CapturedDelta::ReplaySetEdgeSemanticPredicateByIds {
from_id: a_id.to_string(),
to_id: b_id.to_string(),
predicate: Some("https://schema.org/author".into()),
},
CapturedDelta::ReplayAssertSemanticPredicateByIds {
from_id: b_id.to_string(),
to_id: c_id.to_string(),
predicate: "https://schema.org/citation".into(),
},
CapturedDelta::ReplayAppendFrameLayoutHintById {
node_id: a_id.to_string(),
hint: FrameLayoutHint::SplitHalf {
first: b_id.to_string(),
second: c_id.to_string(),
orientation: SplitOrientation::Vertical,
},
},
CapturedDelta::ReplayAppendFrameLayoutHintById {
node_id: a_id.to_string(),
hint: FrameLayoutHint::SplitHalf {
first: c_id.to_string(),
second: b_id.to_string(),
orientation: SplitOrientation::Horizontal,
},
},
CapturedDelta::ReplayMoveFrameLayoutHintById {
node_id: a_id.to_string(),
from_index: 0,
to_index: 1,
},
CapturedDelta::ReplayRemoveFrameLayoutHintById {
node_id: a_id.to_string(),
hint_index: 1,
},
CapturedDelta::ReplaySetFrameSplitOfferSuppressedById {
node_id: a_id.to_string(),
suppressed: true,
},
CapturedDelta::ReplayUpdateNodeHistoryById {
node_id: a_id.to_string(),
entries: vec![
"https://a.test/one".into(),
"https://a.test/two".into(),
"https://a.test/three".into(),
],
current_index: 9,
},
CapturedDelta::ReplaySetImportRecords {
import_records: vec![ImportRecord {
record_id: "import-record:seed".into(),
source_id: "import:seed".into(),
source_label: "Seed import".into(),
imported_at_secs: 1_763_500_800,
memberships: vec![
ImportRecordMembership {
node_id: a_id.to_string(),
suppressed: false,
},
ImportRecordMembership {
node_id: c_id.to_string(),
suppressed: true,
},
],
}],
},
];
let graph = replay_captured_deltas(deltas);
assert_eq!(graph.node_count(), 3);
assert_eq!(graph.edge_count(), 2);
assert!(graph.get_node_by_id(a_id).is_some());
assert!(graph.get_node_by_id(b_id).is_some());
assert!(graph.get_node_by_id(c_id).is_some());
assert_eq!(graph.relations().count(), 4);
assert_eq!(
graph
.relations()
.filter(|r| r.kind == RelationKind::OpenPredicate)
.count(),
2
);
let from = graph.get_node_key_by_id(a_id).expect("from key");
let to = graph.get_node_key_by_id(b_id).expect("to key");
let edge = graph.find_edge_key(from, to).expect("edge key");
let payload = graph.get_edge(edge).expect("edge payload");
assert_eq!(payload.traversals().len(), 1);
assert_eq!(payload.metrics().total_navigations, 1);
assert_eq!(payload.metrics().last_navigated_at, Some(6_789));
let node = graph.get_node(from).expect("node payload");
assert_eq!(node.title, "Alpha");
assert_eq!(node.url(), "https://a.test/next");
assert_eq!(node.preview(), Some(&ImageRef::new([7u8; 32], 1, 1)));
assert_eq!(node.favicon(), Some(&ImageRef::new([9u8; 32], 1, 1)));
assert_eq!(node.media_type.as_deref(), Some("text/html"));
assert_eq!(graph.node_is_pinned(from), Some(true));
assert_eq!(node.body.as_deref(), Some("body"));
assert_eq!(
graph
.node_last_visited(from)
.expect("last visited facet")
.duration_since(std::time::UNIX_EPOCH)
.expect("last visited since epoch")
.as_millis() as u64,
1_763_573_400_123
);
assert!(!node.tags.contains("research"));
assert!(node.tags.contains("paper"));
assert_eq!(
graph
.node_tag_presentation(from)
.unwrap()
.icon_overrides
.get("paper"),
Some(&BadgeIcon::Lucide("file-text".into()))
);
let properties = graph.node_properties(from).unwrap();
assert_eq!(properties.len(), 1);
assert_eq!(properties[0].predicate, "https://schema.org/datePublished");
assert_eq!(properties[0].value, "2026-07-02");
let classifications = graph.node_classifications(from).unwrap();
assert_eq!(classifications.len(), 2);
assert!(classifications.iter().any(|classification| {
classification.value == "article"
&& classification.status == ClassificationStatus::Verified
&& !classification.primary
}));
assert!(classifications.iter().any(|classification| {
classification.value == "essay"
&& classification.status == ClassificationStatus::Suggested
&& classification.primary
}));
assert!(
classifications
.iter()
.all(|classification| classification.value != "draft")
);
let derivations = graph.node_derivations(from).unwrap();
assert_eq!(derivations.len(), 1);
assert_eq!(derivations[0].sub_kind, ProvenanceSubKind::ExtractedFrom);
assert_eq!(
payload
.semantic_data()
.and_then(|data| data.predicate.as_deref()),
Some("https://schema.org/author")
);
let history_node_key = graph.get_node_key_by_id(b_id).expect("history node key");
let history_node = graph.get_node(history_node_key).expect("history node");
assert_eq!(history_node.url(), "https://b.test/two");
assert_eq!(graph.node_last_session_visited(history_node_key), Some(77));
let history_projection = graph.node_history_projection(history_node_key);
assert_eq!(
history_projection.entries,
vec![
"https://b.test/one".to_string(),
"https://b.test/two".to_string(),
]
);
assert_eq!(history_projection.current_index, 1);
let branched_node_key = graph.get_node_key_by_id(c_id).expect("branched node key");
let branched_node = graph.get_node(branched_node_key).expect("branched node");
assert_eq!(branched_node.url(), "https://c.test/branched");
assert_eq!(graph.node_last_session_visited(branched_node_key), Some(77));
let semantic_edge = graph
.find_edge_key(history_node_key, branched_node_key)
.expect("semantic edge key");
let semantic_payload = graph
.get_edge(semantic_edge)
.expect("semantic edge payload");
assert_eq!(
semantic_payload
.semantic_data()
.and_then(|data| data.predicate.as_deref()),
Some("https://schema.org/citation")
);
let field = graph.field(field_id).expect("field payload");
assert_eq!(field.name.as_deref(), Some("focus"));
assert!(field.is_active());
assert_eq!(
field.extent,
FieldExtent::Region {
min_x: -10.0,
min_y: -20.0,
max_x: 30.0,
max_y: 40.0,
}
);
let coupling = graph
.couplings_for_field(field_id)
.next()
.expect("field coupling");
assert_eq!(coupling.id, coupling_id);
assert_eq!(coupling.selector, NodeSelector::Kind("paper".into()));
assert_eq!(
coupling.response,
CouplingResponse::DampenInside { factor: 0.3 }
);
assert_eq!(coupling.strength, 2.0);
let hints = graph.frame_layout_hints(from).expect("frame layout hints");
assert_eq!(hints.len(), 1);
assert_eq!(
hints[0],
FrameLayoutHint::SplitHalf {
first: c_id.to_string(),
second: b_id.to_string(),
orientation: SplitOrientation::Horizontal,
}
);
assert_eq!(graph.frame_split_offer_suppressed(from), Some(true));
let history = graph.node_history_projection(from);
assert_eq!(
history.entries,
vec![
"https://a.test/one".to_string(),
"https://a.test/two".to_string(),
"https://a.test/three".to_string(),
]
);
assert_eq!(history.current_index, 2);
let import_records = graph.import_records();
assert_eq!(import_records.len(), 1);
assert_eq!(import_records[0].record_id, "import-record:seed");
assert_eq!(
graph.import_record_member_keys("import-record:seed"),
vec![from]
);
assert_eq!(
graph
.node_import_provenance(from)
.expect("import provenance"),
[NodeImportProvenance {
source_id: "import:seed".into(),
source_label: "Seed import".into(),
}]
);
assert!(
graph
.node_import_provenance(branched_node_key)
.expect("suppressed provenance")
.is_empty()
);
let mut expected_nav = SharedNavigationMemory::empty();
expected_nav.record_visit(b_id, "https://b.test/one", TransitionKind::UrlTyped, 111);
expected_nav.record_visit(b_id, "https://b.test/two", TransitionKind::UrlTyped, 222);
assert_eq!(
expected_nav.back(b_id, 333).as_deref(),
Some("https://b.test/one")
);
assert_eq!(
expected_nav.forward(b_id, 444).as_deref(),
Some("https://b.test/two")
);
expected_nav.spawn(c_id, b_id);
expected_nav.record_visit(
c_id,
"https://c.test/branched",
TransitionKind::UrlTyped,
555,
);
expected_nav.seed_linear(
a_id,
vec![
"https://a.test/one".to_string(),
"https://a.test/two".to_string(),
"https://a.test/three".to_string(),
],
9,
);
let mut actual_snapshot = graph.to_snapshot().navigation.snapshot().clone();
for owner in &mut actual_snapshot.owners {
owner.owned_visits.sort_unstable();
}
for visit in &mut actual_snapshot.visits {
visit.bindings.sort_by_key(|binding| {
(
binding.owner,
binding.forward_child.unwrap_or(usize::MAX),
binding.last_accessed_at_ms,
)
});
}
let mut expected_snapshot = expected_nav.snapshot().clone();
for owner in &mut expected_snapshot.owners {
owner.owned_visits.sort_unstable();
}
for visit in &mut expected_snapshot.visits {
visit.bindings.sort_by_key(|binding| {
(
binding.owner,
binding.forward_child.unwrap_or(usize::MAX),
binding.last_accessed_at_ms,
)
});
}
assert_eq!(actual_snapshot, expected_snapshot);
}
#[test]
fn capture_hook_receives_replayable_apply_events() {
let captured = Arc::new(Mutex::new(Vec::<CapturedDelta>::new()));
let sink = captured.clone();
set_captured_delta_hook(Some(Arc::new(move |delta| {
sink.lock().expect("capture sink").push(delta.clone());
})));
let mut graph = Graph::new();
graph.set_current_session(77);
let a = crate::graph::apply::add_node(
&mut graph,
Some(Uuid::from_u128(21)),
"https://a.test".into(),
point(0.0, 0.0),
);
let b = crate::graph::apply::add_node(
&mut graph,
Some(Uuid::from_u128(22)),
"https://b.test".into(),
point(1.0, 0.0),
);
let c = crate::graph::apply::add_node(
&mut graph,
Some(Uuid::from_u128(23)),
"https://c.test".into(),
point(2.0, 0.0),
);
let field_id = FieldId::from_uuid(Uuid::from_u128(24));
let coupling_id = CouplingId::from_uuid(Uuid::from_u128(25));
graph.assert_semantic_statement(
a,
b,
crate::graph::SemanticStatementSpec {
predicate: "https://schema.org/author".into(),
recognized_sub_kind: Some(SemanticSubKind::Hyperlink),
provenance_iri: Some(crate::graph::journal::Author::user().asserter_iri()),
..Default::default()
},
);
let historical_statement = graph
.resource_relations()
.flat_map(|(_, _, _, payload)| payload.semantic_statements())
.find(|statement| statement.predicate == "https://schema.org/author")
.unwrap()
.clone();
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AppendTraversal {
from: a,
to: b,
trigger: NavigationTrigger::Programmatic,
timestamp_ms: Some(4_321),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodeTitle {
key: a,
title: "Alpha".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodeUrl {
key: a,
new_url: "https://a.test/next".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodeImage {
key: a,
role: ImageRole::Preview,
image: ImageRef::new([7u8; 32], 1, 1),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodeImage {
key: a,
role: ImageRole::Favicon,
image: ImageRef::new([9u8; 32], 1, 1),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodeMimeHint {
key: a,
mime_hint: Some("text/html".into()),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodePinned {
key: a,
is_pinned: true,
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::InsertNodeTag {
key: a,
tag: "research".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::RemoveNodeTag {
key: a,
tag: "research".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodeBody {
key: a,
body: Some("body".into()),
},
);
std::thread::sleep(std::time::Duration::from_millis(2));
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::TouchNodeLastVisited { key: a },
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::InsertNodeTag {
key: a,
tag: "paper".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodeTagIconOverride {
key: a,
tag: "paper".into(),
icon: Some(BadgeIcon::Lucide("file-text".into())),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::NavigateNode {
key: b,
url: "https://b.test/one".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::NavigateNode {
key: b,
url: "https://b.test/two".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::NodeHistoryBack { key: b },
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::NodeHistoryForward { key: b },
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::BranchHistory {
child: c,
parent: b,
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::NavigateNode {
key: c,
url: "https://c.test/branched".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AddField {
field: sample_field(field_id),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AddCoupling {
coupling: sample_coupling(coupling_id, field_id),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetFieldCouplingStrength {
field: field_id,
strength: 2.0,
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::RetireField { id: field_id },
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::ActivateField { id: field_id },
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::RetractCoupling { id: coupling_id },
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AddCoupling {
coupling: sample_coupling(coupling_id, field_id),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetFieldCouplingStrength {
field: field_id,
strength: 2.0,
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AppendNodeProperty {
key: a,
property: NodeProperty::new(
"https://schema.org/datePublished".into(),
"2026-07-02".into(),
),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AddNodeClassification {
key: a,
classification: NodeClassification {
scheme: ClassificationScheme::ContentKind,
value: "article".into(),
label: Some("Article".into()),
confidence: 1.0,
provenance: ClassificationProvenance::UserAuthored,
status: ClassificationStatus::Accepted,
primary: true,
},
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AddNodeClassification {
key: a,
classification: NodeClassification {
scheme: ClassificationScheme::ContentKind,
value: "essay".into(),
label: Some("Essay".into()),
confidence: 0.6,
provenance: ClassificationProvenance::AgentSuggested,
status: ClassificationStatus::Suggested,
primary: false,
},
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AddNodeClassification {
key: a,
classification: NodeClassification {
scheme: ClassificationScheme::ContentKind,
value: "draft".into(),
label: Some("Draft".into()),
confidence: 0.3,
provenance: ClassificationProvenance::AgentSuggested,
status: ClassificationStatus::Suggested,
primary: false,
},
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodeClassificationStatus {
key: a,
scheme: ClassificationScheme::ContentKind,
value: "article".into(),
status: ClassificationStatus::Verified,
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodePrimaryClassification {
key: a,
scheme: ClassificationScheme::ContentKind,
value: "essay".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::RemoveNodeClassification {
key: a,
scheme: ClassificationScheme::ContentKind,
value: "draft".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::RecordNodeDerivation {
key: a,
derivation: NodeDerivation {
sub_kind: ProvenanceSubKind::ExtractedFrom,
source_node: Uuid::from_u128(99).to_string(),
source_graph: Some("graph:test".into()),
},
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AssertSemanticPredicate {
asserter_iri: crate::graph::journal::Author::user().asserter_iri(),
from: b,
to: c,
predicate: "https://schema.org/citation".into(),
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AppendFrameLayoutHint {
key: a,
hint: FrameLayoutHint::SplitHalf {
first: Uuid::from_u128(22).to_string(),
second: Uuid::from_u128(23).to_string(),
orientation: SplitOrientation::Vertical,
},
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::AppendFrameLayoutHint {
key: a,
hint: FrameLayoutHint::SplitHalf {
first: Uuid::from_u128(23).to_string(),
second: Uuid::from_u128(22).to_string(),
orientation: SplitOrientation::Horizontal,
},
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::MoveFrameLayoutHint {
key: a,
from_index: 0,
to_index: 1,
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::RemoveFrameLayoutHint {
key: a,
hint_index: 1,
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetFrameSplitOfferSuppressed {
key: a,
suppressed: true,
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::UpdateNodeHistory {
key: a,
entries: vec![
"https://a.test/one".into(),
"https://a.test/two".into(),
"https://a.test/three".into(),
],
current_index: 9,
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetNodeImportProvenance {
key: a,
import_provenance: vec![NodeImportProvenance {
source_id: "import:seed".into(),
source_label: "Seed import".into(),
}],
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetImportRecordMembershipSuppressed {
record_id: "import-record:import:seed".into(),
key: a,
suppressed: true,
},
);
let c_node_id = graph.get_node(c).expect("node c").id.to_string();
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::SetImportRecords {
import_records: vec![ImportRecord {
record_id: "import-record:seed-two".into(),
source_id: "import:seed-two".into(),
source_label: "Seed import two".into(),
imported_at_secs: 1_763_500_801,
memberships: vec![ImportRecordMembership {
node_id: c_node_id,
suppressed: false,
}],
}],
},
);
let _ = crate::graph::apply::apply_graph_delta(
&mut graph,
GraphDelta::RetractRelations {
from: a,
to: b,
selector: RelationSelector::Semantic(SemanticSubKind::Hyperlink),
},
);
let _ =
crate::graph::apply::apply_graph_delta(&mut graph, GraphDelta::RemoveNode { key: b });
set_captured_delta_hook(None);
let captured = captured.lock().expect("capture sink");
let stamps = captured
.windows(2)
.filter(|pair| {
matches!(pair[0], CapturedDelta::ReplayAddNodeWithIdIfMissing { .. })
&& matches!(
pair[1],
CapturedDelta::ReplayTouchNodeLastVisitedById { .. }
)
})
.count();
let minted = captured
.iter()
.filter(|delta| matches!(delta, CapturedDelta::ReplaySetResourceEdgesByIds { edges, .. }
if edges.iter().flat_map(|edge| edge.retained_assertions())
.any(|statement| statement.predicate != crate::graph::resource::TAGGED_WITH_IRI)))
.count();
assert_eq!(
(stamps, minted),
(3, 2),
"three new nodes; hyperlink assertion with its predicate and open assertion captured"
);
let expected_bindings = [
(21, "https://a.test"),
(22, "https://b.test"),
(23, "https://c.test"),
(21, "https://a.test/next"),
(22, "https://b.test/one"),
(22, "https://b.test/two"),
(22, "https://b.test/one"),
(22, "https://b.test/two"),
(23, "https://c.test/branched"),
]
.map(|(surface, iri)| {
(
Uuid::from_u128(surface).to_string(),
chartulary::resource_id(iri).to_string(),
)
});
let actual_bindings = captured
.iter()
.filter_map(|delta| match delta {
CapturedDelta::ReplaySetShownResourceById {
surface_id,
resource_id: Some(resource_id),
} => Some((surface_id.clone(), resource_id.clone())),
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(actual_bindings, expected_bindings);
let expected_records = [
"https://a.test",
"https://b.test",
"https://c.test",
"https://a.test/next",
"https://b.test/one",
"https://b.test/two",
"https://c.test/branched",
]
.map(|iri| {
(
chartulary::resource_id(iri).to_string(),
chartulary::canonical_url(iri),
)
});
let actual_records = captured.iter().enumerate().filter_map(|(index, delta)| match delta {
CapturedDelta::ReplaySetResourceRecordById { resource_id, record: Some(record) }
if record.facets.is_empty() && expected_records.iter().any(|(id, _)| id == resource_id) => {
assert!(record.facets.is_empty());
let shown = captured.iter().position(|delta| matches!(delta,
CapturedDelta::ReplaySetShownResourceById { resource_id: Some(id), .. } if id == resource_id)).unwrap();
assert!(index < shown, "resource exists before the first shown binding");
assert!(captured[..index].iter().any(|delta| match delta {
CapturedDelta::ReplayAddNodeWithIdIfMissing { url, .. }
| CapturedDelta::ReplayNavigateNodeById { url, .. }
| CapturedDelta::ReplaySetNodeUrlById { new_url: url, .. } => {
chartulary::resource_id(url).to_string() == *resource_id
},
_ => false,
}));
Some((resource_id.clone(), record.canonical_iri.clone()))
},
_ => None,
}).collect::<Vec<_>>();
assert_eq!(
actual_records, expected_records,
"history revisits retain existing records"
);
let replayed = replay_captured_deltas(captured.iter().cloned());
let expected = graph.to_snapshot();
let mut actual = replayed.to_snapshot();
actual.timestamp_secs = expected.timestamp_secs;
let canonical = |snapshot: &crate::persistence::GraphSnapshot| {
let mut value = serde_json::to_value(snapshot).unwrap();
let navigation = &mut value["navigation"]["snapshot"];
for owner in navigation["owners"].as_array_mut().unwrap() {
owner["owned_visits"]
.as_array_mut()
.unwrap()
.sort_by_key(|id| id.as_u64().unwrap());
}
for visit in navigation["visits"].as_array_mut().unwrap() {
visit["bindings"]
.as_array_mut()
.unwrap()
.sort_by_key(|binding| binding["owner"].as_u64().unwrap());
}
value
};
assert_eq!(canonical(&actual), canonical(&expected));
assert_eq!(replayed.facets(), graph.facets());
assert_eq!(actual.resources, expected.resources);
assert_eq!(actual.resource_edges, expected.resource_edges);
assert_eq!(actual.shown_resources, expected.shown_resources);
assert!(replayed.get_node_key_by_id(Uuid::from_u128(22)).is_none());
assert_eq!(
graph
.find_semantic_statement(&historical_statement.statement_id)
.unwrap()
.1,
&historical_statement,
"navigation and Surface removal leave the original Resource assertion held"
);
assert!(graph.node_content_tags(a).unwrap().contains("paper"));
assert!(!graph.node_content_tags(a).unwrap().contains("research"));
assert_eq!(graph.node_properties(a).unwrap().len(), 1);
let classes = graph.node_classifications(a).unwrap();
assert_eq!(classes.len(), 2);
assert!(
classes
.iter()
.any(|classification| classification.value == "article"
&& classification.status == ClassificationStatus::Verified)
);
assert!(
classes
.iter()
.any(|classification| classification.value == "essay"
&& classification.primary
&& classification.status == ClassificationStatus::Suggested)
);
let content_records: Vec<_> = captured
.iter()
.filter_map(|delta| match delta {
CapturedDelta::ReplaySetResourceRecordById {
record: Some(record),
..
} if !record.facets.is_empty() => Some(record),
_ => None,
})
.collect();
for facet in [
crate::graph::resource_content::TAG_CONCEPT,
crate::graph::resource_content::RESOURCE_PROPERTIES,
crate::graph::resource_content::RESOURCE_CLASSIFICATIONS,
] {
assert!(
content_records
.iter()
.any(|record| record.facets.iter().any(|entry| entry.facet == facet)),
"{facet} is captured exactly"
);
}
let mut out = Vec::new();
for (index, delta) in captured.iter().enumerate() {
let stamp = index > 0
&& matches!(delta, CapturedDelta::ReplayTouchNodeLastVisitedById { .. })
&& matches!(
captured[index - 1],
CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
);
if !stamp
&& !matches!(
delta,
CapturedDelta::ReplaySetEdgesByIds { .. }
| CapturedDelta::ReplaySetResourceEdgesByIds { .. }
| CapturedDelta::ReplaySetResourceRecordById { .. }
| CapturedDelta::ReplaySetShownResourceById { .. }
)
{
out.push(delta.clone());
}
}
assert_eq!(out.len(), 38);
assert!(matches!(
out[0],
CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
));
assert!(matches!(
out[1],
CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
));
assert!(matches!(
out[2],
CapturedDelta::ReplayAddNodeWithIdIfMissing { .. }
));
assert!(matches!(
out[3],
CapturedDelta::ReplayAppendTraversalByIds { .. }
));
assert!(matches!(
out[4],
CapturedDelta::ReplaySetNodeTitleById { .. }
));
assert!(matches!(out[5], CapturedDelta::ReplaySetNodeUrlById { .. }));
assert!(matches!(
out[6],
CapturedDelta::ReplaySetNodeImageById { .. }
));
assert!(matches!(
out[7],
CapturedDelta::ReplaySetNodeImageById { .. }
));
assert!(matches!(
out[8],
CapturedDelta::ReplaySetNodeMimeHintById { .. }
));
assert!(matches!(
out[9],
CapturedDelta::ReplaySetNodePinnedById { .. }
));
assert!(matches!(
out[10],
CapturedDelta::ReplaySetNodeBodyById { .. }
));
assert!(matches!(
out[11],
CapturedDelta::ReplayTouchNodeLastVisitedById { .. }
));
assert!(matches!(
out[12],
CapturedDelta::ReplaySetNodeTagIconOverrideById { .. }
));
assert!(matches!(
out[13],
CapturedDelta::ReplayNavigateNodeById { .. }
));
assert!(matches!(
out[14],
CapturedDelta::ReplayNavigateNodeById { .. }
));
assert!(matches!(
out[15],
CapturedDelta::ReplayNodeHistoryBackById { .. }
));
assert!(matches!(
out[16],
CapturedDelta::ReplayNodeHistoryForwardById { .. }
));
assert!(matches!(
out[17],
CapturedDelta::ReplayBranchHistoryByIds { .. }
));
assert!(matches!(
out[18],
CapturedDelta::ReplayNavigateNodeById { .. }
));
assert!(matches!(out[19], CapturedDelta::ReplayAddField { .. }));
assert!(matches!(out[20], CapturedDelta::ReplayAddCoupling { .. }));
assert!(matches!(
out[21],
CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId { .. }
));
assert!(matches!(
out[22],
CapturedDelta::ReplayRetireFieldById { .. }
));
assert!(matches!(
out[23],
CapturedDelta::ReplayActivateFieldById { .. }
));
assert!(matches!(
out[24],
CapturedDelta::ReplayRetractCouplingById { .. }
));
assert!(matches!(out[25], CapturedDelta::ReplayAddCoupling { .. }));
assert!(matches!(
out[26],
CapturedDelta::ReplaySetFieldCouplingStrengthByFieldId { .. }
));
assert!(matches!(
out[27],
CapturedDelta::ReplayRecordNodeDerivationById { .. }
));
assert!(matches!(
out[28],
CapturedDelta::ReplayAppendFrameLayoutHintById { .. }
));
assert!(matches!(
out[29],
CapturedDelta::ReplayAppendFrameLayoutHintById { .. }
));
assert!(matches!(
out[30],
CapturedDelta::ReplayMoveFrameLayoutHintById { .. }
));
assert!(matches!(
out[31],
CapturedDelta::ReplayRemoveFrameLayoutHintById { .. }
));
assert!(matches!(
out[32],
CapturedDelta::ReplaySetFrameSplitOfferSuppressedById { .. }
));
assert!(matches!(
out[33],
CapturedDelta::ReplayUpdateNodeHistoryById { .. }
));
assert!(matches!(
out[34],
CapturedDelta::ReplaySetImportRecords { .. }
));
assert!(matches!(
out[35],
CapturedDelta::ReplaySetImportRecords { .. }
));
assert!(matches!(
out[36],
CapturedDelta::ReplaySetImportRecords { .. }
));
assert!(matches!(
out[37],
CapturedDelta::ReplayRemoveNodeById { .. }
));
}
}
#[cfg(test)]
mod resource_capture_tests {
use std::sync::{Arc, Mutex};
use super::*;
use crate::graph::{Author, GraphJournal, SemanticStatement};
use crate::persistence::PersistedResourceFacet;
fn record(iri: &str) -> CapturedDelta {
CapturedDelta::ReplaySetResourceRecordById {
resource_id: chartulary::resource_id(iri).to_string(),
record: Some(PersistedResourceRecord {
canonical_iri: chartulary::canonical_url(iri),
facets: vec![PersistedResourceFacet {
facet: "foreign.metadata".into(),
value_json: r#"{"nested":[null,{"future":"kept"}]}"#.into(),
}],
}),
}
}
fn edges(from: Uuid, to: Uuid) -> Vec<PersistedEdge> {
let mut persisted = Vec::new();
for (statement_id, source_iri, time) in [
("minted-handle", "https://people.test/minter", 10),
("explicit-handle", "https://people.test/explicit", 20),
] {
let mut graph = Graph::new();
let source =
graph.add_node_with_id(from, "https://surface-a.test".into(), Default::default());
let target =
graph.add_node_with_id(to, "https://surface-b.test".into(), Default::default());
graph.assert_surface_persisted_semantic_statement(
source,
target,
SemanticStatement {
statement_id: statement_id.into(),
predicate: "https://vocab.test/relation".into(),
recognized_sub_kind: None,
label: None,
graph_scope: crate::types::GraphScope::User,
provenance_iri: Some(source_iri.into()),
asserted_at_ms: Some(time),
first_asserted_ms: Some(time),
withdrawn: None,
basis: Default::default(),
},
);
persisted.extend(graph.persisted_edges_between(source, target));
}
persisted
}
#[test]
fn resource_capture_codecs_preserve_old_ordinals_and_new_payloads() {
let old_pair = CapturedDelta::ReplaySetEdgesByIds {
from_id: "a".into(),
to_id: "b".into(),
edges: Vec::new(),
};
assert_eq!(
postcard::to_allocvec(&old_pair).unwrap(),
[37, 1, b'a', 1, b'b', 0]
);
let old_content = CapturedDelta::ReplaySetNodeContentById {
node_id: "a".into(),
content: None,
};
assert_eq!(
postcard::to_allocvec(&old_content).unwrap(),
[46, 1, b'a', 0]
);
let iri = "https://resource.test/a";
let resource = chartulary::resource_id(iri);
let other = chartulary::resource_id("https://resource.test/b");
let variants = [
record(iri),
CapturedDelta::ReplaySetResourceEdgesByIds {
from_resource_id: resource.to_string(),
to_resource_id: other.to_string(),
edges: edges(resource, other),
},
CapturedDelta::ReplaySetShownResourceById {
surface_id: Uuid::from_u128(1).to_string(),
resource_id: Some(resource.to_string()),
},
];
for (ordinal, delta) in (47u8..).zip(variants) {
let bytes = postcard::to_allocvec(&delta).unwrap();
assert_eq!(bytes[0], ordinal);
assert_eq!(
postcard::from_bytes::<CapturedDelta>(&bytes).unwrap(),
delta
);
let json = serde_json::to_string(&delta).unwrap();
assert_eq!(serde_json::from_str::<CapturedDelta>(&json).unwrap(), delta);
}
}
#[test]
fn resource_capture_replay_preserves_strata_exact_data_and_noops() {
let from = chartulary::resource_id("https://resource.test/a");
let to = chartulary::resource_id("https://resource.test/b");
let mut graph = Graph::new();
let source =
graph.add_node_with_id(from, "https://surface.test/a".into(), Default::default());
let target =
graph.add_node_with_id(to, "https://surface.test/b".into(), Default::default());
graph.assert_surface_persisted_semantic_statement(
source,
target,
SemanticStatement {
statement_id: "surface-control".into(),
predicate: "https://vocab.test/surface".into(),
recognized_sub_kind: None,
label: None,
graph_scope: crate::types::GraphScope::User,
provenance_iri: Some("https://people.test/surface".into()),
asserted_at_ms: Some(30),
first_asserted_ms: Some(30),
withdrawn: None,
basis: Default::default(),
},
);
let baseline = graph.clone();
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = seen.clone();
graph.set_recorder(Some(Arc::new(move |delta: &CapturedDelta| {
sink.lock().unwrap().push(delta.clone())
})));
let writes = [
record("https://resource.test/a"),
record("https://resource.test/b"),
CapturedDelta::ReplaySetResourceEdgesByIds {
from_resource_id: from.to_string(),
to_resource_id: to.to_string(),
edges: edges(from, to),
},
CapturedDelta::ReplaySetShownResourceById {
surface_id: from.to_string(),
resource_id: Some(from.to_string()),
},
];
for delta in &writes {
apply_graph_delta(&mut graph, delta.replay().into_write().unwrap());
}
let recorded = seen.lock().unwrap().clone();
assert_eq!(recorded.len(), 4);
let revision = graph.revision();
for delta in &recorded {
apply_graph_delta(&mut graph, delta.replay().into_write().unwrap());
}
assert_eq!(
seen.lock().unwrap().len(),
4,
"identical writes capture nothing"
);
assert_eq!(graph.revision(), revision);
assert_eq!(
graph.persisted_edges_between(source, target),
baseline.persisted_edges_between(source, target)
);
assert_eq!(
graph.persisted_resource_edges_between(from, to),
edges(from, to)
);
let mut restored = baseline;
replay_captured_deltas_onto(&mut restored, recorded);
assert_eq!(restored.resource_record(from), graph.resource_record(from));
assert_eq!(
restored.persisted_resource_edges_between(from, to),
graph.persisted_resource_edges_between(from, to)
);
assert_eq!(restored.shown_resource_id(source), Some(from));
assert_eq!(restored.surface_ids_showing_resource(from), [from]);
}
#[test]
fn resource_capture_journal_preserves_mint_source_across_withdrawal() {
let from = chartulary::resource_id("https://resource.test/a");
let to = chartulary::resource_id("https://resource.test/b");
let mut captured = edges(from, to);
captured[0].retained_assertions_mut()[0].provenance_iri = None;
let pair = |edges| CapturedDelta::ReplaySetResourceEdgesByIds {
from_resource_id: from.to_string(),
to_resource_id: to.to_string(),
edges,
};
let minter = Author::engine("mint-engine", "v1");
let restorer = Author::person("restoring-person");
let mut journal = GraphJournal::new();
journal.record(record("https://resource.test/a"));
journal.record(record("https://resource.test/b"));
journal.record_as(minter.clone(), pair(captured.clone()));
let before_withdrawal = journal.replay();
journal.record_as(restorer.clone(), pair(Vec::new()));
let absent = journal.replay();
assert!(absent.persisted_resource_edges_between(from, to).is_empty());
assert!(
absent.resource_record(from).is_some(),
"withdrawal keeps resource identity"
);
journal.record_as(restorer, pair(captured));
let restored = journal.replay();
assert_eq!(
restored.persisted_resource_edges_between(from, to),
before_withdrawal.persisted_resource_edges_between(from, to)
);
let persisted = restored.persisted_resource_edges_between(from, to);
assert_eq!(persisted.len(), 2, "parallel exact records remain separate");
let minted = &persisted[0].retained_assertions()[0];
let explicit = &persisted[1].retained_assertions()[0];
assert_eq!(minted.statement_id, "minted-handle");
assert_eq!(minted.asserted_at_ms, Some(10));
assert_eq!(minted.provenance_iri, Some(minter.asserter_iri()));
assert_eq!(explicit.statement_id, "explicit-handle");
assert_eq!(explicit.asserted_at_ms, Some(20));
assert_eq!(
explicit.provenance_iri.as_deref(),
Some("https://people.test/explicit")
);
}
}