diff --git a/Cargo.lock b/Cargo.lock index 78ce2dd1f1..430e4e93cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2866,6 +2866,7 @@ dependencies = [ "log", "math-parser", "migration-compiled", + "migration-core", "migration-formats", "migration-nodes", "node-macro", diff --git a/document/graph-storage/src/attributes/attr.rs b/document/graph-storage/src/attributes/attr.rs index 439d827e92..5e78c1a47f 100644 --- a/document/graph-storage/src/attributes/attr.rs +++ b/document/graph-storage/src/attributes/attr.rs @@ -24,7 +24,8 @@ pub mod node { pub const PINNED: &str = "ui::pinned"; pub const OUTPUT_NAMES: &str = "ui::output_names"; pub const OUTPUT_DESCRIPTIONS: &str = "ui::output_descriptions"; - pub const REFERENCE: &str = "ui::reference"; // TODO: Remove? + /// The built-in network definition a network was created from, stored on the network's attributes. See [`NetworkReference`](crate::NetworkReference). + pub const REFERENCE: &str = "ui::reference"; } } diff --git a/document/graph-storage/src/from_runtime.rs b/document/graph-storage/src/from_runtime.rs index 5f48d37305..81ff9e7a0a 100644 --- a/document/graph-storage/src/from_runtime.rs +++ b/document/graph-storage/src/from_runtime.rs @@ -491,7 +491,7 @@ fn write_ui_network_attributes( timestamp: TimeStamp, ) -> Result<(), ConversionError> { if let Some(reference) = metadata.reference(location) { - attributes.set(node::ui::REFERENCE, Value::Str(reference.to_string()), timestamp); + attributes.set(node::ui::REFERENCE, reference.to_value(), timestamp); } write_network_interface_attributes(attributes, metadata, location, timestamp)?; diff --git a/document/graph-storage/src/lib.rs b/document/graph-storage/src/lib.rs index 170207fd24..2e2a05b44f 100644 --- a/document/graph-storage/src/lib.rs +++ b/document/graph-storage/src/lib.rs @@ -9,6 +9,7 @@ pub mod history; mod history_metadata; pub mod ids; pub mod model; +mod network_reference; mod prior; pub mod registry; pub mod resources; @@ -30,6 +31,7 @@ pub use document::*; pub use history::{History, rehash_deltas}; pub use history_metadata::{HistoryMetadata, MetadataFact, Subject, WallStamp, rev_attr, user_attr}; pub use ids::*; +pub use network_reference::NetworkReference; pub use schema::*; pub use session::*; pub use sorted::Sorted; diff --git a/document/graph-storage/src/metadata_source.rs b/document/graph-storage/src/metadata_source.rs index 70468150aa..0d2fea0560 100644 --- a/document/graph-storage/src/metadata_source.rs +++ b/document/graph-storage/src/metadata_source.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap}; use core_types::uuid::NodeId as RuntimeNodeId; use graph_craft::document::NetworkLocation; -use crate::Value; +use crate::{NetworkReference, Value}; /// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per /// node, since every node carries an identity to restore even when it carries no `ui::*` attribute. @@ -98,7 +98,7 @@ pub trait NodeMetadataSource { } /// The definition the network was instantiated from, if it still names one. - fn reference(&self, _network: NetworkLocation) -> Option<&str> { + fn reference(&self, _network: NetworkLocation) -> Option { None } diff --git a/document/graph-storage/src/network_reference.rs b/document/graph-storage/src/network_reference.rs new file mode 100644 index 0000000000..52c9919a6e --- /dev/null +++ b/document/graph-storage/src/network_reference.rs @@ -0,0 +1,77 @@ +use crate::attr::node::ui::REFERENCE; +use crate::{Attributes, Value}; + +const IDENTIFIER: &str = "identifier"; +const VERSION: &str = "version"; + +/// The built-in network definition a network was created from, stored under [`REFERENCE`] on the network's attributes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NetworkReference { + pub identifier: String, + /// The definition's position in its lineage, like [`ProtoNode::version`](crate::ProtoNode). + pub version: u32, +} + +impl NetworkReference { + pub fn read(attributes: &Attributes) -> Option { + attributes.get(REFERENCE).filter(|value| !value.deleted).and_then(|value| Self::from_value(&value.value)) + } + + /// A bare identifier at version 1, so first versions keep the value they had before definitions were versioned. + pub fn to_value(&self) -> Value { + if self.version == 1 { + return Value::Str(self.identifier.clone()); + } + + Value::Object(vec![ + (IDENTIFIER.to_string(), Value::Str(self.identifier.clone())), + (VERSION.to_string(), Value::Int(self.version.into())), + ]) + } + + pub fn from_value(value: &Value) -> Option { + match value { + Value::Str(identifier) => Some(Self { + identifier: identifier.clone(), + version: 1, + }), + Value::Object(fields) => { + let field = |name: &str| fields.iter().find(|(key, _)| key == name).map(|(_, value)| value); + let (Some(Value::Str(identifier)), Some(Value::Int(version))) = (field(IDENTIFIER), field(VERSION)) else { + return None; + }; + + Some(Self { + identifier: identifier.clone(), + version: (*version).try_into().ok()?, + }) + } + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_through_its_value() { + for version in [1, 2] { + let reference = NetworkReference { + identifier: "Merge".to_string(), + version, + }; + assert_eq!(NetworkReference::from_value(&reference.to_value()), Some(reference)); + } + } + + #[test] + fn first_version_is_a_bare_identifier() { + let reference = NetworkReference { + identifier: "Merge".to_string(), + version: 1, + }; + assert_eq!(reference.to_value(), Value::Str("Merge".to_string())); + } +} diff --git a/document/graph-storage/src/tests/round_trip.rs b/document/graph-storage/src/tests/round_trip.rs index 203c04cd2d..4b29a1ca7f 100644 --- a/document/graph-storage/src/tests/round_trip.rs +++ b/document/graph-storage/src/tests/round_trip.rs @@ -895,3 +895,35 @@ fn large_input_value_round_trips_through_a_blob() { let error = registry.to_runtime_with_metadata(&declarations, &crate::blob::BlobBytes::new()).expect_err("a missing blob must error"); assert!(matches!(error, crate::to_runtime::ConversionError::BlobNotFound(hash) if hash == blob), "{error}"); } + +/// Names the nested network a built-in definition at `version`. +struct ReferenceMetadata { + version: u32, +} + +impl NodeMetadataSource for ReferenceMetadata { + fn reference(&self, network: NetworkLocation) -> Option { + (network == Some(NESTED)).then(|| crate::NetworkReference { + identifier: "Merge".into(), + version: self.version, + }) + } +} + +#[test] +fn network_reference_round_trips_with_its_version() { + for version in [1, 2] { + let network = create_nested_network(); + let conversion = Registry::convert_from_runtime(&network, &ReferenceMetadata { version }, &Default::default(), PeerId(0)).expect("the nested network converts"); + + let stored: Vec<_> = conversion.registry.networks.values().filter_map(|network| crate::NetworkReference::read(&network.attributes)).collect(); + assert_eq!(stored, vec![crate::NetworkReference { identifier: "Merge".into(), version }]); + + let (_, _, network_entries) = conversion + .registry + .to_runtime_with_full_metadata(&conversion.declarations, &conversion.blob_bytes) + .expect("the registry converts back"); + let references: Vec<_> = network_entries.iter().filter_map(|entry| entry.reference.as_deref()).collect(); + assert_eq!(references, vec!["Merge"]); + } +} diff --git a/document/graph-storage/src/to_runtime.rs b/document/graph-storage/src/to_runtime.rs index 6cd2523a0e..115c81b0a1 100644 --- a/document/graph-storage/src/to_runtime.rs +++ b/document/graph-storage/src/to_runtime.rs @@ -11,7 +11,7 @@ use rustc_hash::{FxHashMap, FxHashSet}; use crate::attr::*; use crate::blob::{BlobBytes, decode_blob}; use crate::metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry}; -use crate::{BlobHash, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value}; +use crate::{BlobHash, Implementation, NetworkId, NetworkReference, Node, NodeId, NodeInput, Position, ProtoNode, ROOT_NETWORK, Registry, ResourceId, Value, from_value}; #[derive(Debug, thiserror::Error)] pub enum ConversionError { @@ -421,7 +421,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, NetworkMetadataEntry { network, network_id, - reference: attributes.get_typed(node::ui::REFERENCE), + reference: NetworkReference::read(attributes).map(|reference| reference.identifier), pinned_order, import_metadata: attributes.get_or_default(network::IMPORT_METADATA), export_names: attributes.get_or_default(network::EXPORT_NAMES), diff --git a/document/migrations/core/src/declaration.rs b/document/migrations/core/src/declaration.rs index 5d9a748443..e37178d09a 100644 --- a/document/migrations/core/src/declaration.rs +++ b/document/migrations/core/src/declaration.rs @@ -1,28 +1,85 @@ -use document_graph_storage::{ProtoNode, ResourceEntry, ResourceId}; +use document_graph_storage::{Attributes, NetworkReference, ProtoNode, ResourceEntry, ResourceId}; use serde::Serialize; -/// A proto-node declaration at one version, written `identifier@version`. +/// What a declaration describes: a proto node, or a built-in network definition that instances copy. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +pub enum DeclarationKind { + #[default] + Proto, + Network, +} + +impl DeclarationKind { + fn is_proto(&self) -> bool { + *self == Self::Proto + } +} + +/// A declaration at one version, written `identifier@version`, or `network identifier@version` for a network definition. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] pub struct Declaration { pub identifier: &'static str, pub version: u32, + /// Skipped for proto nodes, so the IDs derived from declarations predating network definitions stay the same. + #[serde(skip_serializing_if = "DeclarationKind::is_proto")] + pub kind: DeclarationKind, } impl Declaration { pub const fn new(identifier: &'static str, version: u32) -> Self { - Self { identifier, version } + Self { + identifier, + version, + kind: DeclarationKind::Proto, + } + } + + pub const fn network(identifier: &'static str, version: u32) -> Self { + Self { + identifier, + version, + kind: DeclarationKind::Network, + } + } + + pub fn is_network(&self) -> bool { + self.kind == DeclarationKind::Network + } + + /// Whether a network's attributes name this network definition. + pub fn describes_network(&self, attributes: &Attributes) -> bool { + NetworkReference::read(attributes).is_some_and(|reference| self.is_reference(&reference)) + } + + /// Whether `reference` names this network definition. + pub fn is_reference(&self, reference: &NetworkReference) -> bool { + self.is_network() && reference.identifier == self.identifier && reference.version == self.version + } + + /// The reference a network of this definition stores. Meaningless for a proto node. + pub fn network_reference(&self) -> NetworkReference { + NetworkReference { + identifier: self.identifier.to_string(), + version: self.version, + } } } impl std::fmt::Display for Declaration { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}@{}", self.identifier, self.version) + match self.kind { + DeclarationKind::Proto => write!(f, "{}@{}", self.identifier, self.version), + DeclarationKind::Network => write!(f, "network {}@{}", self.identifier, self.version), + } } } -/// Names a declaration as `decl!("module::node"@2)`. +/// Names a declaration as `decl!("module::node"@2)`, or a network definition as `decl!(network "Merge"@2)`. #[macro_export] macro_rules! decl { + (network $identifier:literal @ $version:literal) => { + $crate::Declaration::network($identifier, $version) + }; ($identifier:literal @ $version:literal) => { $crate::Declaration::new($identifier, $version) }; diff --git a/document/migrations/core/src/lib.rs b/document/migrations/core/src/lib.rs index 624be749f9..123c101121 100644 --- a/document/migrations/core/src/lib.rs +++ b/document/migrations/core/src/lib.rs @@ -27,7 +27,7 @@ pub use compiler::{Compiler, MigrationHost, ValueType}; #[cfg(feature = "typed")] pub use connector::{InputConnector, NewNode, OutputConnector}; #[cfg(feature = "typed")] -pub use declaration::{Declaration, DeclarationResolver}; +pub use declaration::{Declaration, DeclarationKind, DeclarationResolver}; #[cfg(feature = "typed")] pub use document_graph_storage::NodeInput; pub use error::MigrationError; @@ -44,7 +44,7 @@ pub use registry::{register_migration, registered_migrations}; #[cfg(feature = "typed")] pub use value::{encode, literal, literal_of}; #[cfg(feature = "typed")] -pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View}; +pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements}; // For the registration `#[migration]`, `rename!`, and `format_migration!` generate #[doc(hidden)] diff --git a/document/migrations/core/src/view.rs b/document/migrations/core/src/view.rs index 2d61643692..638fd1950e 100644 --- a/document/migrations/core/src/view.rs +++ b/document/migrations/core/src/view.rs @@ -1,5 +1,5 @@ use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector}; -use document_graph_storage::{InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp}; +use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp}; use std::ops::Deref; /// Which part of the registry around an anchor a view reads or edits. A migration's footprint is the union of its views' regions. @@ -148,9 +148,9 @@ impl<'a> Graph<'a> { self.registry.node_instances.get(&id).filter(|node| node.network() == self.network) } - /// The declaration a node of this network implements, if it is one a migration knows. + /// The proto-node declaration a node of this network implements, if it is one a migration knows. pub fn declaration(&self, id: NodeId) -> Option { - let document_graph_storage::Implementation::ProtoNode(resource) = self.node(id)?.implementation() else { + let Implementation::ProtoNode(resource) = self.node(id)?.implementation() else { return None; }; self.resolver.declaration(*resource) @@ -196,6 +196,14 @@ impl<'a> Graph<'a> { } } +/// Whether `node` implements `declaration`: a proto node through its declaration resource, a network instance through the definition its network names. +pub fn implements(registry: &Registry, node: &document_graph_storage::Node, declaration: Declaration, resolver: &dyn DeclarationResolver) -> bool { + match node.implementation() { + Implementation::ProtoNode(resource) => !declaration.is_network() && resolver.declaration(*resource) == Some(declaration), + Implementation::Network(network) => registry.networks.get(network).is_some_and(|network| declaration.describes_network(&network.attributes)), + } +} + /// A parameter type of a migration: a window onto one region around the anchor that records edits rather than applying them. pub trait View<'a>: Sized { /// The region this view reads or edits. diff --git a/document/migrations/macros/src/lib.rs b/document/migrations/macros/src/lib.rs index 4311c6b795..633dfb99dd 100644 --- a/document/migrations/macros/src/lib.rs +++ b/document/migrations/macros/src/lib.rs @@ -13,6 +13,7 @@ use syn::{Error, FnArg, Ident, ItemFn, ReturnType, Type, parse_macro_input}; /// Turns a function into a node migration, named by its source and target declarations: /// `#[migration("module::node"@1 => @2)]` for a version step, `#[migration("module::old"@1 => "module::new"@2)]` for a replacement. +/// A `network` prefix names a built-in network definition, as in `#[migration(network "Merge"@1 => "module::merge"@2)]`. /// /// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, `Option<&dyn Compiler>` asks what only the /// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`. @@ -233,7 +234,16 @@ fn expand_rename(step: Step) -> syn::Result { } fn step_name(step: &Step) -> String { - format!("{}@{}=>{}@{}", step.source.identifier, step.source.version, step.target.identifier, step.target.version) + let prefix = |declaration: &Declaration| if declaration.network { "network " } else { "" }; + format!( + "{}{}@{}=>{}{}@{}", + prefix(&step.source), + step.source.identifier, + step.source.version, + prefix(&step.target), + step.target.identifier, + step.target.version + ) } /// Passes `migration` to `register` at startup: through `ctor` on native targets, and through an exported function the host calls @@ -259,8 +269,11 @@ fn registration(core: &TokenStream2, register: TokenStream2, migration: TokenStr } fn declaration(core: &TokenStream2, declaration: &Declaration) -> TokenStream2 { - let Declaration { identifier, version } = declaration; - quote!(#core::Declaration::new(#identifier, #version)) + let Declaration { identifier, version, network } = declaration; + match network { + true => quote!(#core::Declaration::network(#identifier, #version)), + false => quote!(#core::Declaration::new(#identifier, #version)), + } } /// How the expansion names `migration-core`: `crate` inside it, its (possibly renamed) dependency name elsewhere. diff --git a/document/migrations/macros/src/step.rs b/document/migrations/macros/src/step.rs index 68973473bc..c25addd080 100644 --- a/document/migrations/macros/src/step.rs +++ b/document/migrations/macros/src/step.rs @@ -1,16 +1,18 @@ use proc_macro2::{TokenStream, TokenTree}; use syn::parse::{Parse, ParseStream}; -use syn::{Error, LitInt, LitStr, Token}; +use syn::{Error, Ident, LitInt, LitStr, Token}; -/// A declaration as written in macro input: `"identifier"@version`. +/// A declaration as written in macro input: `"identifier"@version`, or `network "identifier"@version` for a network definition. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Declaration { pub identifier: String, pub version: u32, + pub network: bool, } impl Parse for Declaration { fn parse(input: ParseStream) -> syn::Result { + let network = parse_network_keyword(input)?; let identifier: LitStr = input.parse()?; input.parse::()?; let version: LitInt = input.parse()?; @@ -18,11 +20,26 @@ impl Parse for Declaration { Ok(Self { identifier: identifier.value(), version: version.base10_parse()?, + network, }) } } -/// `"identifier"@n => "identifier"@m`, or `"identifier"@n => @m` for a version step that keeps the identifier. +/// Consumes a leading `network` keyword, returning whether it was there. +fn parse_network_keyword(input: ParseStream) -> syn::Result { + if !input.peek(Ident) { + return Ok(false); + } + + let keyword: Ident = input.parse()?; + if keyword != "network" { + return Err(Error::new(keyword.span(), "expected `network` or a declaration identifier string")); + } + Ok(true) +} + +/// `"identifier"@n => "identifier"@m`, or `"identifier"@n => @m` for a version step that keeps the identifier and kind. Either side may be a +/// `network` definition. pub(crate) struct Step { pub source: Declaration, pub target: Declaration, @@ -33,9 +50,12 @@ impl Parse for Step { let source: Declaration = input.parse()?; input.parse::]>()?; - let target_identifier = match input.peek(LitStr) { - true => input.parse::()?.value(), - false => source.identifier.clone(), + let (target_identifier, target_network) = match input.peek(LitStr) || input.peek(Ident) { + true => { + let network = parse_network_keyword(input)?; + (input.parse::()?.value(), network) + } + false => (source.identifier.clone(), source.network), }; input.parse::()?; let target_version_literal: LitInt = input.parse()?; @@ -52,6 +72,7 @@ impl Parse for Step { let target = Declaration { identifier: target_identifier, version: target_version, + network: target_network, }; Ok(Self { source, target }) } diff --git a/document/migrations/runner/src/lib.rs b/document/migrations/runner/src/lib.rs index 5822e4f100..63c1d95946 100644 --- a/document/migrations/runner/src/lib.rs +++ b/document/migrations/runner/src/lib.rs @@ -32,6 +32,10 @@ pub enum RunnerError { Migration { migration: Declaration, anchor: NodeId, error: MigrationError }, #[error("node {anchor:?} chose {target}, which the migration from {migration} doesn't name")] UnnamedTarget { migration: Declaration, anchor: NodeId, target: Declaration }, + #[error("proto node {anchor:?} can't become {target}, which the migration from {migration} chose")] + ProtoToNetwork { migration: Declaration, anchor: NodeId, target: Declaration }, + #[error("node {anchor:?} adds a node of {declaration}, but migrations only add proto nodes")] + AddedNetworkDefinition { anchor: NodeId, declaration: Declaration }, #[error("node {anchor:?} adds two nodes of {declaration} under the key {key:?}")] DuplicateAddedNode { anchor: NodeId, declaration: Declaration, key: String }, #[error("added node {0:?} already exists")] diff --git a/document/migrations/runner/src/node.rs b/document/migrations/runner/src/node.rs index 63c526daa6..0521026d12 100644 --- a/document/migrations/runner/src/node.rs +++ b/document/migrations/runner/src/node.rs @@ -1,9 +1,11 @@ //! The node tier: `M` as a function on registry states, and the history rewrite derived from it. use crate::{MigrationBlobs, RunnerError}; +use document_graph_storage::TimeStamp; +use document_graph_storage::attributes::attr::node::ui::REFERENCE; use document_graph_storage::delta::compute_deltas; use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op}; -use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector}; +use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector, implements}; use std::collections::{HashMap, HashSet}; /// A [`DeclarationResolver`] over a fixed set of declarations for tests, whose resource IDs derive from `identifier@version` rather than the encoded declarations documents store. @@ -201,13 +203,11 @@ fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeI }); } - if let Some(node) = target.node_instances.get_mut(anchor) { - *node.implementation_mut() = Implementation::ProtoNode(resolver.resource(chosen)); - } + switch_implementation(&mut target, *anchor, chosen, resolver).map_err(|error| error.for_anchor(migration.source(), *anchor))?; used_declarations.push(chosen); used_declarations.extend(edits.added_nodes.iter().map(|added| added.node.declaration)); } - for declaration in used_declarations { + for declaration in used_declarations.into_iter().filter(|declaration| !declaration.is_network()) { if let Some(entry) = resolver.resource_entry(declaration) { target.resources.entry(resolver.resource(declaration)).or_insert(entry); } @@ -216,6 +216,65 @@ fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeI Ok(target) } +/// Why an anchor can't switch to the declaration its run chose. +enum SwitchError { + /// Only a network anchor can become a network definition, since a proto node has no network to name it. + ProtoToNetwork(Declaration), +} + +impl SwitchError { + fn for_anchor(self, migration: Declaration, anchor: NodeId) -> RunnerError { + match self { + Self::ProtoToNetwork(target) => RunnerError::ProtoToNetwork { migration, anchor, target }, + } + } +} + +/// Switch `anchor` to `declaration`. A network anchor becoming a proto node drops the network it implemented, with every network nested in it. +fn switch_implementation(registry: &mut Registry, anchor: NodeId, declaration: Declaration, resolver: &dyn DeclarationResolver) -> Result<(), SwitchError> { + let Some(implementation) = registry.node_instances.get(&anchor).map(|node| node.implementation().clone()) else { + return Ok(()); + }; + + match (implementation, declaration.is_network()) { + (Implementation::ProtoNode(_), true) => Err(SwitchError::ProtoToNetwork(declaration)), + (Implementation::Network(network), true) => { + if let Some(network) = registry.networks.get_mut(&network) { + network.attributes.set(REFERENCE, declaration.network_reference().to_value(), TimeStamp::ORIGIN); + } + Ok(()) + } + (implementation, false) => { + if let Implementation::Network(network) = implementation { + remove_network_tree(registry, network); + } + if let Some(node) = registry.node_instances.get_mut(&anchor) { + *node.implementation_mut() = Implementation::ProtoNode(resolver.resource(declaration)); + } + Ok(()) + } + } +} + +/// Remove `network`, its nodes, and every network one of them implements. +fn remove_network_tree(registry: &mut Registry, network: NetworkId) { + let mut pending = vec![network]; + + while let Some(network) = pending.pop() { + registry.networks.remove(&network); + + registry.node_instances.retain(|_, node| { + if node.network() != network { + return true; + } + if let Implementation::Network(nested) = node.implementation() { + pending.push(*nested); + } + false + }); + } +} + /// Whether a live node of `registry` implements `declaration`. pub fn holds(registry: &Registry, declaration: Declaration, resolver: &dyn DeclarationResolver) -> bool { !anchors(declaration, registry, resolver).is_empty() @@ -226,7 +285,7 @@ fn anchors(declaration: Declaration, registry: &Registry, resolver: &dyn Declara let mut anchors: Vec = registry .node_instances .iter() - .filter(|(_, node)| matches!(node.implementation(), Implementation::ProtoNode(resource) if resolver.declaration(*resource) == Some(declaration))) + .filter(|(_, node)| implements(registry, node, declaration, resolver)) .map(|(id, _)| *id) .collect(); anchors.sort_unstable(); @@ -240,6 +299,12 @@ fn add_nodes(target: &mut Registry, runs: &[(NodeId, Edits)], resolver: &dyn Dec let Some(network) = target.node_instances.get(anchor).map(Node::network) else { continue }; for added in &edits.added_nodes { + if added.node.declaration.is_network() { + return Err(RunnerError::AddedNetworkDefinition { + anchor: *anchor, + declaration: added.node.declaration, + }); + } if !added_ids.insert(added.id) { return Err(RunnerError::DuplicateAddedNode { anchor: *anchor, @@ -305,7 +370,7 @@ struct Branch { /// Undoing and then editing leaves an abandoned branch, which rewrites like any other since each delta only depends on its ancestors. /// Fails on a delta that merges branches, or whose parent isn't in `history`. /// -/// A migration reading the graph or asking the compiler needs whole states, so it only runs at the boundaries undo can land on, the end of an interaction, +/// A migration reading the graph, asking the compiler, or starting from a network definition needs whole states, so it only runs at the boundaries undo can land on, the end of an interaction, /// and rewrites everything since the last one as a single chain. Each delta inside maps to the boundary before it, and `kept` names further states to keep. /// /// Each delta costs one full evaluation of `M` and one full diff, so this is O(history × registry), until the RFC's footprint-scoped @@ -328,7 +393,7 @@ pub(crate) fn rewrite_history( } let child_counts = children.clone(); - let whole_states_only = migration.footprint().reads_network(); + let whole_states_only = needs_whole_states(migration); let is_boundary = |delta: &Delta| { let continues_alone = child_counts.get(&Some(delta.id)) == Some(&1) && child_authors.get(&delta.id).is_some_and(|authors| authors.contains(&delta.author)); delta.is_interaction_end() || !continues_alone || kept.contains(&delta.id) @@ -425,6 +490,12 @@ pub fn registry_at(deltas: &[Delta], head: Option) -> Result bool { + migration.footprint().reads_network() || migration.source().is_network() +} + /// Ops `M` can't affect and `compute_deltas` doesn't diff, which therefore keep their original form. fn passes_through(kind: &RegistryDelta) -> bool { matches!(kind, RegistryDelta::RegisterPeer { .. } | RegistryDelta::Other(_)) diff --git a/document/migrations/runner/src/order.rs b/document/migrations/runner/src/order.rs index 95a4b1fb5c..a9019db572 100644 --- a/document/migrations/runner/src/order.rs +++ b/document/migrations/runner/src/order.rs @@ -2,7 +2,8 @@ use crate::node::{apply_migration, rewrite_history}; use crate::{MigrationBlobs, RewrittenHistory, RunnerError}; -use document_graph_storage::{Delta, Implementation, Node, Registry, RegistryDelta, Rev}; +use document_graph_storage::attributes::attr::node::ui::REFERENCE; +use document_graph_storage::{Delta, Implementation, NetworkReference, Node, Registry, RegistryDelta, Rev}; use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration}; use std::collections::{BTreeSet, HashMap, HashSet}; @@ -121,8 +122,24 @@ pub fn migrate_registry( Ok(migrated) } -/// Whether `kind` stores a node implementing `declaration`. +/// Whether `kind` stores a node implementing `declaration`, or for a network definition, a network naming it. pub fn references(kind: &RegistryDelta, declaration: Declaration, resolver: &dyn DeclarationResolver) -> bool { + if declaration.is_network() { + return match kind { + RegistryDelta::AddNetwork { network, .. } => declaration.describes_network(&network.attributes), + RegistryDelta::RemoveNetwork { snapshot, .. } => declaration.describes_network(&snapshot.attributes), + RegistryDelta::ChangeNetworkAttribute { delta, .. } => { + delta.key == REFERENCE + && delta + .value + .as_ref() + .and_then(NetworkReference::from_value) + .is_some_and(|reference| declaration.is_reference(&reference)) + } + _ => false, + }; + } + let is_declaration = |implementation: &Implementation| matches!(implementation, Implementation::ProtoNode(resource) if resolver.declaration(*resource) == Some(declaration)); let implements = |node: &Node| is_declaration(node.implementation()); diff --git a/document/migrations/runner/src/testing.rs b/document/migrations/runner/src/testing.rs index 37887077c7..c009680cd1 100644 --- a/document/migrations/runner/src/testing.rs +++ b/document/migrations/runner/src/testing.rs @@ -1,10 +1,13 @@ //! What every migration's tests need: fixtures for one anchor, and the property that rewriting a generated history gives `M` of it at every step. //! Panics on failure, since it only runs in tests. -use crate::node::{apply_migration, rewrite_history}; +use crate::node::{apply_migration, needs_whole_states, rewrite_history}; use crate::{DeclarationTable, MigrationBlobs, RunnerError, references, registry_at}; -use document_graph_storage::{Delta, ExportSlot, Implementation, Network, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, UserId, apply_retired_op}; -use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, literal, registered_migrations}; +use document_graph_storage::attributes::attr::node::ui::REFERENCE; +use document_graph_storage::{ + Delta, ExportSlot, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp, UserId, apply_retired_op, +}; +use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, implements, literal, registered_migrations}; use std::collections::HashSet; /// A root network built node by node, for running one migration on. @@ -26,11 +29,35 @@ impl Fixture { } pub fn add(&mut self, declaration: Declaration, inputs: Vec) -> NodeId { + self.add_in(ROOT_NETWORK, declaration, inputs) + } + + /// Add a proto node of `declaration` to `network`. + pub fn add_in(&mut self, network: NetworkId, declaration: Declaration, inputs: Vec) -> NodeId { + let resource = self.table.register(declaration); + self.insert_node(network, Implementation::ProtoNode(resource), inputs) + } + + /// Add a node to the root network implementing a new, empty network that names the network definition `declaration`. + pub fn add_network(&mut self, declaration: Declaration, inputs: Vec) -> (NodeId, NetworkId) { + assert!(declaration.is_network(), "{declaration} is not a network definition"); + + self.next_id += 1; + let network_id = NetworkId(self.next_id); + + let mut network = Network::default(); + network.attributes.set(REFERENCE, declaration.network_reference().to_value(), TimeStamp::ORIGIN); + self.registry.networks.insert(network_id, network); + + let node = self.insert_node(ROOT_NETWORK, Implementation::Network(network_id), inputs); + (node, network_id) + } + + fn insert_node(&mut self, network: NetworkId, implementation: Implementation, inputs: Vec) -> NodeId { self.next_id += 1; let id = NodeId(self.next_id); - let resource = self.table.register(declaration); - let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(resource), inputs.len()); + let mut node = Node::new(network, implementation, inputs.len()); for (slot, input) in node.inputs_mut().iter_mut().zip(inputs) { slot.input = input; } @@ -40,7 +67,11 @@ impl Fixture { } pub fn export(&mut self, input: NodeInput) { - let network = self.registry.networks.get_mut(&ROOT_NETWORK).expect("the fixture creates the root network"); + self.export_from(ROOT_NETWORK, input); + } + + pub fn export_from(&mut self, network: NetworkId, input: NodeInput) { + let network = self.registry.networks.get_mut(&network).expect("exports go to a network the fixture created"); network.exports.push(ExportSlot { target: Some(input), ..Default::default() @@ -135,7 +166,11 @@ struct Generator<'a> { impl Generator<'_> { fn commit(&mut self, op: RegistryDelta) { - self.session.stage_computed_ops(vec![op]).expect("generated ops are valid"); + self.commit_interaction(vec![op]); + } + + fn commit_interaction(&mut self, ops: Vec) { + self.session.stage_computed_ops(ops).expect("generated ops are valid"); let revs = self.session.retire_all().expect("staged ops retire"); if let Some(last) = revs.last() { self.session.mark_interaction_end(*last); @@ -149,24 +184,37 @@ impl Generator<'_> { nodes } - fn declaration_of(&self, node: &Node) -> Option { - let Implementation::ProtoNode(resource) = node.implementation() else { return None }; - [self.source, CONSUMER].into_iter().find(|declaration| DeclarationTable::resource_id(*declaration) == *resource) + fn live_nodes_in(&self, network: NetworkId) -> Vec { + let registry = self.session.registry(); + self.live_nodes().into_iter().filter(|node| registry.node_instances[node].network() == network).collect() } - /// A literal or a wire to another live node. - fn input_for(&mut self, declaration: Declaration, slot: usize, exclude: Option) -> NodeInput { + fn declaration_of(&self, node: &Node) -> Option { + if implements(self.session.registry(), node, self.source, &*self.table) { + return Some(self.source); + } + + let Implementation::ProtoNode(resource) = node.implementation() else { return None }; + (DeclarationTable::resource_id(CONSUMER) == *resource).then_some(CONSUMER) + } + + /// A literal, a wire to another live node of `network`, or inside a source network, one of its imports. + fn input_for(&mut self, declaration: Declaration, slot: usize, exclude: Option, network: NetworkId) -> NodeInput { let is_source = declaration == self.source; let reads_own_output = !is_source || (self.contract.reads_own_output)(slot); let registry = self.session.registry(); let allowed = |node: &NodeId| reads_own_output || self.declaration_of(®istry.node_instances[node]) != Some(self.source); - let candidates: Vec = self.live_nodes().into_iter().filter(|node| Some(*node) != exclude && allowed(node)).collect(); + let candidates: Vec = self.live_nodes_in(network).into_iter().filter(|node| Some(*node) != exclude && allowed(node)).collect(); if !candidates.is_empty() && self.random.below(2) == 0 { let node = self.random.pick(&candidates); return NodeInput::Node { id: node, index: 0 }; } + if network != ROOT_NETWORK && self.contract.input_count > 0 && self.random.below(2) == 0 { + let index = self.random.below(self.contract.input_count) as u32; + return NodeInput::Import { index }; + } if is_source { (self.contract.literal)(&mut self.random, slot) @@ -175,8 +223,62 @@ impl Generator<'_> { } } + /// An instance of the source network definition with one inner node, adding the network before the node that implements it, as the editor does. + fn add_network_instance(&mut self) { + let network_id = NetworkId(self.session.next_node_id().0); + let mut network = Network::default(); + network.attributes.set(REFERENCE, self.source.network_reference().to_value(), TimeStamp::ORIGIN); + + let inner_id = self.session.next_node_id(); + let mut inner = Node::new(network_id, Implementation::ProtoNode(self.table.register(CONSUMER)), CONSUMER_INPUTS); + for slot in 0..CONSUMER_INPUTS { + inner.inputs_mut()[slot].input = self.input_for(CONSUMER, slot, None, network_id); + } + + let mut instance = Node::new(ROOT_NETWORK, Implementation::Network(network_id), self.contract.input_count); + for slot in 0..self.contract.input_count { + instance.inputs_mut()[slot].input = self.input_for(self.source, slot, None, ROOT_NETWORK); + } + let instance_id = self.session.next_node_id(); + + self.commit_interaction(vec![ + RegistryDelta::AddNetwork { id: network_id, network }, + RegistryDelta::AddNode { id: inner_id, node: inner }, + RegistryDelta::SetNetworkExport { + id: network_id, + index: 0, + export: Some(NodeInput::Node { id: inner_id, index: 0 }), + }, + RegistryDelta::AddNode { id: instance_id, node: instance }, + ]); + } + + /// Remove a node, along with the network it implements and that network's nodes. + fn remove(&mut self, id: NodeId) { + let registry = self.session.registry(); + let snapshot = registry.node_instances[&id].clone(); + + let mut ops = Vec::new(); + if let Implementation::Network(network) = snapshot.implementation() + && let Some(network_snapshot) = registry.networks.get(network) + { + for inner in self.live_nodes_in(*network) { + let snapshot = registry.node_instances[&inner].clone(); + ops.push(RegistryDelta::RemoveNode { id: inner, snapshot }); + } + ops.push(RegistryDelta::RemoveNetwork { + id: *network, + snapshot: network_snapshot.clone(), + }); + } + ops.insert(0, RegistryDelta::RemoveNode { id, snapshot }); + + self.commit_interaction(ops); + } + fn step(&mut self) { let nodes = self.live_nodes(); + let root_nodes = self.live_nodes_in(ROOT_NETWORK); match self.random.below(11) { 0..=3 => { @@ -185,11 +287,15 @@ impl Generator<'_> { } else { (CONSUMER, CONSUMER_INPUTS) }; + if declaration.is_network() { + self.add_network_instance(); + return; + } let resource = self.table.register(declaration); let mut node = Node::new(ROOT_NETWORK, Implementation::ProtoNode(resource), input_count); for slot in 0..input_count { - node.inputs_mut()[slot].input = self.input_for(declaration, slot, None); + node.inputs_mut()[slot].input = self.input_for(declaration, slot, None, ROOT_NETWORK); } let id = self.session.next_node_id(); self.commit(RegistryDelta::AddNode { id, node }); @@ -203,19 +309,18 @@ impl Generator<'_> { } let index = self.random.below(node.inputs().len()); - let new_input = self.input_for(declaration, index, Some(id)); + let new_input = self.input_for(declaration, index, Some(id), node.network()); if node.inputs()[index].input == new_input { return; } self.commit(RegistryDelta::ChangeNodeInput { id, index: index as u32, new_input }); } - 7 if !nodes.is_empty() => { - let id = self.random.pick(&nodes); - let snapshot = self.session.registry().node_instances[&id].clone(); - self.commit(RegistryDelta::RemoveNode { id, snapshot }); + 7 if !root_nodes.is_empty() => { + let id = self.random.pick(&root_nodes); + self.remove(id); } - 8 | 9 if !nodes.is_empty() => { - let id = self.random.pick(&nodes); + 8 | 9 if !root_nodes.is_empty() => { + let id = self.random.pick(&root_nodes); let index = self.random.below(2) as u32; let export = Some(NodeInput::Node { id, index: 0 }); @@ -283,7 +388,8 @@ pub fn check_commutation_with(migration: &dyn NodeMigration, contract: &SourceCo let rewritten = rewrite_history(migration, &history, &table, host, &HashSet::new(), &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: rewrite failed: {error}")); - for delta in &history { + // A migration needing whole states maps a delta inside an interaction to the boundary before it, so only boundaries are comparable + for delta in history.iter().filter(|delta| !needs_whole_states(migration) || delta.is_interaction_end()) { let original = registry_at(&history, Some(delta.id)).unwrap_or_else(|error| panic!("seed {seed}: {error}")); let expected = apply_migration(migration, &original, &table, host, &mut MigrationBlobs::default()).unwrap_or_else(|error| panic!("seed {seed}: M failed: {error}")); let replayed = registry_at(&rewritten.deltas, rewritten.revs[&delta.id]).unwrap_or_else(|error| panic!("seed {seed}: {error}")); diff --git a/document/migrations/runner/tests/node_migrations/main.rs b/document/migrations/runner/tests/node_migrations/main.rs index 4d96062cb5..4e7bcfab59 100644 --- a/document/migrations/runner/tests/node_migrations/main.rs +++ b/document/migrations/runner/tests/node_migrations/main.rs @@ -1,6 +1,7 @@ mod blobs; mod compiler; mod examples; +mod networks; mod registration; mod rewrite; diff --git a/document/migrations/runner/tests/node_migrations/networks.rs b/document/migrations/runner/tests/node_migrations/networks.rs new file mode 100644 index 0000000000..6a6e33810d --- /dev/null +++ b/document/migrations/runner/tests/node_migrations/networks.rs @@ -0,0 +1,125 @@ +//! Network definitions as migration sources: a built-in subgraph collapsing into a proto node, and a version step of one. + +use crate::{Tagged, inputs, wire}; +use document_graph_storage::attributes::attr::node::ui::REFERENCE; +use document_graph_storage::{AttributeDelta, Implementation, NetworkId, NetworkReference, NodeId, NodeInput, RegistryDelta}; +use migration_core::{NewNode, Upstream, decl, literal, migration, rename}; +use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo, registered}; +use migration_runner::{DeclarationTable, RunnerError, references}; + +// The Merge subgraph became the `merge` proto node, which takes the instance's inputs as they are. Inner edits are dropped with the subgraph +rename!(network "Merge"@1 => "graphic_nodes::merge"@2); + +rename!(network "Artboard"@1 => @2); + +/// Adds a node of a network definition, which the runner rejects since only proto nodes can be added. +#[migration(network "Frame"@1 => @2)] +pub fn add_network_definition(upstream: &mut Upstream) { + upstream.add_node(NewNode { + declaration: decl!(network "Merge"@1), + inputs: Vec::new(), + }); +} + +const MERGE: migration_core::Declaration = decl!(network "Merge"@1); + +/// A Merge instance in the root network whose subgraph holds the frozen shape, plus `extra_inner_nodes` the user added. +fn merge_fixture(extra_inner_nodes: usize) -> (Fixture, NodeId, NetworkId, NodeId) { + let mut fixture = Fixture::new(registered(MERGE)); + let (merge, network) = fixture.add_network(MERGE, vec![literal(Tagged::Number(1.)), literal(Tagged::Number(2.))]); + + let into_group = fixture.add_in(network, decl!("graphic_nodes::into_group"@1), vec![NodeInput::Import { index: 0 }]); + fixture.export_from(network, wire(into_group, 0)); + for _ in 0..extra_inner_nodes { + fixture.add_in(network, decl!("graphic_nodes::into_group"@1), vec![NodeInput::Import { index: 1 }]); + } + + (fixture, merge, network, into_group) +} + +#[test] +fn network_anchor_collapses_into_proto_node() { + let (fixture, merge, network, into_group) = merge_fixture(0); + + let migrated = fixture.migrate(registered(MERGE)).unwrap(); + + assert_eq!(fixture.declaration_of(&migrated, merge), Some(decl!("graphic_nodes::merge"@2))); + assert_eq!(inputs(&migrated, merge), inputs(&fixture.registry, merge)); + assert!(!migrated.networks.contains_key(&network)); + assert!(!migrated.node_instances.contains_key(&into_group)); +} + +#[test] +fn edited_subgraph_collapses_too() { + let (fixture, merge, network, _) = merge_fixture(1); + + let migrated = fixture.migrate(registered(MERGE)).unwrap(); + + assert_eq!(fixture.declaration_of(&migrated, merge), Some(decl!("graphic_nodes::merge"@2))); + assert!(!migrated.networks.contains_key(&network)); + assert!(migrated.node_instances.values().all(|node| node.network() != network)); +} + +#[test] +fn adding_a_network_definition_fails() { + let migration = registered(decl!(network "Frame"@1)); + let mut fixture = Fixture::new(migration); + let (frame, _) = fixture.add_network(decl!(network "Frame"@1), Vec::new()); + + let result = fixture.migrate(migration); + + assert!(matches!(result, Err(RunnerError::AddedNetworkDefinition { anchor, .. }) if anchor == frame)); +} + +#[test] +fn network_of_another_version_is_no_anchor() { + let mut fixture = Fixture::new(registered(MERGE)); + fixture.add_network(decl!(network "Merge"@2), Vec::new()); + + let migrated = fixture.migrate(registered(MERGE)).unwrap(); + + assert_eq!(migrated, fixture.registry); +} + +#[test] +fn network_version_step_names_the_new_version() { + let migration = registered(decl!(network "Artboard"@1)); + let mut fixture = Fixture::new(migration); + let (artboard, network) = fixture.add_network(decl!(network "Artboard"@1), vec![literal(Tagged::Number(1.))]); + + let migrated = fixture.migrate(migration).unwrap(); + + assert_eq!(NetworkReference::read(&migrated.networks[&network].attributes), Some(decl!(network "Artboard"@2).network_reference())); + assert_eq!(migrated.node_instances[&artboard].implementation(), &Implementation::Network(network)); +} + +#[test] +fn reference_write_is_pending_for_network_definition() { + let delta = RegistryDelta::ChangeNetworkAttribute { + id: NetworkId(1), + delta: AttributeDelta { + key: REFERENCE.to_string(), + value: Some(MERGE.network_reference().to_value()), + }, + }; + + assert!(references(&delta, MERGE, &DeclarationTable::default())); + assert!(!references(&delta, decl!(network "Merge"@2), &DeclarationTable::default())); + assert!(!references(&delta, decl!(network "Artboard"@1), &DeclarationTable::default())); +} + +fn numbers(input_count: usize) -> SourceContract { + SourceContract::new(input_count, |random, _| literal(Tagged::Number(random.below(10) as f64))) +} + +#[test] +fn collapse_commutes() { + check_commutation(registered(MERGE), &numbers(2)); + check_undo(registered(MERGE), &numbers(2)); +} + +#[test] +fn network_version_step_commutes() { + check_commutation(registered(decl!(network "Artboard"@1)), &numbers(1)); + check_undo(registered(decl!(network "Artboard"@1)), &numbers(1)); +} diff --git a/document/migrations/runner/tests/node_migrations/registration.rs b/document/migrations/runner/tests/node_migrations/registration.rs index 7477bf53d1..061d22fcb6 100644 --- a/document/migrations/runner/tests/node_migrations/registration.rs +++ b/document/migrations/runner/tests/node_migrations/registration.rs @@ -20,6 +20,9 @@ fn every_migration_registers_once() { decl!("choice::toggle"@1), decl!("choice::unnamed"@1), decl!("graphene_core::ops::AddNode"@1), + decl!(network "Artboard"@1), + decl!(network "Frame"@1), + decl!(network "Merge"@1), decl!("math_nodes::multiply"@1), decl!("order::asking"@1), decl!("order::inspector"@1), diff --git a/document/migrations/snapshot/src/lineage.rs b/document/migrations/snapshot/src/lineage.rs index 45dd588f36..9780fd468a 100644 --- a/document/migrations/snapshot/src/lineage.rs +++ b/document/migrations/snapshot/src/lineage.rs @@ -4,34 +4,61 @@ use std::collections::BTreeSet; use std::path::Path; use syn::parse::{Parse, ParseStream}; -/// `identifier@version`. +/// `identifier@version`. A network definition's identifier starts with [`NETWORK`], which no node's identifier does. pub(crate) type Declaration = (String, u32); +/// Starts the identifier of a network definition, which the editor's catalog declares instead of a node crate. +const NETWORK: &str = "network "; + /// The source and target of one migration in `migration-nodes`. pub(crate) struct MigrationStep { pub source: Declaration, pub target: Declaration, } -/// `"id"@1 => @2` or `"id"@1 => "other"@2`, as `#[migration]` and `rename!` take it. +/// `"id"@1 => @2` or `"id"@1 => "other"@2`, as `#[migration]` and `rename!` take it. Either side may be a `network` definition. impl Parse for MigrationStep { fn parse(input: ParseStream) -> syn::Result { + let source_network = parse_network_keyword(input)?; let identifier: syn::LitStr = input.parse()?; input.parse::()?; let version: syn::LitInt = input.parse()?; input.parse::]>()?; - let target_identifier = if input.peek(syn::LitStr) { input.parse::()?.value() } else { identifier.value() }; + // A version step keeps the identifier and its kind + let (target_identifier, target_network) = if input.peek(syn::LitStr) || input.peek(syn::Ident) { + let network = parse_network_keyword(input)?; + (input.parse::()?.value(), network) + } else { + (identifier.value(), source_network) + }; input.parse::()?; let target_version: syn::LitInt = input.parse()?; Ok(Self { - source: (identifier.value(), version.base10_parse()?), - target: (target_identifier, target_version.base10_parse()?), + source: (named(identifier.value(), source_network), version.base10_parse()?), + target: (named(target_identifier, target_network), target_version.base10_parse()?), }) } } +/// Consumes a leading `network` keyword, returning whether it was there. +fn parse_network_keyword(input: ParseStream) -> syn::Result { + if !input.peek(syn::Ident) { + return Ok(false); + } + + let keyword: syn::Ident = input.parse()?; + if keyword != "network" { + return Err(syn::Error::new(keyword.span(), "expected `network` or a declaration identifier string")); + } + Ok(true) +} + +fn named(identifier: String, network: bool) -> String { + if network { format!("{NETWORK}{identifier}") } else { identifier } +} + /// Every migration step the crate at `directory` compiles, following its modules from `lib.rs` so a file no `mod` declares doesn't count. pub(crate) fn find_migrations(directory: &Path) -> Result, String> { let mut steps = Vec::new(); @@ -110,8 +137,8 @@ pub(crate) fn lineage_problems(nodes: &[Declaration], migrations: &[MigrationSte } } - // A target is a current declaration, or a step on the way to one - for step in migrations { + // A target is a current declaration, or a step on the way to one. Network definitions aren't checked, since the editor declares them + for step in migrations.iter().filter(|step| !step.target.0.starts_with(NETWORK)) { if !current.contains(&step.target) && !sources.contains(&step.target) { let ((source, from), (target, to)) = (&step.source, &step.target); problems.push(format!( @@ -144,6 +171,27 @@ mod tests { assert_eq!((replacement.source, replacement.target), (declaration("a::B", 2), declaration("c::D", 3))); } + #[test] + fn parses_network_definitions_on_either_side() { + let version_step: MigrationStep = syn::parse_str(r#"network "A"@1 => @2"#).unwrap(); + assert_eq!((version_step.source, version_step.target), (declaration("network A", 1), declaration("network A", 2))); + + let collapse: MigrationStep = syn::parse_str(r#"network "A"@1 => "c::D"@2"#).unwrap(); + assert_eq!((collapse.source, collapse.target), (declaration("network A", 1), declaration("c::D", 2))); + + assert!(syn::parse_str::(r#"subgraph "A"@1 => @2"#).is_err()); + } + + #[test] + fn network_steps_lead_to_nodes_and_to_definitions_this_check_cannot_see() { + let nodes = [declaration("c::D", 2)]; + let migrations = [ + step(declaration("network A", 1), declaration("c::D", 2)), + step(declaration("network B", 1), declaration("network B", 2)), + ]; + assert!(lineage_problems(&nodes, &migrations).is_empty()); + } + #[test] fn whole_lineages_pass() { let nodes = [declaration("a", 1), declaration("b", 3)]; diff --git a/editor/Cargo.toml b/editor/Cargo.toml index 7775699a07..e5413702ac 100644 --- a/editor/Cargo.toml +++ b/editor/Cargo.toml @@ -80,3 +80,4 @@ env_logger = { workspace = true } futures = { workspace = true } node-macro = { workspace = true } core-types = { workspace = true } +migration-core = { workspace = true, features = ["typed"] } diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs index d50cd88924..24fc64af1e 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs @@ -124,6 +124,10 @@ pub struct DocumentNodeDefinition { /// Used to create the [`DefinitionIdentifier::Network`] identifier. pub identifier: &'static str, + /// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly. + /// Instances store it next to their reference. Proto-node definitions take theirs from the node macro. + pub version: u32, + /// The default [`NodeTemplate`] this definition instantiates. pub node_template: NodeTemplate, @@ -154,6 +158,7 @@ fn document_node_definitions() -> HashMap HashMap HashMap HashMap HashMap HashMap HashMap HashMap HashMap HashMap Option<& DOCUMENT_NODE_TYPES.get(identifier) } +/// The current version of the network definition `identifier`, or 1 for a reference that names no definition. +pub fn network_definition_version(identifier: &str) -> u32 { + resolve_network_node_type(identifier).map_or(1, |definition| definition.version) +} + impl InputTypeConstraint { #[must_use] fn type_name(ty: &Type) -> String { @@ -1679,7 +1698,7 @@ impl DocumentNodeDefinition { #[cfg(test)] mod test { - use super::resolve_network_node_type; + use super::{DOCUMENT_NODE_TYPES, DefinitionIdentifier, resolve_network_node_type}; use crate::test_utils::test_prelude::*; use graph_craft::document::NodeId; @@ -1755,6 +1774,20 @@ mod test { let empty: Vec<_> = CATEGORY_ORDER.iter().filter(|category| !categories.contains(*category)).collect(); assert!(empty.is_empty(), "`CATEGORY_ORDER` lists categories with no nodes: {empty:?}"); } + + #[test] + fn every_bumped_network_definition_has_a_migration_leading_to_it() { + let targets: Vec<_> = migration_core::registered_migrations().iter().map(|migration| migration.target()).collect(); + + for (identifier, definition) in DOCUMENT_NODE_TYPES.iter() { + if !matches!(identifier, DefinitionIdentifier::Network(_)) || definition.version == 1 { + continue; + } + + let declaration = migration_core::Declaration::network(definition.identifier, definition.version); + assert!(targets.contains(&declaration), "{declaration} has no migration leading to it"); + } + } } #[cfg(test)] diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs index b237abe6e2..78793f346a 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs @@ -43,6 +43,7 @@ pub(super) fn post_process_nodes(custom: Vec) -> HashMap description, inspector, output_fields, + version, .. } = metadata; @@ -85,6 +86,7 @@ pub(super) fn post_process_nodes(custom: Vec) -> HashMap identifier, DocumentNodeDefinition { identifier: display_name, + version: *version, node_template: NodeTemplate { inputs, call_argument: input_type.clone(), diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs index cf87f36d58..2eb35530bb 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs @@ -1,4 +1,4 @@ -use super::storage_metadata::{input_metadata_entry_from_runtime, position_from_runtime}; +use super::storage_metadata::{input_metadata_entry_from_runtime, position_from_runtime, versioned_reference}; use super::{DocumentNodePersistentMetadata, LayerPosition, NodePosition, NodeTypePersistentMetadata}; use super::{InputMetadata, InputPersistentMetadata}; use document_graph_storage::attr::network as network_attr; @@ -280,7 +280,7 @@ impl EditorDelta { let delta = match change { NetworkMetadataChange::Reference(reference) => AttributeDelta { key: node_attr::ui::REFERENCE.to_string(), - value: reference.clone().map(Value::Str), + value: reference.clone().map(|identifier| versioned_reference(identifier).to_value()), }, NetworkMetadataChange::PinnedOrder(order) => { let stored: Vec<_> = order.iter().map(|node_id| storage_node_id(*node_id)).collect(); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs index 71050b85e0..3bbc5d7e54 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/storage_metadata.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap}; use document_graph_storage::attr::session; -use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position, Value, from_value, to_value}; +use document_graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NetworkReference, NodeMetadataEntry, NodeMetadataSource, Position, Value, from_value, to_value}; use glam::IVec2; use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork}; use graphene_std::vector::style::RenderMode; @@ -17,6 +17,7 @@ use super::{ DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing, }; +use crate::messages::portfolio::document::node_graph::document_node_definitions::network_definition_version; use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings; use crate::messages::portfolio::document::utility_types::misc::SnappingState; use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers; @@ -131,8 +132,9 @@ impl NodeMetadataSource for StorageMetadataView<'_> { self.subnetwork_persistent(network).map(|persistent| persistent.export_descriptions.clone()).unwrap_or_default() } - fn reference(&self, network: NetworkLocation) -> Option<&str> { - self.network_persistent(network)?.reference.as_deref() + fn reference(&self, network: NetworkLocation) -> Option { + let identifier = self.network_persistent(network)?.reference.clone()?; + Some(versioned_reference(identifier)) } fn pinned_order(&self, network: NetworkLocation) -> Vec { @@ -166,6 +168,12 @@ impl DocumentSettings<'_> { } } +/// The stored form of a network's reference. Opening a document migrates every instance to its definition's current version, so that is the version it holds. +pub(super) fn versioned_reference(identifier: String) -> NetworkReference { + let version = network_definition_version(&identifier); + NetworkReference { identifier, version } +} + /// The stored position of a node, which pairs with `is_layer` to reconstruct the runtime node type. pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position { match node_type { diff --git a/node-graph/rfcs/document-format-migrations.md b/node-graph/rfcs/document-format-migrations.md index f5ef3e9515..06d452ceec 100644 --- a/node-graph/rfcs/document-format-migrations.md +++ b/node-graph/rfcs/document-format-migrations.md @@ -2,7 +2,7 @@ A migration system for `.gdd` documents built around one rule: **history is always in the current shape**. A migration is a deterministic function over registry states. The runner applies it by replaying stored history and rewriting every delta into what it would have been had the author worked against the new shape, inserting deltas where the migration restructures the graph. Undo, time travel, replay, and deltas arriving from peers on an older build therefore never meet an outdated node shape, and the runtime never needs to execute one. -Migrations come in two tiers sharing that rule. **Format migrations** step serialized payloads across a `format_version` bump. **Node migrations** step one proto-node declaration from `identifier@version` to its successor on the typed `Registry`. Migrations are written as plain functions whose parameter types state what they read and write, live in independent crates that register themselves, and are ordered automatically. +Migrations come in two tiers sharing that rule. **Format migrations** step serialized payloads across a `format_version` bump. **Node migrations** step one declaration, a proto node or a built-in network definition, from `identifier@version` to its successor on the typed `Registry`. Migrations are written as plain functions whose parameter types state what they read and write, live in independent crates that register themselves, and are ordered automatically. # Motivation @@ -326,6 +326,33 @@ Cycles are rejected in CI, as are two migrations from the same declaration. Migr A node migration is pending when its source declaration is referenced anywhere in the document, *including history*. A node removed long ago still has its old shape stored in its `AddNode` and in the removal snapshot, and undo can bring it back. Pending format migrations come from `manifest.format_version`. +## Network definitions + +Built-in subgraphs such as Merge and Artboard aren't proto nodes. Each instance is a node whose `Implementation::Network` points at its own copy of a network from the editor's catalog. They migrate through the same tier, with the differences below. + +**Declarations.** `Declaration` carries a kind, `Proto` or `Network`. A network declaration is written `decl!(network "Merge"@1)`, and steps name it the same way: + +```rust +rename!(network "Artboard"@1 => @2); // Version step +rename!(network "Merge"@1 => "graphic_nodes::merge"@2); // Replacement by a proto node +``` + +A proto declaration's encoding leaves the kind out, so IDs derived from declarations written before network definitions existed stay the same. + +**Stored reference.** The network's `ui::reference` attribute names its definition as a `NetworkReference { identifier, version }`. Version 1 stays the bare identifier string it was before versions existed, so existing documents keep their bytes. Later versions store an object with both fields. One attribute rather than one per field keeps identifier and version under one LWW timestamp, so concurrent writes can't pair one peer's identifier with another's version, and pending detection matches the exact version. + +`DocumentNodeDefinition` declares the `version`. The editor writes the catalog's current version whenever it stores a reference, the way runtime conversion takes a proto node's version from `NODE_METADATA`. Opening a document migrates every instance to its definition's current version, so the editor never holds an older one in memory. + +**Anchors.** A node is an anchor of a network declaration when it implements a network whose reference names that declaration. `references` finds the declaration in `AddNetwork`, in `RemoveNetwork` snapshots, and in writes to `ui::reference`. + +**Switching.** The runner switches a network anchor to a network declaration by rewriting the reference. It switches one to a proto declaration by setting the implementation and removing the network the anchor implemented, with every node in it and every network nested in it. A proto anchor can't become a network declaration, and migrations only add proto nodes. + +Removing the network drops whatever it holds, including nodes the user added. This is a deliberate exception to totality, since the alternatives are worse. Reporting an edited subgraph as `unrepresentable` opens the document read-only, and keeping the edited copy usually doesn't compile anyway, since the nodes inside it typically folded into the new proto node. Built-in subgraphs are rarely edited, so the loss is rare. + +**Whole states.** An instance consists of two entities that history adds in separate deltas, and the editor's diff adds the network first. In between, the network names the definition without an anchor to migrate it, so `M` would leave the old reference in rewritten history, and every later open would find the migration pending again. Migrations from a network declaration therefore run on whole states only, like those reading `&Graph`. + +**Checks.** An editor test requires a registered migration leading to every network definition above version 1. The API dump doesn't cover network definitions yet. + ## Runner pipeline 1. **Format tier.** While `format_version` is below the current version, apply the step whose `migrates_from` matches (a gap is a hard error) to the registry, history records, and session, then bump the version. @@ -499,6 +526,8 @@ document/migrations/ **Truncate always.** Simple and always possible, but it discards undo history on every node upgrade and needs every peer to agree on the truncation point. +**Reference attribute vs. declaration resource for network definitions.** A content-addressed resource behind `Implementation::Network`, like `ProtoNode`, would let one resolver path cover both kinds. It changes the shape of `Implementation`, which needs a format step, and turns detaching an instance into a resource swap. A single attribute holding identifier and version gives the same atomicity and exact matching. + **Frozen mirrors vs. runtime types.** Input values are stored as self-describing `graph-storage::Value`s, so a migration decodes them into its own frozen mirror. Old runtime types therefore never need to stay in the runtime crates. # Unresolved questions @@ -511,6 +540,8 @@ document/migrations/ - **`unrepresentable` in CI.** Whether reaching it in the commutation test fails CI outright. - **Layout.** Whether migrations may write node positions and chain placement, or leave inserted nodes to a host-side layout pass. - **Multiple pending migrations.** Whether consecutive pending node migrations run as separate rewrite passes or are fused into one replay. +- **Migrations reading a subgraph.** A migration that inspects an instance's inner nodes depends on their versions, which change independently of the definition's. The planned answer is a cascading bump: the API dump lists a definition's inner `identifier@version`s, so bumping an inner node also requires bumping every definition containing it, and pins order that node's migrations around the definition's. Nothing reads a subgraph yet, so neither a read view for it nor the cascading bump exists. +- **Detaching.** Whether a migration may clear an edited instance's reference, keeping it as a custom subgraph, instead of collapsing it. # Future possibilities diff --git a/website/content/volunteer/guide/graphene/document-migrations.md b/website/content/volunteer/guide/graphene/document-migrations.md index 9c7f68840f..fd9baa7cdd 100644 --- a/website/content/volunteer/guide/graphene/document-migrations.md +++ b/website/content/volunteer/guide/graphene/document-migrations.md @@ -202,6 +202,24 @@ pub fn vary_from_style(node: &Node, target: &mut Target) { A wire written to a removed node brings that node back, so avoid switching a wire on and off depending on state. Keep the slot reading the same thing, and add nodes downstream of the anchor instead. +### Network definitions + +Some built-in nodes, like Merge and Artboard, are subgraphs. Each instance holds its own copy of a network defined in `document_node_definitions.rs`, and stores the definition's identifier and `version` next to it. Bump `version` on the `DocumentNodeDefinition` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix: + +```rust +rename!(network "Artboard"@1 => @2); +``` + +To replace a subgraph with a proto node, make the node the target. As with any replacement, the node has to be at `version + 1`: + +```rust +rename!(network "Merge"@1 => "graphic_nodes::merge"@2); +``` + +The runner removes the instance's network with every node in it, including nodes the user added, and keeps the instance's inputs. If the proto node's inputs are laid out differently, write a function with `#[migration(network "Merge"@1 => "graphic_nodes::merge"@2)]` and change them through `&mut Inputs`. A proto node can't become a network definition. + +An instance only exists once both its node and its network are in the document, so these migrations run on whole states, like the ones reading `&Graph`. + ### Asking the compiler Which node a migration inserts can depend on the type flowing through a wire, such as a flatten node restoring what a group erased. Such a migration goes in the `migration-compiled` crate, which links the node crates, and takes `Option<&dyn Compiler>`. It compares with `element_is`, which only compares `type_name`s within the running build, so no type name is ever stored, and removing a type breaks the build rather than changing the result: @@ -300,4 +318,4 @@ Leave corpus documents as they were added. They're there to prove that old files ## Current limits -A document whose history contains merges can't have that history rewritten, so migrating it restarts history from the migrated state and undo can't reach further back. Nodes generated by `#[derive(Destructure)]` can't be scaffolded, because they have no function of their own to carry a version. +A document whose history contains merges can't have that history rewritten, so migrating it restarts history from the migrated state and undo can't reach further back. Nodes generated by `#[derive(Destructure)]` can't be scaffolded, because they have no function of their own to carry a version. `cargo run migration check` doesn't see network definitions yet, so an editor test catches a bumped `version` without a migration instead, and `cargo run migration new` can't scaffold one.