Reconcile remote changes into the interface instead of rebuilding it

This commit is contained in:
Dennis Kobert committed 2026-09-24 17:32:12 +00:00
1 parent 3c7bc125ea
commit e784ebfeb7
10 files changed
+813 -24

No files matched your search

@@ -99,6 +99,11 @@ impl DocumentHistory {
self.storage.as_mut()
}
/// The decoded proto-node declarations the working copy's registry states reference.
pub fn declarations(&self) -> &Declarations {
&self.declarations
}
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
self.needs_whole_document_stage |= storage.registry().node_instances.is_empty();
@@ -23,7 +23,7 @@ use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType
use crate::messages::portfolio::document::properties_panel::properties_panel_message_handler::PropertiesPanelMessageContext;
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
@@ -149,10 +149,11 @@ pub struct DocumentMessageHandler {
/// Undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor.
#[serde(skip)]
history: DocumentHistory,
/// Peers changed the registry and the interface hasn't been rebuilt from it yet, so a staged diff
/// would read as reverting their edits.
/// What peers changed in the working registry that the interface does not show yet. Applied once every
/// declaration it needs is cached. Local edits stage meanwhile: they are constructed against the
/// registry rather than diffed from the interface, so nothing here reads as reverting them.
#[serde(skip)]
pub(crate) runtime_stale: bool,
pub(crate) pending_remote: document_format::network::RemoteChanges,
/// Hash of the document snapshot that was most recently saved to disk by the user.
#[serde(skip)]
saved_hash: Option<u64>,
@@ -204,7 +205,7 @@ impl Default for DocumentMessageHandler {
breadcrumb_network_path: Vec::new(),
selection_network_path: Vec::new(),
history: DocumentHistory::default(),
runtime_stale: false,
pending_remote: Default::default(),
saved_hash: None,
auto_saved_hash: None,
layer_range_selection_reference: None,
@@ -2056,7 +2057,7 @@ impl DocumentMessageHandler {
/// session that never mounts one.
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
let deltas = self.network_interface.take_deltas();
if self.history.storage().is_none() || self.runtime_stale {
if self.history.storage().is_none() {
return;
}
@@ -2064,7 +2065,9 @@ impl DocumentMessageHandler {
self.history
.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, legacy_document.as_str(), byte_store);
if validate {
// The interface is behind the registry by what peers changed, so the two are only expected to
// agree once that is applied.
if validate && self.pending_remote.is_empty() {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
@@ -2141,10 +2144,69 @@ impl DocumentMessageHandler {
}
}
/// Swap in an interface rebuilt from the registry a peer's changes left behind.
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) {
let Some(rebuilt) = self.history.rebuild_interface() else { return };
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
/// Brings the interface into line with what peers changed in the registry. Returns whether nothing is
/// left pending: a declaration still on its way keeps the changes for a later call.
///
/// The touched entities are reconciled in place. Only a registry rederived wholesale, or a reconcile
/// that fails for some other reason, costs a rebuild of the whole interface.
pub(crate) fn apply_remote_changes(&mut self, responses: &mut VecDeque<Message>) -> bool {
let changes = std::mem::take(&mut self.pending_remote);
if changes.is_empty() {
return true;
}
if !changes.rebuilt
&& let Some(gdd) = self.history.storage()
{
let peer = gdd.session().peer();
match self.network_interface.reconcile_remote(gdd.registry(), self.history.declarations(), &changes.touched, peer) {
Ok(reconciled) => {
self.finish_remote_reconcile(reconciled, changes.touched.resources, responses);
return true;
}
Err(ReconcileError::DeclarationMissing(id)) => {
log::debug!("Remote changes wait for declaration {id}");
self.pending_remote = changes;
return false;
}
Err(error) => log::warn!("Reconciling remote changes failed, rebuilding the interface instead: {error}"),
}
}
if let Some(rebuilt) = self.history.rebuild_interface() {
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
}
true
}
/// What a rebuild does for the whole interface, for the networks a reconcile changed: drops what the
/// changed nodes feed and re-derives the layer structure.
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, responses: &mut VecDeque<Message>) {
for path in &reconciled.networks {
if self.network_interface.document_network().nested_network(path).is_none() {
continue;
}
self.network_interface.unload_stack_dependents(path);
self.network_interface.unload_import_export_ports(path);
self.network_interface.unload_modify_import_export(path);
self.network_interface.unload_all_nodes_bounding_box(path);
self.network_interface.unload_outward_wires(path);
self.network_interface.unload_all_nodes_click_targets(path);
}
self.network_interface.load_structure();
if let Some(gdd) = self.history.storage_mut() {
gdd.mark_runtime_current();
}
if resources_changed {
self.refresh_resource_registry();
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
}
/// Cache a resource received from a peer as a proto-node declaration, so a rebuild can resolve it.
@@ -2163,7 +2225,7 @@ impl DocumentMessageHandler {
}
self.network_interface = rebuilt;
self.runtime_stale = false;
self.pending_remote = Default::default();
if let Some(gdd) = self.history.storage_mut() {
gdd.mark_runtime_current();
}
@@ -14,6 +14,7 @@ mod layout;
mod memo_network;
mod mutations;
mod queries;
mod reconcile;
mod resolved_types;
pub mod storage_metadata;
mod store;
@@ -25,6 +26,7 @@ mod validation;
mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded;
pub use store::NodeLocator;
pub use template::*;
@@ -8,7 +8,6 @@ impl NodeNetworkInterface {
/// never made back to whoever sent it. Writing through the store and then dropping what the store
/// recorded keeps the two parallel trees written by one place, which is the property the store
/// exists for, without the echo.
#[cfg_attr(not(test), expect(dead_code, reason = "no caller until deltas from another peer are replayed; the replay tests exercise it"))]
pub(crate) fn apply(&mut self, delta: &EditorDelta) {
let recorded = self.deltas.len();
self.mirror(delta);
@@ -612,3 +612,249 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
"the node's own metadata should not be restated by a swap that did not write it"
);
}
/// What a peer receives must bring its interface to what the editing peer holds: the recorded deltas are
/// constructed into storage ops, applied to the peer's registry, and the touched entities reconciled
/// into a clone of the interface taken before the edit. Anything the reconcile expresses wrongly, or
/// not at all, shows here as a difference from the edited interface, and the reconciled interface has
/// to convert back to the registry it was reconciled from.
async fn assert_remote_reconcile_reproduces(edit: impl FnOnce(&mut EditorTestUtils)) {
use document_graph_storage::Touched;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
editor.active_document_mut().network_interface.discard_deltas();
// Both interfaces address nodes the way storage does, so they compare directly.
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
// The peer's registry holds what a conversion of the interface holds before the edit.
let mut mirror = editor.active_document().network_interface.clone();
let baseline = {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion")
};
let mut peer = Session::with_peer(PeerId(8));
peer.stage_computed_ops(compute_deltas(&Registry::default(), &baseline.registry)).expect("the peer takes the baseline");
let mut declarations = baseline.declarations;
edit(&mut editor);
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
let recorded = editor.active_document_mut().network_interface.take_deltas();
assert!(!recorded.is_empty(), "the edit should have recorded something to send");
let constructed = {
let document = editor.active_document();
construct_batch(
&recorded,
&baseline.registry,
&document.resources.registry,
&StorageMetadataView::new(&document.network_interface),
PEER,
)
.expect("construction")
};
declarations.extend(constructed.declarations.decoded);
let mut touched = Touched::default();
for op in &constructed.ops {
touched.record(op);
}
peer.stage_computed_ops(constructed.ops).expect("the peer applies the batch");
mirror.reconcile_remote(peer.registry(), &declarations, &touched, PEER).expect("reconcile");
let edited = &editor.active_document().network_interface;
assert!(
mirror.document_network() == edited.document_network(),
"reconciling {} recorded deltas did not reproduce the edited graph:\n{}",
recorded.len(),
crate::messages::portfolio::document::document_diff::diff_networks(edited.document_network(), mirror.document_network())
);
let metadata = |interface: &super::NodeNetworkInterface| serde_json::to_value(interface.document_network_metadata()).expect("metadata serializes");
let (reconciled_metadata, edited_metadata) = (metadata(&mirror), metadata(edited));
assert!(
reconciled_metadata == edited_metadata,
"reconciling {} recorded deltas did not reproduce the edited metadata:\n{}",
recorded.len(),
json_diff(&edited_metadata, &reconciled_metadata, "")
);
let converted = Registry::convert_from_runtime(mirror.document_network(), &StorageMetadataView::new(&mirror), &editor.active_document().resources.registry, PEER)
.expect("the reconciled interface converts")
.registry;
assert!(
peer.registry().value_equal(&converted),
"the reconciled interface must convert back to the registry it was reconciled from\nresidual: {:#?}",
compute_deltas(&converted, peer.registry())
);
}
/// The paths at which two JSON values differ, one per line, so a metadata mismatch names the field.
fn json_diff(expected: &serde_json::Value, actual: &serde_json::Value, path: &str) -> String {
use serde_json::Value;
match (expected, actual) {
(Value::Object(expected), Value::Object(actual)) => {
let keys: std::collections::BTreeSet<_> = expected.keys().chain(actual.keys()).collect();
keys.into_iter()
.map(|key| match (expected.get(key), actual.get(key)) {
(Some(expected), Some(actual)) => json_diff(expected, actual, &format!("{path}/{key}")),
(Some(expected), None) => format!("{path}/{key}: missing, expected {expected}\n"),
(None, Some(actual)) => format!("{path}/{key}: unexpected {actual}\n"),
(None, None) => String::new(),
})
.collect()
}
(Value::Array(expected), Value::Array(actual)) if expected.len() == actual.len() => expected
.iter()
.zip(actual)
.enumerate()
.map(|(index, (expected, actual))| json_diff(expected, actual, &format!("{path}[{index}]")))
.collect(),
_ if expected == actual => String::new(),
_ => format!("{path}: expected {expected}\n{path}: actual {actual}\n"),
}
}
#[tokio::test]
async fn reconciling_metadata_edits_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&group, "Renamed".to_string(), &[]);
network_interface.set_locked(&group, &[], true);
network_interface.set_pinned(&group, &[], true);
network_interface.set_visibility(&group, &[], false);
network_interface.shift_node(&group, glam::IVec2::new(3, 5), &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_an_arity_change_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
editor
.active_document_mut()
.network_interface
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_node_insertion_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17A), template, &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_node_insertion_inside_a_group_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
editor.active_document_mut().network_interface.insert_node(NodeId(0xDE17B), template, &[group]);
})
.await;
}
#[tokio::test]
async fn reconciling_a_group_removal_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
})
.await;
}
#[tokio::test]
async fn reconciling_an_implementation_swap_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let interface = &mut editor.active_document_mut().network_interface;
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(group, &[])) else {
panic!("the group should resolve")
};
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), None);
})
.await;
}
#[tokio::test]
async fn reconciling_an_input_value_edit_reproduces_the_interface() {
assert_remote_reconcile_reproduces(|editor| {
let group = only_group(editor);
let interface = &mut editor.active_document_mut().network_interface;
let inner = interface
.nested_network(&[group])
.expect("the group's network")
.nodes
.iter()
.find(|(_, node)| node.inputs.iter().any(|input| input.as_value().is_some()))
.map(|(id, _)| *id)
.expect("a node with a value input inside the group");
let index = interface
.nested_network(&[group])
.and_then(|network| network.nodes.get(&inner))
.and_then(|node| node.inputs.iter().position(|input| input.as_value().is_some()))
.expect("the value input");
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
})
.await;
}
/// A touched node the registry holds unchanged, which is what a late-writer-wins loser leaves behind,
/// must not disturb the interface.
#[tokio::test]
async fn reconciling_an_untouched_node_changes_nothing() {
use document_graph_storage::Touched;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.active_document_mut().network_interface.pin_storage_identities(PEER);
let baseline = convert(&editor);
let declarations = {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion")
.declarations
};
let mut touched = Touched::default();
touched.nodes.extend(baseline.node_instances.keys().copied());
touched.networks.extend(baseline.networks.keys().copied());
let before = editor.active_document().network_interface.clone();
let reconciled = editor
.active_document_mut()
.network_interface
.reconcile_remote(&baseline, &declarations, &touched, PEER)
.expect("reconcile");
assert!(reconciled.networks.is_empty(), "nothing differed, so nothing should have been applied: {:?}", reconciled.networks);
assert_eq!(editor.active_document().network_interface, before);
}
@@ -0,0 +1,387 @@
//! Brings the interface into line with the working registry for the entities peers touched, so a remote
//! batch costs deltas for what changed rather than a rebuild of the whole interface.
//!
//! Each touched node is projected to its runtime form and compared with what the interface holds. The
//! difference is applied as the same `EditorDelta`s a local edit records, through `apply`, which mirrors
//! without recording, so nothing here is offered back to the peer that sent it. A node held on one side
//! only is added or removed whole. What a comparison cannot express as a field write, a changed
//! implementation or scope injection, replaces the node.
//!
//! The touched set is an over-approximation: a late-writer-wins loser or an op that failed to apply
//! names an entity that did not change, and the comparison finds nothing to emit for it.
use std::collections::{BTreeSet, HashMap};
use document_graph_storage::to_runtime::ConversionError;
use document_graph_storage::{Declarations, NodeId as StorageNodeId, ROOT_NETWORK, Registry, RuntimeProjection, Touched};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::runtime_delta::RuntimeDelta;
use super::storage_metadata::{InterfaceRebuildError, node_metadata_from_projection};
use super::{DocumentNodePersistentMetadata, EditorDelta, NetworkMetadataChange, NodeMetadataChange, NodeNetworkInterface};
#[derive(Debug, thiserror::Error)]
pub enum ReconcileError {
/// A declaration the touched nodes need is not cached yet. Nothing was applied; retry once it lands.
#[error("waiting for proto-node declaration {0}")]
DeclarationMissing(document_graph_storage::ResourceId),
#[error("the interface lacks the network at {0:?} that the registry places a node in")]
NetworkMissing(Vec<NodeId>),
#[error(transparent)]
Conversion(ConversionError),
#[error(transparent)]
Metadata(#[from] InterfaceRebuildError),
}
impl From<ConversionError> for ReconcileError {
fn from(error: ConversionError) -> Self {
match error {
ConversionError::DeclarationNotFound(id) => Self::DeclarationMissing(id),
other => Self::Conversion(other),
}
}
}
/// What a reconcile changed, for the caller to unload what those changes feed.
#[derive(Debug, Default)]
pub struct Reconciled {
/// The networks a delta was applied in.
pub networks: BTreeSet<Vec<NodeId>>,
}
/// Where the interface holds each node storage knows, keyed by the identity storage addresses it by.
type StorageIndex = HashMap<StorageNodeId, (Vec<NodeId>, NodeId)>;
impl NodeNetworkInterface {
/// Applies to the interface whatever the registry holds differently for the touched entities.
///
/// Can fail part-way through, leaving some of them reconciled. That is safe to retry with the same
/// touched set, since a reconciled node compares equal and emits nothing, which is what the caller
/// does when a declaration is still on its way; on any other error it rebuilds from the whole registry.
pub(crate) fn reconcile_remote(&mut self, registry: &Registry, declarations: &Declarations, touched: &Touched, peer: document_graph_storage::PeerId) -> Result<Reconciled, ReconcileError> {
let projection = registry.runtime_projection(declarations);
let index = self.pin_storage_identities(peer);
// A touched network is reconciled through the node implementing it, whose comparison covers the
// network's exports and metadata. The root has no such node.
let mut ids = touched.nodes.clone();
let mut root = false;
for &network in &touched.networks {
match projection.owner(network) {
Some(owner) => {
ids.insert(owner);
}
None => root |= network == ROOT_NETWORK,
}
}
// A node the runtime cannot reach and the interface does not hold has nothing to reconcile.
let mut items: Vec<(Vec<NodeId>, NodeId, StorageNodeId)> = ids
.into_iter()
.filter_map(|id| {
let (path, local_id) = projection.node_address(id).or_else(|| index.get(&id).cloned())?;
Some((path, local_id, id))
})
.collect();
// A network's path is a prefix of the paths inside it, so this puts each node after the one
// implementing its network, and a nested node finds its network in place.
items.sort();
let mut reconciled = Reconciled::default();
for (path, local_id, id) in items {
self.reconcile_node(&projection, &index, &path, local_id, id, &mut reconciled)?;
}
if root {
let target = projection.network_entry(ROOT_NETWORK)?;
let current_exports = self.document_network().exports.clone();
let current = &self.document_network_metadata().persistent_metadata;
let mut deltas = Vec::new();
export_deltas(&[], &current_exports, &target.exports, &mut deltas);
network_metadata_deltas(
&[],
current.reference.as_deref(),
&current.pinned_node_order,
target.metadata.reference.as_deref(),
&target.metadata.pinned_order,
&mut deltas,
);
self.apply_reconciled(&[], deltas, &mut reconciled);
}
Ok(reconciled)
}
fn reconcile_node(
&mut self,
projection: &RuntimeProjection,
index: &StorageIndex,
path: &[NodeId],
local_id: NodeId,
id: StorageNodeId,
reconciled: &mut Reconciled,
) -> Result<(), ReconcileError> {
// The interface holds the node somewhere else: under another id, or in a network it has since
// left. That copy goes before the one the registry describes is put in place.
if let Some((held_path, held_id)) = index.get(&id)
&& (held_path.as_slice() != path || *held_id != local_id)
&& self.holds_node(held_path, *held_id)
{
self.apply_reconciled(held_path, vec![remove_node(held_path, *held_id)], reconciled);
}
let stored = projection.node_address(id).is_some();
let held = self.holds_node(path, local_id);
match (stored, held) {
(false, false) => {}
(false, true) => self.apply_reconciled(path, vec![remove_node(path, local_id)], reconciled),
(true, false) => {
if !self.holds_network(path) {
return Err(ReconcileError::NetworkMissing(path.to_vec()));
}
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
let nested = matches!(node.implementation, DocumentNodeImplementation::Network(_));
let deltas = vec![
EditorDelta::Graph(RuntimeDelta::AddNode {
network_path: path.to_vec(),
node_id: local_id,
node: Box::new(node),
}),
EditorDelta::NodeMetadataSnapshot {
network_path: path.to_vec(),
node_id: local_id,
metadata: Box::new(metadata),
},
];
self.apply_reconciled(path, deltas, reconciled);
if nested {
reconciled.networks.insert(nested_path(path, local_id));
}
}
(true, true) => {
let (node, metadata) = node_metadata_from_projection(projection.node(id)?)?;
self.diff_node(path, local_id, node, metadata, reconciled);
}
}
Ok(())
}
/// Emits what differs between the node the interface holds at `path` / `local_id` and `target`, which
/// the registry describes. A network node's contents are left to their own reconciliation: only its
/// exports and its network's metadata are compared here.
fn diff_node(&mut self, path: &[NodeId], local_id: NodeId, target: DocumentNode, target_metadata: DocumentNodePersistentMetadata, reconciled: &mut Reconciled) {
let Some(current) = self.document_network().nested_network(path).and_then(|network| network.nodes.get(&local_id)) else {
return;
};
let Some(current_metadata) = self
.document_network_metadata()
.nested_metadata(path)
.and_then(|network| network.persistent_metadata.node_metadata.get(&local_id))
.map(|node| &node.persistent_metadata)
else {
return;
};
let mut deltas = Vec::new();
let mut nested_changed = false;
let at = |change: NodeMetadataChange| EditorDelta::NodeMetadata {
network_path: path.to_vec(),
node_id: local_id,
change,
};
// What no field write expresses replaces the node whole, and its metadata with it.
if !same_implementation(&current.implementation, &target.implementation) || current.skip_deduplication != target.skip_deduplication {
nested_changed = matches!(target.implementation, DocumentNodeImplementation::Network(_)) || matches!(current.implementation, DocumentNodeImplementation::Network(_));
deltas.push(EditorDelta::Graph(RuntimeDelta::ReplaceNode {
network_path: path.to_vec(),
node_id: local_id,
node: Box::new(target),
}));
deltas.push(EditorDelta::NodeMetadataSnapshot {
network_path: path.to_vec(),
node_id: local_id,
metadata: Box::new(target_metadata),
});
} else {
// The slots first, so the metadata array that indexes them lands on a list of the right length.
if current.inputs.len() != target.inputs.len() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInputs {
network_path: path.to_vec(),
node_id: local_id,
inputs: target.inputs.clone(),
}));
deltas.push(EditorDelta::NodeInputMetadata {
network_path: path.to_vec(),
node_id: local_id,
input_metadata: target_metadata.input_metadata.clone(),
});
} else {
for (input_index, (held, wanted)) in current.inputs.iter().zip(&target.inputs).enumerate() {
if held != wanted {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: path.to_vec(),
node_id: local_id,
input_index,
input: wanted.clone(),
}));
}
}
if current_metadata.input_metadata != target_metadata.input_metadata {
deltas.push(EditorDelta::NodeInputMetadata {
network_path: path.to_vec(),
node_id: local_id,
input_metadata: target_metadata.input_metadata.clone(),
});
}
}
// Export slot writes rename the encapsulating node's outputs as a side effect, so the names are
// restated after them whenever the slot count moved.
let mut restate_output_names = false;
if let (DocumentNodeImplementation::Network(held), DocumentNodeImplementation::Network(wanted)) = (&current.implementation, &target.implementation) {
let nested = nested_path(path, local_id);
let before = deltas.len();
export_deltas(&nested, &held.exports, &wanted.exports, &mut deltas);
restate_output_names = held.exports.len() != wanted.exports.len();
let (held_reference, held_order) = current_metadata
.network_metadata
.as_ref()
.map(|network| (network.persistent_metadata.reference.as_deref(), network.persistent_metadata.pinned_node_order.as_slice()))
.unwrap_or((None, &[]));
let (wanted_reference, wanted_order) = target_metadata
.network_metadata
.as_ref()
.map(|network| (network.persistent_metadata.reference.as_deref(), network.persistent_metadata.pinned_node_order.as_slice()))
.unwrap_or((None, &[]));
network_metadata_deltas(&nested, held_reference, held_order, wanted_reference, wanted_order, &mut deltas);
nested_changed = deltas.len() != before;
}
if current.visible != target.visible {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetVisibility {
network_path: path.to_vec(),
node_id: local_id,
visible: target.visible,
}));
}
if current.call_argument != target.call_argument {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetCallArgument {
network_path: path.to_vec(),
node_id: local_id,
call_argument: target.call_argument.clone(),
}));
}
if current.context_features != target.context_features {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetContextFeatures {
network_path: path.to_vec(),
node_id: local_id,
context_features: target.context_features,
}));
}
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
deltas.push(at(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
}
if current_metadata.display_name != target_metadata.display_name {
deltas.push(at(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
}
if current_metadata.locked != target_metadata.locked {
deltas.push(at(NodeMetadataChange::Locked(target_metadata.locked)));
}
if current_metadata.pinned != target_metadata.pinned {
deltas.push(at(NodeMetadataChange::Pinned(target_metadata.pinned)));
}
if restate_output_names || current_metadata.output_names != target_metadata.output_names {
deltas.push(at(NodeMetadataChange::OutputNames(target_metadata.output_names.clone())));
}
}
if deltas.is_empty() {
return;
}
self.apply_reconciled(path, deltas, reconciled);
if nested_changed {
reconciled.networks.insert(nested_path(path, local_id));
}
}
fn apply_reconciled(&mut self, path: &[NodeId], deltas: Vec<EditorDelta>, reconciled: &mut Reconciled) {
if deltas.is_empty() {
return;
}
for delta in &deltas {
self.apply(delta);
}
reconciled.networks.insert(path.to_vec());
}
fn holds_node(&self, path: &[NodeId], local_id: NodeId) -> bool {
self.document_network().nested_network(path).is_some_and(|network| network.nodes.contains_key(&local_id))
&& self
.document_network_metadata()
.nested_metadata(path)
.is_some_and(|network| network.persistent_metadata.node_metadata.contains_key(&local_id))
}
fn holds_network(&self, path: &[NodeId]) -> bool {
self.document_network().nested_network(path).is_some() && self.document_network_metadata().nested_metadata(path).is_some()
}
}
fn remove_node(path: &[NodeId], local_id: NodeId) -> EditorDelta {
EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: path.to_vec(),
node_id: local_id,
})
}
fn nested_path(path: &[NodeId], local_id: NodeId) -> Vec<NodeId> {
[path, &[local_id]].concat()
}
/// Whether a field-by-field comparison can bring `current` to `target`, which it cannot across a
/// change of what the node computes.
fn same_implementation(current: &DocumentNodeImplementation, target: &DocumentNodeImplementation) -> bool {
match (current, target) {
(DocumentNodeImplementation::ProtoNode(held), DocumentNodeImplementation::ProtoNode(wanted)) => held == wanted,
(DocumentNodeImplementation::Network(held), DocumentNodeImplementation::Network(wanted)) => held.scope_injections == wanted.scope_injections,
_ => false,
}
}
/// The slot writes taking `current` to `target`: a write per slot that differs, then a removal at the
/// end for each slot too many, which the mirror applies as removals of that index in turn.
fn export_deltas(network_path: &[NodeId], current: &[NodeInput], target: &[NodeInput], deltas: &mut Vec<EditorDelta>) {
for (export_index, input) in target.iter().enumerate() {
if current.get(export_index) != Some(input) {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index,
input: Some(input.clone()),
}));
}
}
for _ in target.len()..current.len() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: network_path.to_vec(),
export_index: target.len(),
input: None,
}));
}
}
fn network_metadata_deltas(network_path: &[NodeId], current_reference: Option<&str>, current_order: &[NodeId], target_reference: Option<&str>, target_order: &[NodeId], deltas: &mut Vec<EditorDelta>) {
if current_reference != target_reference {
deltas.push(EditorDelta::NetworkMetadata {
network_path: network_path.to_vec(),
change: NetworkMetadataChange::Reference(target_reference.map(str::to_string)),
});
}
if current_order != target_order {
deltas.push(EditorDelta::NetworkMetadata {
network_path: network_path.to_vec(),
change: NetworkMetadataChange::PinnedOrder(target_order.to_vec()),
});
}
}
@@ -188,6 +188,47 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
Ok(NodeNetworkInterface::from_trees(network, network_metadata))
}
/// The runtime node and the persistent metadata for it and everything nested under it, from a
/// single-node projection of the registry. Built through the same entry patching as a whole rebuild, on
/// a tree holding just this node, so a reconciled node matches what a rebuild would hold for it.
pub(super) fn node_metadata_from_projection(projected: document_graph_storage::ProjectedNode) -> Result<(graph_craft::document::DocumentNode, DocumentNodePersistentMetadata), InterfaceRebuildError> {
let document_graph_storage::ProjectedNode {
network_path: prefix,
local_id,
node,
node_entries,
network_entries,
} = projected;
// The entries carry absolute paths; the scratch tree is rooted at the node's own network.
let rebase = |path: Vec<NodeId>| path.get(prefix.len()..).map(<[NodeId]>::to_vec).unwrap_or_default();
let node_entries = node_entries
.into_iter()
.map(|entry| NodeMetadataEntry {
network_path: rebase(entry.network_path),
..entry
})
.collect();
let network_entries = network_entries
.into_iter()
.map(|entry| NetworkMetadataEntry {
network_path: rebase(entry.network_path),
..entry
})
.collect();
let mut scratch = NodeNetwork::default();
scratch.nodes.insert(local_id, node);
let mut metadata = NodeNetworkMetadata::default();
seed_metadata_tree(&scratch, &mut metadata);
apply_entries_into_tree(&scratch, &mut metadata, node_entries)?;
apply_network_entries_into_tree(&mut metadata, network_entries);
let persistent = metadata.persistent_metadata.node_metadata.remove(&local_id).map(|node| node.persistent_metadata).unwrap_or_default();
let node = scratch.nodes.remove(&local_id).expect("inserted above");
Ok((node, persistent))
}
/// Build the runtime-`network_path` -> stable-`NetworkId` map from the `NetworkMetadataEntry`s that
/// `to_runtime_with_full_metadata` emits, so the open path can apply per-network view settings.
pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> HashMap<Vec<NodeId>, document_graph_storage::NetworkId> {
@@ -303,7 +303,6 @@ impl NodeMut<'_> {
/// The encapsulating node's names for every one of the network's exports, replaced together since
/// they are stored as one array.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_output_names(&mut self, output_names: Vec<String>) -> bool {
let changed = self.metadata.output_names != output_names;
self.metadata.output_names = output_names;
@@ -315,7 +314,6 @@ impl NodeMut<'_> {
}
/// The metadata array the node's inputs index, one entry per input.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn input_metadata(&self) -> &[InputMetadata] {
&self.metadata.input_metadata
}
@@ -374,7 +372,6 @@ impl NodeMut<'_> {
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
/// which is the write a metadata snapshot describes.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn replace_metadata(&mut self, metadata: DocumentNodePersistentMetadata) {
*self.metadata = metadata;
@@ -383,7 +380,6 @@ impl NodeMut<'_> {
}
/// Replaces the metadata array the node's inputs index, leaving the inputs themselves alone.
#[cfg_attr(not(test), expect(dead_code, reason = "reached only through replay, which has no caller until deltas from another peer arrive"))]
pub(crate) fn set_input_metadata(&mut self, input_metadata: Vec<InputMetadata>) {
self.metadata.input_metadata = input_metadata;
self.emit_input_metadata();
@@ -329,6 +329,49 @@ impl NodeNetworkInterface {
self.deltas.clear();
}
/// Pins every node to the identity storage addresses it by, returning where each is held.
///
/// A node the interface built from storage is already pinned; one created here is addressed by a
/// hash of its location until now, which is what a conversion derives for it anyway. Pinning changes
/// no document content, so nothing is recorded: the identity is a fact about the node, not an edit.
pub(crate) fn pin_storage_identities(&mut self, peer: document_graph_storage::PeerId) -> HashMap<document_graph_storage::NodeId, (Vec<NodeId>, NodeId)> {
let mut index = HashMap::new();
let mut unpinned = Vec::new();
{
let view = super::storage_metadata::StorageMetadataView::new(self);
let resolver = document_graph_storage::PathResolver::new(Some(&view), peer);
let mut stack = vec![(Vec::new(), &*self.network_metadata)];
while let Some((path, metadata)) = stack.pop() {
for (&local_id, node) in &metadata.persistent_metadata.node_metadata {
let storage_id = match node.persistent_metadata.storage_id {
Some(pinned) => document_graph_storage::NodeId(pinned),
None => {
let derived = resolver.node_id(&path, local_id);
unpinned.push((path.clone(), local_id, derived));
derived
}
};
index.insert(storage_id, (path.clone(), local_id));
if let Some(nested) = &node.persistent_metadata.network_metadata {
stack.push(([path.as_slice(), &[local_id]].concat(), nested));
}
}
}
}
for (path, local_id, storage_id) in unpinned {
if let Some(node) = self
.network_metadata
.get_mut()
.nested_metadata_mut(&path)
.and_then(|network| network.persistent_metadata.node_metadata.get_mut(&local_id))
{
node.persistent_metadata.storage_id = Some(storage_id.0);
}
}
index
}
/// Drops the network's link to the definition it was instantiated from, which no longer describes it
/// once its signature is edited.
pub(crate) fn clear_encapsulating_reference(&mut self, network_path: &[NodeId]) {
@@ -108,11 +108,17 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
}
let events = gdd.poll_peers();
// Taken every poll rather than on an event: a refold a hello triggers can leave the
// registry rederived with no change event to announce it.
let changes = gdd.take_remote_changes();
if !changes.is_empty() {
document.pending_remote.extend(changes);
self.dirty.insert(document_id);
}
for event in events {
match event {
Event::Synced | Event::Changed => {
self.dirty.insert(document_id);
document.runtime_stale = true;
}
Event::ResourceRequested { from, hash } => {
log::debug!("Peer asked for resource {hash}");
@@ -129,8 +135,8 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
}
}
// Rebuild only once every referenced resource is in the app cache, and never underneath an
// open transaction, whose un-staged edits the swap would discard.
// Apply only once every referenced resource is in the app cache, and never underneath an
// open transaction, whose tool state names nodes a peer may have removed.
for document_id in self.dirty.clone() {
let Some(document) = documents.get_mut(&document_id) else {
self.dirty.remove(&document_id);
@@ -142,16 +148,18 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
if missing > 0 || transaction != TransactionStatus::Finished {
let reason = format!("missing {missing} transaction {transaction:?}");
if self.blocked_reason.get(&document_id) != Some(&reason) {
log::debug!("Sync rebuild for {document_id:?} waiting: {reason}");
log::debug!("Applying remote changes to {document_id:?} waits: {reason}");
self.blocked_reason.insert(document_id, reason);
}
continue;
}
self.blocked_reason.remove(&document_id);
self.dirty.remove(&document_id);
document.apply_remote_changes(responses);
// The swapped-in registry names resources this peer may still have to fetch or resolve.
// Stays dirty while a declaration the changes need is still on its way.
if document.apply_remote_changes(responses) {
self.dirty.remove(&document_id);
}
// The registry names resources this peer may still have to fetch or resolve.
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
}
}