Compare commits

..
Author SHA1 Message Date
Dennis Kobert 40a9600f03 Fix swapped legacy aliases of the logic nodes 2026-11-15 23:40:11 +01:00
Dennis Kobert dc1856a5a7 Show the matched old name in the node catalog with the typed part highlighted 2026-11-15 23:39:56 +01:00
Dennis Kobert fb9f48e7db Find nodes in the catalog search by their names from before migrations 2026-11-15 22:52:09 +01:00
Dennis Kobert 48ff126082 Add a generic observation mechanism to the node runtime (#4961)
Add a keyed observation mechanism to the node runtime and move the Data panel onto it
2026-11-15 21:36:14 +01:00
Dennis KobertandKeavon Chambers 47cc1c462d Extend document migrations to built-in subgraph nodes like 'Merge' (#4949)
* Support migrating built-in network definitions like proto nodes

* Reject added network definitions and fix review findings

* Fix the migration check failing on steps that name a network definition

---------

Co-authored-by: Keavon Chambers <[email protected]>
2026-11-14 17:19:18 -08:00
42 changed files with 1357 additions and 676 deletions

No files matched your search

@@ -26,8 +26,8 @@ env:
CARGO_TERM_COLOR: always
# The four benchmarks, built and run by one `cargo bench` call so their slow thin-LTO links happen in parallel
BENCHMARKS: --bench compile_demo_art_gungraun --bench update_executor_gungraun --bench run_once_gungraun --bench run_cached_gungraun
# The benchmarks in `node-graph/interpreted-executor/benches` that render on the GPU, built with its `gpu` feature in a call of their own so the others build as before
GPU_BENCHMARKS: brush_stroke_gungraun artwork_gungraun
# The brush benchmark, which needs the GPU nodes and so gets its own call rather than changing what the others build
BRUSH_BENCHMARK: -p interpreted-executor --features gpu --bench brush_stroke_gungraun
jobs:
profile:
@@ -57,7 +57,7 @@ jobs:
- name: Install lavapipe
run: |
# The runners have no GPU, so the GPU benchmarks render on Mesa's software Vulkan device
# The runners have no GPU, so the brush benchmark renders on Mesa's software Vulkan device
sudo apt-get update
sudo apt-get install -y mesa-vulkan-drivers
# Mesa releases name the ICD with or without the architecture (`lvp_icd.x86_64.json` or `lvp_icd.json`), so ask the package where it put it
@@ -87,9 +87,10 @@ jobs:
run: |
cargo bench $BENCHMARKS -- --save-baseline=master
# A PR adding a GPU benchmark is measured against a baseline commit that predates it
gpu_benchmarks=$(for benchmark in $GPU_BENCHMARKS; do if [ -f "node-graph/interpreted-executor/benches/$benchmark.rs" ]; then echo "--bench $benchmark"; fi; done)
if [ -n "$gpu_benchmarks" ]; then cargo bench -p interpreted-executor --features gpu $gpu_benchmarks -- --save-baseline=master; fi
# Until the brush benchmark reaches master, a baseline commit may predate it
if [ -f node-graph/interpreted-executor/benches/brush_stroke_gungraun.rs ]; then
cargo bench $BRUSH_BENCHMARK -- --save-baseline=master
fi
# Saved before the PR benchmarks run, since they write their own results into the same folder
- name: Save benchmark baseline
@@ -108,31 +109,23 @@ jobs:
# Unlike the default, this sets `pipefail`, so a failed benchmark fails the step rather than leaving its results empty
shell: bash
run: |
# A GPU benchmark has nothing to compare against until the baseline commit has it
baselined=$(for benchmark in $GPU_BENCHMARKS; do if git cat-file -e "HEAD^1:node-graph/interpreted-executor/benches/$benchmark.rs" 2>/dev/null; then echo "$benchmark"; fi; done)
gpu_benchmarks=$(for benchmark in $baselined; do echo "--bench $benchmark"; done)
# The brush benchmark has nothing to compare against until the baseline commit has it
git cat-file -e HEAD^1:node-graph/interpreted-executor/benches/brush_stroke_gungraun.rs 2>/dev/null && brush=true || brush=false
{
cargo bench $BENCHMARKS -- --baseline=master --output-format=json
if [ -n "$gpu_benchmarks" ]; then cargo bench -p interpreted-executor --features gpu $gpu_benchmarks -- --baseline=master --output-format=json; fi
if $brush; then cargo bench $BRUSH_BENCHMARK -- --baseline=master --output-format=json; fi
} | jq -sc | sed 's/\\"//g' > /tmp/all_output.json
# Split the results into one file per benchmark, or per function of one, for the analysis below
split_results() { jq -c --arg path "$1" '[.[] | select(.module_path == $path or (.module_path | startswith($path + "::")))]' /tmp/all_output.json > "/tmp/$2_output.json"; }
# Split the results into one file per benchmark for the analysis below
split_results() { jq -c --arg prefix "$1::" '[.[] | select(.module_path | startswith($prefix))]' /tmp/all_output.json > "/tmp/$2_output.json"; }
split_results compile_demo_art_gungraun compile
split_results update_executor_gungraun update
split_results run_once_gungraun run_once
split_results run_cached_gungraun run_cached
for benchmark in $baselined; do
case $benchmark in
# Its edits and zooms take different render paths, so each gets a section of its own
artwork_gungraun)
split_results artwork_gungraun::artwork_group::add_rectangle artwork_edit
split_results artwork_gungraun::artwork_group::zoom artwork_zoom
;;
*) split_results "$benchmark" "$benchmark" ;;
esac
done
if $brush; then
split_results brush_stroke_gungraun brush_stroke
fi
- name: Make old comments collapsed by default
# Only run if we have write permissions (not a fork)
@@ -185,22 +178,18 @@ jobs:
return benchmark.profiles?.find((profile) => profile.tool === 'Callgrind')?.data?.total?.metrics;
}
// A GPU benchmark only has results once the baseline commit has it too
const gpuBenchmarks = [
['brush_stroke_gungraun', 'Brush Strokes'],
['artwork_edit', 'Artwork Edit'],
['artwork_zoom', 'Zoom'],
].filter(([name]) => fs.existsSync(`/tmp/${name}_output.json`));
// The brush benchmark only has results once the baseline commit has it too
const brush = fs.existsSync('/tmp/brush_stroke_output.json');
const allOutputs = [
JSON.parse(fs.readFileSync('/tmp/compile_output.json', 'utf8')),
JSON.parse(fs.readFileSync('/tmp/update_output.json', 'utf8')),
JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8')),
JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8')),
...gpuBenchmarks.map(([name]) => JSON.parse(fs.readFileSync(`/tmp/${name}_output.json`, 'utf8')))
...(brush ? [JSON.parse(fs.readFileSync('/tmp/brush_stroke_output.json', 'utf8'))] : [])
];
const outputNames = ['compile', 'update', 'run_once', 'run_cached', ...gpuBenchmarks.map(([name]) => name)];
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution', ...gpuBenchmarks.map(([, title]) => title)];
const outputNames = ['compile', 'update', 'run_once', 'run_cached', ...(brush ? ['brush_stroke'] : [])];
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution', ...(brush ? ['Brush Stroke'] : [])];
// Fail instead of reporting no changes when a benchmark has no baseline comparison, such as after gungraun changes its output format
const missingComparisons = [];
@@ -263,11 +252,9 @@ jobs:
const updateOutput = JSON.parse(fs.readFileSync('/tmp/update_output.json', 'utf8'));
const runOnceOutput = JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8'));
const runCachedOutput = JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8'));
// A GPU benchmark only has results once the baseline commit has it too, and a section without results is left out
// The brush benchmark only has results once the baseline commit has it too, and a section without results is left out
const readOptional = (path) => (fs.existsSync(path) ? JSON.parse(fs.readFileSync(path, 'utf8')) : []);
const brushStrokeOutput = readOptional('/tmp/brush_stroke_gungraun_output.json');
const artworkEditOutput = readOptional('/tmp/artwork_edit_output.json');
const artworkZoomOutput = readOptional('/tmp/artwork_zoom_output.json');
const brushStrokeOutput = readOptional('/tmp/brush_stroke_output.json');
const hasSignificantChanges = '${{ steps.analyze.outputs.has-significant-changes }}' === 'true';
let commentBody = "";
@@ -357,9 +344,7 @@ jobs:
{ output: updateOutput, title: "🔄 Executor Update" },
{ output: runOnceOutput, title: "🚀 Render: Cold Execution" },
{ output: runCachedOutput, title: "⚡ Render: Cached Execution" },
{ output: brushStrokeOutput, title: "🖌️ Render: Brush Strokes" },
{ output: artworkEditOutput, title: "✏️ Render: Artwork Edit" },
{ output: artworkZoomOutput, title: "🔍 Render: Zoom" }
{ output: brushStrokeOutput, title: "🖌️ Render: Brush Strokes" }
];
// Generate sections and determine which ones have results
Generated
+2
View File
@@ -2846,6 +2846,7 @@ dependencies = [
"bitflags 2.13.2",
"blake3",
"color",
"convert_case 0.12.0",
"core-types",
"derivative",
"document-container",
@@ -2866,6 +2867,7 @@ dependencies = [
"log",
"math-parser",
"migration-compiled",
"migration-core",
"migration-formats",
"migration-nodes",
"node-macro",
@@ -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";
}
}
+1 -1
View File
@@ -491,7 +491,7 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
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)?;
+2
View File
@@ -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;
@@ -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<NetworkReference> {
None
}
@@ -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<Self> {
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<Self> {
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()));
}
}
@@ -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<crate::NetworkReference> {
(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"]);
}
}
+2 -2
View File
@@ -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),
+62 -5
View File
@@ -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)
};
+2 -2
View File
@@ -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)]
+11 -3
View File
@@ -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<Declaration> {
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.
+16 -3
View File
@@ -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<TokenStream2> {
}
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.
+27 -6
View File
@@ -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<Self> {
let network = parse_network_keyword(input)?;
let identifier: LitStr = input.parse()?;
input.parse::<Token![@]>()?;
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<bool> {
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::<Token![=>]>()?;
let target_identifier = match input.peek(LitStr) {
true => input.parse::<LitStr>()?.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::<LitStr>()?.value(), network)
}
false => (source.identifier.clone(), source.network),
};
input.parse::<Token![@]>()?;
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 })
}
+4
View File
@@ -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")]
+79 -8
View File
@@ -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<NodeId> = 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<Rev>) -> Result<Registry, Runn
Ok(registry)
}
/// A network definition's instance is a node and the network it implements, which a history adds in separate deltas. In between, the network
/// names the definition without an anchor to migrate it, so only states where both or neither exist are migrated.
pub(crate) fn needs_whole_states(migration: &dyn NodeMigration) -> 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(_))
+19 -2
View File
@@ -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());
+128 -22
View File
@@ -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<NodeInput>) -> 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<NodeInput>) -> 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<NodeInput>) -> (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<NodeInput>) -> 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<RegistryDelta>) {
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<Declaration> {
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<NodeId> {
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<NodeId>) -> NodeInput {
fn declaration_of(&self, node: &Node) -> Option<Declaration> {
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<NodeId>, 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(&registry.node_instances[node]) != Some(self.source);
let candidates: Vec<NodeId> = self.live_nodes().into_iter().filter(|node| Some(*node) != exclude && allowed(node)).collect();
let candidates: Vec<NodeId> = 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}"));
@@ -1,6 +1,7 @@
mod blobs;
mod compiler;
mod examples;
mod networks;
mod registration;
mod rewrite;
@@ -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));
}
@@ -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),
+55 -7
View File
@@ -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<Self> {
let source_network = parse_network_keyword(input)?;
let identifier: syn::LitStr = input.parse()?;
input.parse::<syn::Token![@]>()?;
let version: syn::LitInt = input.parse()?;
input.parse::<syn::Token![=>]>()?;
let target_identifier = if input.peek(syn::LitStr) { input.parse::<syn::LitStr>()?.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::<syn::LitStr>()?.value(), network)
} else {
(identifier.value(), source_network)
};
input.parse::<syn::Token![@]>()?;
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<bool> {
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<Vec<MigrationStep>, 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::<MigrationStep>(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)];
+2
View File
@@ -26,6 +26,7 @@ document-format = { workspace = true, features = ["migrations", "network"] }
migration-formats = { workspace = true }
migration-compiled = { workspace = true }
migration-nodes = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
document-graph-storage = { workspace = true, features = ["conversion"] }
document-container = { workspace = true }
peer-transport = { workspace = true }
@@ -49,6 +50,7 @@ kurbo = { workspace = true }
futures = { workspace = true }
glam = { workspace = true }
derivative = { workspace = true }
convert_case = { workspace = true }
tsify = { workspace = true }
dyn-any = { workspace = true }
num_enum = { workspace = true }
@@ -65,9 +65,9 @@ const DEFAULT_ROWS_IN_VIEW: Range<usize> = 0..100;
impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanelMessageHandler {
fn process_message(&mut self, message: DataPanelMessage, responses: &mut VecDeque<Message>, context: DataPanelMessageContext) {
match message {
DataPanelMessage::UpdateLayout { mut inspect_result } => {
self.introspected_data = inspect_result.take_data();
self.introspected_node_path = inspect_result.inspect_node_path;
DataPanelMessage::UpdateLayout { inspect_result } => {
self.introspected_data = inspect_result.data;
self.introspected_node_path = inspect_result.node_path;
self.context = inspect_result.context;
self.update_layout(responses, context);
}
@@ -8,9 +8,11 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
};
use crate::messages::portfolio::document_migration::legacy_aliases;
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
use crate::node_graph_executor::NodeGraphExecutor;
use convert_case::{Boundary, Case, Casing};
use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::*;
@@ -21,6 +23,7 @@ use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color,
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::*;
use migration_core::{DeclarationKind, NodeMigration};
use std::collections::{HashMap, VecDeque};
pub struct NodeInspectorContext<'a> {
@@ -124,6 +127,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 +161,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
let custom = vec![
DocumentNodeDefinition {
identifier: "Custom Node",
version: 1,
category: "Routing",
icon: Some("NodeCustomNode"),
node_template: NodeTemplate {
@@ -165,6 +173,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Merge",
version: 1,
category: "Graphic",
icon: Some("NodeMerge"),
node_template: NodeTemplate {
@@ -233,6 +242,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Artboard",
version: 1,
category: "Graphic",
icon: Some("NodeArtboard"),
node_template: NodeTemplate {
@@ -333,6 +343,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Blend",
version: 1,
category: "Vector: Deform",
icon: Some("NodeBlend"),
node_template: NodeTemplate {
@@ -517,6 +528,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Origins to Polyline",
version: 1,
category: "Vector: Path",
icon: Some("NodeOriginsToPolyline"),
node_template: NodeTemplate {
@@ -598,6 +610,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Load Image",
version: 1,
category: "Data: I/O",
icon: Some("NodeLoadImage"),
node_template: NodeTemplate {
@@ -638,6 +651,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
#[cfg(feature = "gpu")]
DocumentNodeDefinition {
identifier: "Rasterize",
version: 1,
category: "Raster",
icon: Some("NodeRasterize"),
node_template: NodeTemplate {
@@ -666,6 +680,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Extract",
version: 1,
category: "",
icon: None,
node_template: NodeTemplate {
@@ -681,6 +696,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Regex Find",
version: 1,
category: "String: Regex",
icon: Some("NodeRegexFind"),
node_template: NodeTemplate {
@@ -758,6 +774,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNodeDefinition {
identifier: "Path",
version: 1,
category: "Vector: Geometry",
icon: Some("NodePath"),
node_template: NodeTemplate {
@@ -1470,6 +1487,11 @@ pub fn resolve_document_node_type(identifier: &DefinitionIdentifier) -> 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 {
@@ -1601,6 +1623,8 @@ impl InputTypeConstraint {
/// The node catalog's entries, ordered by category and then by name.
pub fn collect_node_types() -> Vec<FrontendNodeType> {
let migrations = migration_core::registered_migrations();
let mut node_types: Vec<FrontendNodeType> = DOCUMENT_NODE_TYPES
.iter()
// A Passthrough is placed as a redirect dot on a wire, so it isn't offered as a node
@@ -1614,6 +1638,7 @@ pub fn collect_node_types() -> Vec<FrontendNodeType> {
FrontendNodeType {
identifier: identifier.serialized(),
input_types: InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, &name),
search_aliases: former_names(identifier, &name, &migrations),
name,
category: definition.category.to_string(),
}
@@ -1628,6 +1653,51 @@ pub fn collect_node_types() -> Vec<FrontendNodeType> {
node_types
}
/// The display names of every declaration that migrates, directly or through others, to the node of `identifier`, and of its legacy aliases.
fn former_names(identifier: &DefinitionIdentifier, current_name: &str, migrations: &[&'static dyn NodeMigration]) -> Vec<String> {
let (current, legacy_aliases): (_, Vec<&str>) = match identifier {
DefinitionIdentifier::ProtoNode(proto_node_identifier) => ((proto_node_identifier.as_str(), DeclarationKind::Proto), legacy_aliases(proto_node_identifier).collect()),
DefinitionIdentifier::Network(name) => ((name.as_str(), DeclarationKind::Network), Vec::new()),
};
let mut visited = vec![current];
let mut pending = vec![current];
while let Some((identifier, kind)) = pending.pop() {
for migration in migrations {
let (source, target) = (migration.source(), migration.target());
let predecessor = (source.identifier, source.kind);
if target.identifier == identifier && target.kind == kind && !visited.contains(&predecessor) {
visited.push(predecessor);
pending.push(predecessor);
}
}
}
let mut names: Vec<String> = visited
.into_iter()
.skip(1)
.chain(legacy_aliases.into_iter().map(|alias| (alias, DeclarationKind::Proto)))
.map(|(identifier, kind)| declaration_display_name(identifier, kind))
.filter(|name| !name.eq_ignore_ascii_case(current_name))
.collect();
names.sort();
names.dedup();
names
}
/// A network definition's identifier is its display name, and a proto node's is approximated from its type name, like `MathFxNode` becoming "Math Fx".
fn declaration_display_name(identifier: &str, kind: DeclarationKind) -> String {
match kind {
DeclarationKind::Network => identifier.to_string(),
DeclarationKind::Proto => {
let type_name = identifier.rsplit("::").next().unwrap_or(identifier);
let name = type_name.strip_suffix("Node").unwrap_or(type_name);
name.set_boundaries(&[Boundary::LowerUpper, Boundary::DigitUpper, Boundary::Acronym]).to_case(Case::Title)
}
}
}
pub fn collect_node_descriptions() -> Vec<(String, String)> {
DOCUMENT_NODE_TYPES
.iter()
@@ -1679,7 +1749,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 +1825,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)]
@@ -43,6 +43,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
description,
inspector,
output_fields,
version,
..
} = metadata;
@@ -85,6 +86,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
identifier,
DocumentNodeDefinition {
identifier: display_name,
version: *version,
node_template: NodeTemplate {
inputs,
call_argument: input_type.clone(),
@@ -120,6 +120,9 @@ pub struct FrontendNodeType {
pub category: String,
#[serde(rename = "inputTypes")]
pub input_types: Vec<InputTypeConstraint>,
/// Names the node went by before migrations replaced it, which the catalog search also matches.
#[serde(rename = "searchAliases")]
pub search_aliases: Vec<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -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();
@@ -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<NetworkReference> {
let identifier = self.network_persistent(network)?.reference.clone()?;
Some(versioned_reference(identifier))
}
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
@@ -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 {
@@ -55,6 +55,14 @@ fn into_group_aliases() -> impl Iterator<Item = &'static &'static str> {
.flat_map(|replacement| replacement.aliases)
}
/// The identifiers and display names that legacy documents use for `node`.
pub fn legacy_aliases(node: &ProtoNodeIdentifier) -> impl Iterator<Item = &'static str> + '_ {
NODE_REPLACEMENTS
.iter()
.filter(move |replacement| replacement.node == *node)
.flat_map(|replacement| replacement.aliases.iter().copied())
}
/// Clears a migrated node's stored display name if it was only the replaced node's default name, so it shows its new node's name instead.
fn reset_default_display_name(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], old_default_name: &str) {
if document.network_interface.display_name(node_id, network_path) == old_default_name {
@@ -353,8 +361,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::logical_and::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalAndNode",
"graphene_core::ops::LogicNotNode",
"graphene_core::logic::LogicNotNode",
"graphene_core::ops::LogicAndNode",
"graphene_core::logic::LogicAndNode",
"graphene_math_nodes::LogicalAndNode",
],
},
@@ -362,8 +370,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::logical_not::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalNotNode",
"graphene_core::ops::LogicOrNode",
"graphene_core::logic::LogicOrNode",
"graphene_core::ops::LogicNotNode",
"graphene_core::logic::LogicNotNode",
"graphene_math_nodes::LogicalNotNode",
],
},
@@ -371,8 +379,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::logical_or::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalOrNode",
"graphene_core::ops::LogicAndNode",
"graphene_core::logic::LogicAndNode",
"graphene_core::ops::LogicOrNode",
"graphene_core::logic::LogicOrNode",
"graphene_math_nodes::LogicalOrNode",
],
},
@@ -1933,8 +1941,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
&& inner.nodes.values().any(|n| {
matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::floor::IDENTIFIER)
&& n.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. }))
})
&& let Some(node_definition) = resolve_network_node_type("Blend")
}) && let Some(node_definition) = resolve_network_node_type("Blend")
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
@@ -1946,8 +1953,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
n.inputs
.iter()
.any(|input| matches!(input, NodeInput::Import { import_type, import_index: 2 } if *import_type == item!(f64)))
})
&& let Some(node_definition) = resolve_network_node_type("Regex Find")
}) && let Some(node_definition) = resolve_network_node_type("Regex Find")
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
+86 -25
View File
@@ -15,7 +15,7 @@ use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, Graphic};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -39,8 +39,18 @@ pub struct ExecutionResponse {
/// The layers whose thumbnails the runtime let go of, which it renders anew if they have content to show again.
dropped_thumbnails: Vec<NodeId>,
vector_modify: HashMap<NodeId, VectorGeometry>,
/// The resulting value from the temporary inspected during execution
inspect_result: Option<InspectResult>,
/// The latest result of each observation.
observations: HashMap<ObservationKey, InspectResult>,
}
/// Names an observation so it can be changed or stopped without touching the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
}
#[derive(Debug)]
@@ -81,9 +91,16 @@ pub enum NodeGraphUpdate {
ExecutionResponse(Box<ExecutionResponse>),
CompilationResponse(CompilationResponse),
EyedropperPreview(Raster<CPU>),
Thumbnails { responses: VecDeque<FrontendMessage>, document_id: DocumentId },
InspectResult(Box<InspectResult>),
ClipboardSvg { id: u64, svg: Option<String> },
Thumbnails {
responses: VecDeque<FrontendMessage>,
document_id: DocumentId,
},
/// The latest result of each observation, sent outside an execution after one of them changed.
Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg {
id: u64,
svg: Option<String>,
},
}
#[derive(Debug)]
@@ -98,6 +115,8 @@ pub struct NodeGraphExecutor {
node_graph_document: Option<DocumentId>,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
previous_node_to_inspect: Vec<NodeId>,
/// The context overrides the Data panel evaluates its inspected node with, reset when another node is inspected.
inspect_context_overrides: ContextOverrides,
/// The canvas images the frontend holds, so a render sends only those it lacks.
canvas_images_sent: HashSet<u64>,
/// Evaluation errors of the last evaluation, used in tests
@@ -152,6 +171,7 @@ impl NodeGraphExecutor {
node_graph_hash: 0,
node_graph_document: None,
previous_node_to_inspect: Vec::new(),
inspect_context_overrides: ContextOverrides::default(),
canvas_images_sent: HashSet::new(),
#[cfg(test)]
evaluation_errors: None,
@@ -188,8 +208,16 @@ impl NodeGraphExecutor {
execution_id
}
pub fn submit_inspect_context_overrides(&self, overrides: graphene_std::ContextOverrides) {
self.sender.send(GraphRuntimeRequest::InspectContextOverrides(overrides)).expect("Failed to send the context overrides");
pub fn submit_inspect_context_overrides(&mut self, overrides: ContextOverrides) {
self.inspect_context_overrides = overrides;
let Some(observation) = self.data_panel_observation() else { return };
self.sender
.send(GraphRuntimeRequest::Observe {
key: ObservationKey::DataPanel,
observation: Some(observation),
})
.expect("Failed to send the context overrides");
}
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
@@ -228,9 +256,9 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::new(),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
@@ -238,12 +266,17 @@ impl NodeGraphExecutor {
/// Update the cached network if necessary.
fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> {
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
if inspected_node_changed {
self.previous_node_to_inspect = node_to_inspect;
self.inspect_context_overrides = ContextOverrides::default();
}
let network_hash = document.network_interface.network_hash();
if network_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
let network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes();
let layers = document.network_interface.layer_paths();
self.previous_node_to_inspect.clone_from(&node_to_inspect);
self.node_graph_hash = network_hash;
self.node_graph_document = Some(document_id);
@@ -253,19 +286,38 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect,
previewed,
layers,
observations: self.observations(),
}))
.map_err(|e| e.to_string())?;
} else if self.previous_node_to_inspect != node_to_inspect {
self.previous_node_to_inspect.clone_from(&node_to_inspect);
self.sender.send(GraphRuntimeRequest::Inspect(node_to_inspect)).map_err(|e| e.to_string())?;
} else if inspected_node_changed {
let observation = self.data_panel_observation();
self.sender
.send(GraphRuntimeRequest::Observe {
key: ObservationKey::DataPanel,
observation,
})
.map_err(|e| e.to_string())?;
}
Ok(())
}
/// What the Data panel reads back, if it inspects a node.
fn data_panel_observation(&self) -> Option<Observation> {
(!self.previous_node_to_inspect.is_empty()).then(|| Observation {
node_path: self.previous_node_to_inspect.clone(),
connector: ObservedConnector::Output,
overrides: self.inspect_context_overrides.clone(),
})
}
/// Every observation a graph update of the document starts with.
fn observations(&self) -> HashMap<ObservationKey, Observation> {
self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation)).into_iter().collect()
}
/// Adds an evaluate request for whatever current network is cached.
pub(crate) fn submit_current_node_graph_evaluation(
&mut self,
@@ -429,9 +481,9 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
@@ -467,7 +519,7 @@ impl NodeGraphExecutor {
responses: existing_responses,
dropped_thumbnails,
vector_modify,
inspect_result,
mut observations,
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -503,7 +555,8 @@ impl NodeGraphExecutor {
// Apply only to the active document's in-progress migration, dropping responses left over from a document switch.
if let Some(bake_target) = execution_context.measure_fill {
if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) {
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(inspect_result).flatten();
let measured = observations.remove(&ObservationKey::FillMeasurement);
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(measured).flatten();
self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses);
}
continue;
@@ -605,6 +658,7 @@ impl NodeGraphExecutor {
});
// Update the Data panel on the frontend using the value of the inspect result.
let inspect_result = observations.remove(&ObservationKey::DataPanel);
if let Some(inspect_result) = (!self.previous_node_to_inspect.is_empty()).then_some(inspect_result).flatten() {
responses.add(DataPanelMessage::UpdateLayout {
inspect_result: Box::new(inspect_result),
@@ -661,9 +715,13 @@ impl NodeGraphExecutor {
let (data, width, height) = raster.to_flat_u8();
responses.add(EyedropperToolMessage::PreviewImage { data, width, height });
}
NodeGraphUpdate::InspectResult(inspect_result) => {
if inspect_result.inspect_node_path == self.previous_node_to_inspect {
responses.add(DataPanelMessage::UpdateLayout { inspect_result });
NodeGraphUpdate::Observations(mut observations) => {
if let Some(inspect_result) = observations.remove(&ObservationKey::DataPanel)
&& inspect_result.node_path == self.previous_node_to_inspect
{
responses.add(DataPanelMessage::UpdateLayout {
inspect_result: Box::new(inspect_result),
});
}
}
NodeGraphUpdate::Thumbnails {
@@ -789,14 +847,19 @@ impl NodeGraphExecutor {
}
let resources = document.resources.registry.clone();
let fill_measurement = Observation {
node_path: full_path,
connector: ObservedConnector::Output,
overrides: ContextOverrides::default(),
};
if self
.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: full_path.clone(),
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
}))
.is_err()
{
@@ -807,7 +870,6 @@ impl NodeGraphExecutor {
// Force the next normal render to recompile and re-send the real, non-redirected network
self.node_graph_hash = 0;
self.previous_node_to_inspect = full_path;
let viewport = Footprint {
transform: document.metadata().document_to_viewport,
@@ -858,7 +920,7 @@ impl NodeGraphExecutor {
return;
}
match inspect_result.and_then(|mut result| result.take_data()).and_then(|data| measure_fill_geometry(&data)) {
match inspect_result.and_then(|result| result.data).and_then(|data| measure_fill_geometry(&data)) {
Some((bounding_box, item_transform)) => {
// Skip the bake if the user already placed this gradient themselves, but drop the now-superseded entry either way
if fill_transform_unbaked(document, &network_path, fill_node_id) {
@@ -904,10 +966,9 @@ impl NodeGraphExecutor {
}
// TODO: Eventually remove this document upgrade code
/// Tear down the in-progress migration and clear the stale inspect target and hash so the next normal render recompiles the real network.
/// Tear down the in-progress migration and clear the hash so the next normal render recompiles the real network.
fn cancel_gradient_migration(&mut self) {
self.gradient_migration = None;
self.previous_node_to_inspect = Vec::new();
self.node_graph_hash = 0;
}
+42 -157
View File
@@ -2,7 +2,7 @@ use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
use crate::task::{Spawn, Spawner, Task};
use glam::{DVec2, UVec2};
use glam::UVec2;
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
@@ -20,14 +20,17 @@ use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
use graphene_std::{Context, ContextFeatures, ContextOverrides, NodeError, OwnedContextImpl, Poll};
use graphene_std::{Context, NodeError, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use observer::Observer;
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use thumbnails::Thumbnails;
mod observer;
mod thumbnails;
/// Persistent data between graph executions. It's updated via message passing from the editor thread with [`GraphRuntimeRequest`]`.
@@ -56,9 +59,9 @@ pub struct NodeRuntime {
node_graph_warnings: GraphErrors,
monitor_nodes: Vec<(Vec<NodeId>, NodeId)>,
thumbnails: Thumbnails,
/// The node the Data panel inspects.
inspect_state: Option<InspectState>,
observer: Observer<ObservationKey>,
/// Whether an observation changed since its results were last sent.
observations_changed: bool,
preprocessor: preprocessor::Preprocessor,
@@ -78,22 +81,31 @@ pub struct NodeRuntime {
pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest),
ThumbnailsInView { layers: HashSet<NodeId>, document_id: DocumentId },
Inspect(Vec<NodeId>),
InspectContextOverrides(ContextOverrides),
ClipboardSvg { id: u64, layers: Vec<NodeId> },
ThumbnailsInView {
layers: HashSet<NodeId>,
document_id: DocumentId,
},
/// Starts, changes, or with `None` stops one observation without a graph update.
Observe {
key: ObservationKey,
observation: Option<Observation>,
},
ClipboardSvg {
id: u64,
layers: Vec<NodeId>,
},
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GraphUpdate {
pub(super) network: NodeNetwork,
pub(super) resources: ResourceRegistry,
/// Full path from the root network to the node the Data panel inspects.
pub(super) node_to_inspect: Vec<NodeId>,
/// The node each network renders in place of its export, paired with that network's path.
pub(super) previewed: Vec<(Vec<NodeId>, RootNode)>,
/// Full path from the root network to every layer, which are the nodes with thumbnails.
pub(super) layers: Vec<Vec<NodeId>>,
/// The connectors whose values are sent back after each evaluation, replacing those observed before.
pub(super) observations: HashMap<ObservationKey, Observation>,
}
/// Replaces each network's primary export with its previewed node.
@@ -145,12 +157,13 @@ impl NodeRuntime {
node_graph_warnings: Vec::new(),
monitor_nodes: Vec::new(),
thumbnails: Thumbnails::new(),
observer: Observer::default(),
observations_changed: false,
preprocessor: preprocessor::Preprocessor::new(),
vector_modify: Default::default(),
vector_evaluations: Default::default(),
inspect_state: None,
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(),
#[cfg(all(target_family = "wasm", feature = "gpu"))]
@@ -181,17 +194,15 @@ impl NodeRuntime {
self.thumbnails.set_in_view(layers);
self.pending_thumbnails = Some(document_id);
}
// A graph update applied after this loop would otherwise inspect what was selected before
GraphRuntimeRequest::Inspect(node_to_inspect) => match &mut graph {
Some(update) => update.node_to_inspect = node_to_inspect,
None => self.inspect_state = InspectState::new(node_to_inspect),
},
GraphRuntimeRequest::InspectContextOverrides(overrides) => {
if let Some(inspect_state) = &mut self.inspect_state {
inspect_state.overrides = overrides;
inspect_state.overrides_changed = true;
// A graph update applied after this loop would otherwise replace this with what it observed before
GraphRuntimeRequest::Observe { key, observation } => match (&mut graph, observation) {
(Some(update), Some(observation)) => _ = update.observations.insert(key, observation),
(Some(update), None) => _ = update.observations.remove(&key),
(None, observation) => {
self.observer.set(key, observation);
self.observations_changed = true;
}
}
},
GraphRuntimeRequest::ClipboardSvg { id, layers } => {
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
@@ -202,21 +213,16 @@ impl NodeRuntime {
let Some(GraphUpdate {
mut network,
resources,
node_to_inspect,
previewed,
layers,
observations,
}) = graph
else {
return;
};
apply_previews(&mut network, &previewed);
match &mut self.inspect_state {
Some(inspect_state) if inspect_state.inspect_node_path == node_to_inspect => inspect_state.last_evaluation = None,
_ => self.inspect_state = InspectState::new(node_to_inspect),
}
self.observer.replace_all(observations);
self.resources = resources;
self.node_graph_errors.clear();
@@ -259,12 +265,9 @@ impl NodeRuntime {
}
}
if let Some(inspect_state) = &mut self.inspect_state
&& std::mem::take(&mut inspect_state.overrides_changed)
&& viewport.is_none()
{
let inspect_result = inspect_state.access(&self.executor, self.old_graph.as_ref());
self.sender.send(NodeGraphUpdate::InspectResult(Box::new(inspect_result))).expect("Failed to send response");
if std::mem::take(&mut self.observations_changed) && viewport.is_none() {
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response");
}
if let Some(eyedropper) = self.pending_eyedropper.take() {
@@ -374,7 +377,7 @@ impl NodeRuntime {
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
vector_modify: HashMap::new(),
inspect_result: None,
observations: HashMap::new(),
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None;
@@ -386,7 +389,7 @@ impl NodeRuntime {
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) {
let mut responses = VecDeque::new();
let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await;
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor, self.old_graph.as_ref()));
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
let response = ExecutionResponse {
execution_id,
@@ -394,7 +397,7 @@ impl NodeRuntime {
responses,
dropped_thumbnails,
vector_modify: self.vector_modify.clone(),
inspect_result,
observations,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
@@ -523,23 +526,6 @@ fn records_vector(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> b
.is_ok_and(|data| data.is::<IORecord<Context, List<Vector>>>() || data.is::<IORecord<Context, Item<Vector>>>())
}
fn context_features(context: &OwnedContextImpl) -> InspectedContext {
use graphene_std::{ExtractAnimationTime, ExtractFootprint, ExtractIndex, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs};
InspectedContext {
features: ContextOverrides {
footprint: context.try_footprint().copied(),
real_time: context.try_real_time(),
animation_time: context.try_animation_time(),
pointer_position: context.try_pointer_position(),
index: context.try_index().map(|index| index.collect()),
},
positions: context.try_position().map(|positions| positions.collect()).unwrap_or_default(),
variables: context.varargs_len().unwrap_or_default(),
..Default::default()
}
}
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
match poll {
Poll::Final(output) | Poll::Partial(output) => Some(output),
@@ -594,112 +580,11 @@ impl Spawn for NodeTaskExecutor {
}
}
/// The node the Data panel inspects, which is evaluated again from the context it was last evaluated with.
struct InspectState {
inspect_node_path: Vec<NodeId>,
overrides: ContextOverrides,
last_evaluation: Option<(NodeId, u64, Option<InspectedData>)>,
overrides_changed: bool,
}
type InspectedData = Arc<dyn std::any::Any + Send + Sync + 'static>;
/// The resulting value from the temporary inspected during execution
#[derive(Clone, Debug, Default)]
pub struct InspectResult {
introspected_data: Option<Arc<dyn std::any::Any + Send + Sync + 'static>>,
/// Full path from the root network to the inspected node, with the node itself as the last element.
/// The parent slice (`split_last().1`) is the network the node lives in, which downstream consumers
/// (e.g. the Data panel) need when looking the node up via `network_interface.is_layer(...)` etc.
pub inspect_node_path: Vec<NodeId>,
pub context: InspectedContext,
}
/// The features of the context an inspected node was evaluated with, after the overrides replaced some of them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InspectedContext {
pub features: ContextOverrides,
/// The positions the context carries, from the outermost level in.
pub positions: Vec<DVec2>,
pub variables: usize,
pub overrides: ContextOverrides,
pub dependencies: ContextFeatures,
}
impl InspectResult {
pub fn take_data(&mut self) -> Option<Arc<dyn std::any::Any + Send + Sync + 'static>> {
self.introspected_data.clone()
}
}
// This is very ugly but is required to be inside a message
impl PartialEq for InspectResult {
fn eq(&self, other: &Self) -> bool {
self.inspect_node_path == other.inspect_node_path
}
}
impl InspectState {
fn new(inspect_node_path: Vec<NodeId>) -> Option<Self> {
(!inspect_node_path.is_empty()).then_some(Self {
inspect_node_path,
overrides: ContextOverrides::default(),
last_evaluation: None,
overrides_changed: false,
})
}
fn access(&mut self, executor: &DynamicExecutor, network: Option<&NodeNetwork>) -> InspectResult {
let node = network.and_then(|network| executor.tree().output_node(network, &self.inspect_node_path));
let context = node.and_then(|node| executor.tree().last_context(node).ok().flatten()).map(|context| self.with_overrides(context));
let introspected_data = node.zip(context.clone()).and_then(|(node, context)| self.evaluate(executor, node, context));
let features = context.as_ref().and_then(|context| context.as_deref()).map(context_features).unwrap_or_default();
let context = InspectedContext {
overrides: self.overrides.clone(),
dependencies: node.map(|node| executor.tree().context_features(node)).unwrap_or_default(),
..features
};
InspectResult {
introspected_data,
inspect_node_path: self.inspect_node_path.clone(),
context,
}
}
fn with_overrides(&self, context: Context<'static>) -> Context<'static> {
if self.overrides.is_empty() {
return context;
}
let context = context
.as_deref()
.map(|context| context.with_overrides(&self.overrides))
.unwrap_or_else(|| OwnedContextImpl::empty().with_overrides(&self.overrides));
Some(Arc::new(context))
}
/// Evaluates the node with the context, reusing the last result if neither changed.
fn evaluate(&mut self, executor: &DynamicExecutor, node: NodeId, context: Context<'static>) -> Option<Arc<dyn std::any::Any + Send + Sync + 'static>> {
let context_hash = context_hash(&context);
if let Some((last_node, last_context_hash, data)) = &self.last_evaluation
&& (*last_node, *last_context_hash) == (node, context_hash)
{
return data.clone();
}
let output = evaluated_output(executor.tree().evaluate(node, &context).ok()?)?;
// Output the Data panel can't show is remembered too, so it isn't evaluated again for nothing
let data = crate::messages::portfolio::document::data_panel::shareable_inspect_output(output);
self.last_evaluation = Some((node, context_hash, data.clone()));
data
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::EditorTestUtils;
use glam::DVec2;
use graph_craft::document::DocumentNode;
use graphene_std::SourceId;
use graphene_std::runtime::Runtime;
@@ -0,0 +1,185 @@
use super::{context_hash, evaluated_output};
use crate::messages::portfolio::document::data_panel::shareable_inspect_output;
use glam::DVec2;
use graph_craft::document::{NodeId, NodeNetwork};
use graphene_std::{Context, ContextFeatures, ContextOverrides, OwnedContextImpl};
use interpreted_executor::dynamic_executor::{BorrowTree, DynamicExecutor};
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Arc;
pub type ObservedValue = Arc<dyn std::any::Any + Send + Sync + 'static>;
/// A connector of a document node whose value the editor reads back after each evaluation.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Observation {
pub node_path: Vec<NodeId>,
pub connector: ObservedConnector,
/// Replaces parts of the context the value is evaluated with.
pub overrides: ContextOverrides,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ObservedConnector {
Input(usize),
Output,
}
/// The value an observation read, with the context it was evaluated with.
#[derive(Clone, Debug, Default)]
pub struct InspectResult {
pub data: Option<ObservedValue>,
pub node_path: Vec<NodeId>,
pub context: InspectedContext,
}
/// The features of the context an inspected node was evaluated with, after the overrides replaced some of them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InspectedContext {
pub features: ContextOverrides,
pub positions: Vec<DVec2>,
pub variables: usize,
pub overrides: ContextOverrides,
pub dependencies: ContextFeatures,
}
// This is very ugly but is required to be inside a message
impl PartialEq for InspectResult {
fn eq(&self, other: &Self) -> bool {
self.node_path == other.node_path
}
}
/// Evaluates each observed connector again from the context its node was last evaluated with.
pub struct Observer<Key> {
observations: HashMap<Key, ObservationState>,
}
struct ObservationState {
observation: Observation,
last_evaluation: Option<Evaluation>,
}
struct Evaluation {
source: NodeId,
context_hash: u64,
value: Option<ObservedValue>,
}
impl<Key> Default for Observer<Key> {
fn default() -> Self {
Self { observations: HashMap::new() }
}
}
impl<Key: Clone + Eq + Hash> Observer<Key> {
/// Replaces every observation, keeping the last evaluation of those that stayed the same.
pub fn replace_all(&mut self, observations: HashMap<Key, Observation>) {
let mut previous = std::mem::take(&mut self.observations);
self.observations = observations
.into_iter()
.map(|(key, observation)| {
let state = ObservationState::new(observation, previous.remove(&key));
(key, state)
})
.collect();
}
/// Starts, changes, or with `None` stops the observation under this key.
pub fn set(&mut self, key: Key, observation: Option<Observation>) {
let previous = self.observations.remove(&key);
let Some(observation) = observation else { return };
self.observations.insert(key, ObservationState::new(observation, previous));
}
/// Evaluates the observations whose source or context changed, giving back the latest result of each.
pub fn evaluate(&mut self, executor: &DynamicExecutor, network: Option<&NodeNetwork>) -> HashMap<Key, InspectResult> {
let tree = executor.tree();
self.observations.iter_mut().map(|(key, state)| (key.clone(), state.evaluate(tree, network))).collect()
}
}
impl ObservationState {
fn new(observation: Observation, previous: Option<ObservationState>) -> Self {
let last_evaluation = previous.filter(|previous| previous.observation == observation).and_then(|previous| previous.last_evaluation);
Self { observation, last_evaluation }
}
fn evaluate(&mut self, tree: &BorrowTree, network: Option<&NodeNetwork>) -> InspectResult {
let Observation { node_path, connector, overrides } = &self.observation;
let source = match connector {
ObservedConnector::Input(index) => tree.input_node(node_path, *index).ok(),
ObservedConnector::Output => network.and_then(|network| tree.output_node(network, node_path)),
};
let context = source.and_then(|source| tree.last_context(source).ok().flatten()).map(|context| with_overrides(context, overrides));
let introspected_data = source
.zip(context.clone())
.and_then(|(source, context)| evaluate_value(&mut self.last_evaluation, tree, source, context));
let features = context.as_ref().and_then(|context| context.as_deref()).map(context_features).unwrap_or_default();
let context = InspectedContext {
overrides: overrides.clone(),
dependencies: source.map(|source| tree.context_features(source)).unwrap_or_default(),
..features
};
InspectResult {
data: introspected_data,
node_path: node_path.clone(),
context,
}
}
}
/// Evaluates the node with the context, reusing the last result if neither changed.
fn evaluate_value(last_evaluation: &mut Option<Evaluation>, tree: &BorrowTree, source: NodeId, context: Context<'static>) -> Option<ObservedValue> {
let context_hash = context_hash(&context);
if let Some(evaluation) = last_evaluation
&& (evaluation.source, evaluation.context_hash) == (source, context_hash)
{
return evaluation.value.clone();
}
let output = evaluated_output(tree.evaluate(source, &context).ok()?)?;
// Output that can't be shared is remembered too, so it isn't evaluated again for nothing
let value = shareable_inspect_output(output);
*last_evaluation = Some(Evaluation {
source,
context_hash,
value: value.clone(),
});
value
}
fn with_overrides(context: Context<'static>, overrides: &ContextOverrides) -> Context<'static> {
if overrides.is_empty() {
return context;
}
let context = context
.as_deref()
.map(|context| context.with_overrides(overrides))
.unwrap_or_else(|| OwnedContextImpl::empty().with_overrides(overrides));
Some(Arc::new(context))
}
fn context_features(context: &OwnedContextImpl) -> InspectedContext {
use graphene_std::{ExtractAnimationTime, ExtractFootprint, ExtractIndex, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs};
InspectedContext {
features: ContextOverrides {
footprint: context.try_footprint().copied(),
real_time: context.try_real_time(),
animation_time: context.try_animation_time(),
pointer_position: context.try_pointer_position(),
index: context.try_index().map(|index| index.collect()),
},
positions: context.try_position().map(|positions| positions.collect()).unwrap_or_default(),
variables: context.varargs_len().unwrap_or_default(),
..Default::default()
}
}
@@ -21,8 +21,36 @@
$: nodeCategories = buildNodeCategories(searchTerm);
type TextSegment = {
text: string;
highlighted: boolean;
};
type NodeCatalogEntry = {
nodeType: FrontendNodeType;
matchedAliasSegments: TextSegment[] | undefined;
};
// Splits `text` into runs that are highlighted where one of the lowercase `terms` occurs
function highlightTerms(text: string, terms: string[]): TextSegment[] {
const lowercaseText = text.toLowerCase();
const highlighted = new Array<boolean>(text.length).fill(false);
terms.forEach((term) => {
const start = lowercaseText.indexOf(term);
if (term.length > 0 && start !== -1) highlighted.fill(true, start, start + term.length);
});
const segments: TextSegment[] = [];
highlighted.forEach((isHighlighted, index) => {
const last = segments.at(-1);
if (last?.highlighted === isHighlighted) last.text += text[index];
else segments.push({ text: text[index], highlighted: isHighlighted });
});
return segments;
}
type NodeCategoryDetails = {
nodes: FrontendNodeType[];
nodes: NodeCatalogEntry[];
open: boolean;
};
@@ -43,23 +71,24 @@
nodeTypes.forEach((node) => {
let matchesTypeSearch = true;
let matchesRemainingTerms = true;
if (isTypeSearch && typeSearchTerm) {
matchesTypeSearch = node.inputTypes?.some((constraint) => constraint === "All" || constraint.Limited.some((inputType) => inputType.toLowerCase().includes(typeSearchTerm))) || false;
}
if (remainingSearchTerms.length > 0) {
matchesRemainingTerms = remainingSearchTerms.every((term) => {
const nameMatch = node.name.toLowerCase().includes(term);
const categoryMatch = node.category.toLowerCase().includes(term);
const termsUnmatchedByName = remainingSearchTerms.filter((term) => {
const nameMatch = node.name.toLowerCase().includes(term);
const categoryMatch = node.category.toLowerCase().includes(term);
// Quick and dirty hack to alias "Layer" to "Merge" in the search
const layerAliasMatch = node.name === "Merge" && "layer".includes(term);
// Quick and dirty hack to alias "Layer" to "Merge" in the search
const layerAliasMatch = node.name === "Merge" && "layer".includes(term);
return nameMatch || categoryMatch || layerAliasMatch;
});
}
return !nameMatch && !categoryMatch && !layerAliasMatch;
});
const matchedAlias = termsUnmatchedByName.length > 0 ? node.searchAliases.find((alias) => termsUnmatchedByName.every((term) => alias.toLowerCase().includes(term))) : undefined;
const matchesRemainingTerms = termsUnmatchedByName.length === 0 || matchedAlias !== undefined;
const matchedAliasSegments = matchedAlias !== undefined ? highlightTerms(matchedAlias, termsUnmatchedByName) : undefined;
// Node matches if it passes both type search and remaining terms filters
const includesSearchTerm = matchesTypeSearch && matchesRemainingTerms;
@@ -76,11 +105,11 @@
if (category) {
category.open = category.open || open;
category.nodes.push(node);
category.nodes.push({ nodeType: node, matchedAliasSegments });
} else {
categories.set(node.category, {
open,
nodes: [node],
nodes: [{ nodeType: node, matchedAliasSegments }],
});
}
});
@@ -102,14 +131,20 @@
<summary>
<TextLabel>{nodeCategory[0]}</TextLabel>
</summary>
{#each nodeCategory[1].nodes as nodeType}
{#each nodeCategory[1].nodes as { nodeType, matchedAliasSegments }}
<TextButton
{disabled}
label={nodeType.name}
tooltipLabel={nodeType.name}
tooltipDescription={nodeType.identifier ? $nodeGraph.nodeDescriptions.get(nodeType.identifier) : undefined}
action={() => dispatch("selectNodeType", nodeType.identifier)}
/>
>
{#if matchedAliasSegments}
<span class="matched-alias"
>{#each matchedAliasSegments as segment}<span class:highlighted={segment.highlighted}>{segment.text}</span>{/each}</span
>
{/if}
</TextButton>
{/each}
</details>
{:else}
@@ -172,6 +207,17 @@
&:last-child .text-button {
margin-bottom: 0;
}
.matched-alias {
margin-left: 8px;
overflow: hidden;
text-overflow: ellipsis;
color: var(--color-8-uppergray);
.highlighted {
color: var(--button-text-color);
}
}
}
}
}
@@ -88,6 +88,7 @@
{#if label}
<TextLabel>{label}</TextLabel>
{/if}
<slot />
</button>
{#if menuListChildrenExists}
<MenuList
@@ -73,8 +73,3 @@ harness = false
name = "brush_stroke_gungraun"
harness = false
required-features = ["gpu"]
[[bench]]
name = "artwork_gungraun"
harness = false
required-features = ["gpu"]
@@ -1,190 +0,0 @@
//! Counts the instructions for editing and viewing the demo artwork once it has been rendered, as the editor renders it after each change:
//! drawing a rectangle on top of it, which recompiles the graph and renders the viewport,
//! and zooming in, which renders the viewport anew since none of the cached tiles match the new zoom.
mod gpu_util;
use glam::{DAffine2, DVec2};
use gpu_util::{GpuDocument, VIEWPORT, callgrind};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graphene_std::transform_nodes::transform;
use graphene_std::vector::generator_nodes::rectangle;
use graphene_std::vector::{GradientForm, GradientRamp};
use graphene_std::vector_nodes::fill;
use graphene_std::{Color, Context};
use gungraun::prelude::*;
use std::path::Path;
/// The zoom step the measured render takes, about the viewport center.
const ZOOM: f64 = 1.5;
/// The new rectangle's nodes, numbered clear of the document's own so every run builds the same graph.
const RECTANGLE: NodeId = NodeId(u64::MAX - 3);
const TRANSFORM: NodeId = NodeId(u64::MAX - 2);
const FILL: NodeId = NodeId(u64::MAX - 1);
const LAYER: NodeId = NodeId(u64::MAX);
pub struct Session {
gpu: GpuDocument,
/// Where the viewport shows the artwork.
view: DAffine2,
/// The document graph for the measured update.
document: NodeNetwork,
}
/// Opens lavapipe and renders the demo artwork `name` fitted into the viewport, so the measured step meets the caches the editor would have.
fn open(name: &str) -> (Session, NodeNetwork) {
let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite"))))
.expect("Failed to open the demo artwork")
.network;
let view = fit(&network);
let mut gpu = GpuDocument::new();
gpu.compile(network.clone());
gpu.render(view);
let session = Session {
gpu,
view,
document: NodeNetwork::default(),
};
(session, network)
}
fn setup_add_rectangle(name: &str) -> Session {
let (mut session, network) = open(name);
session.document = with_rectangle(network);
session
}
/// The artwork viewed after zooming out and back, so the device has the shaders for a zoom change while no tiles at the measured zoom are cached.
fn setup_zoom(name: &str) -> Session {
let (session, _) = open(name);
session.gpu.render(zoomed(session.view, 1. / ZOOM));
session.gpu.render(session.view);
session
}
/// The view zoomed by `factor` about the viewport center.
fn zoomed(view: DAffine2, factor: f64) -> DAffine2 {
let center = VIEWPORT.as_dvec2() / 2.;
DAffine2::from_translation(center) * DAffine2::from_scale(DVec2::splat(factor)) * DAffine2::from_translation(-center) * view
}
/// The view that fits the document's root artboard into the viewport with a margin, as zooming to fit does.
fn fit(network: &NodeNetwork) -> DAffine2 {
let artboard = root(network);
let location = vec_input(artboard, 2);
let size = vec_input(artboard, 3);
let scale = (VIEWPORT.as_dvec2() / size).min_element() * 0.9;
let offset = (VIEWPORT.as_dvec2() - size * scale) / 2. - location * scale;
DAffine2::from_translation(offset) * DAffine2::from_scale(DVec2::splat(scale))
}
/// The document with a rectangle layer on top of its artboard's other layers, with the nodes the Rectangle tool creates.
fn with_rectangle(mut network: NodeNetwork) -> NodeNetwork {
let artboard = root(&network);
let location = vec_input(artboard, 2);
let size = vec_input(artboard, 3);
let NodeInput::Node { node_id: top, .. } = artboard.inputs[1] else {
panic!("The artboard has no layers");
};
// The top layer serves as the template for the new one, sharing the document's layer definition
let mut layer = network.nodes[&top].clone();
assert!(matches!(layer.implementation, DocumentNodeImplementation::Definition(_)), "The artboard's top layer is no layer node");
layer.inputs[0] = NodeInput::node(top, 0);
layer.inputs[1] = NodeInput::node(FILL, 0);
let node = |implementation, inputs| DocumentNode {
inputs,
call_argument: concrete!(Context),
implementation: DocumentNodeImplementation::ProtoNode(implementation),
..Default::default()
};
let value = |value| NodeInput::value(value, false);
let rectangle = node(
rectangle::IDENTIFIER,
vec![
value(TaggedValue::None),
value(TaggedValue::Number(size.x / 3.)),
value(TaggedValue::Number(size.y / 3.)),
value(TaggedValue::BoxCorners(vec![0.])),
value(TaggedValue::Bool(true)),
value(TaggedValue::Bool(false)),
],
);
let transform = node(
transform::IDENTIFIER,
vec![
NodeInput::node(RECTANGLE, 0),
value(TaggedValue::DVec2(location + size / 2.)),
value(TaggedValue::Number(0.)),
value(TaggedValue::DVec2(DVec2::ONE)),
value(TaggedValue::DVec2(DVec2::ZERO)),
],
);
let color = Color::from_rgbaf32_unchecked(0.9, 0.3, 0.2, 1.);
let fill = node(
fill::IDENTIFIER,
vec![
NodeInput::node(TRANSFORM, 0),
value(TaggedValue::Color(color)),
value(TaggedValue::Color(color)),
value(TaggedValue::GradientRamp(GradientRamp::default())),
value(TaggedValue::GradientForm(GradientForm::Linear)),
value(TaggedValue::Bool(false)),
value(TaggedValue::DAffine2(DAffine2::IDENTITY)),
],
);
let NodeInput::Node { node_id: root_id, .. } = network.exports[0] else { unreachable!() };
network.nodes.extend([(RECTANGLE, rectangle), (TRANSFORM, transform), (FILL, fill), (LAYER, layer)]);
network.nodes.get_mut(&root_id).expect("The document has no root node").inputs[1] = NodeInput::node(LAYER, 0);
network
}
/// The artboard the document exports, which every demo artwork has.
fn root(network: &NodeNetwork) -> &DocumentNode {
let NodeInput::Node { node_id, .. } = network.exports[0] else {
panic!("The document exports no node");
};
&network.nodes[&node_id]
}
fn vec_input(node: &DocumentNode, index: usize) -> DVec2 {
match node.inputs[index].as_value() {
Some(TaggedValue::DVec2(value)) => *value,
other => panic!("The artboard's input {index} is {other:?} rather than a vector"),
}
}
#[library_benchmark]
#[benches::artwork(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_add_rectangle)]
pub fn add_rectangle(mut session: Session) -> Session {
let document = std::mem::take(&mut session.document);
callgrind::start();
session.gpu.compile(document);
session.gpu.render(session.view);
callgrind::stop();
// Return the session so its teardown happens outside the measured section
session
}
#[library_benchmark]
#[benches::artwork(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_zoom)]
pub fn zoom(session: Session) -> Session {
let view = zoomed(session.view, ZOOM);
callgrind::start();
session.gpu.render(view);
callgrind::stop();
session
}
library_benchmark_group!(name = artwork_group; benchmarks = add_rectangle, zoom);
main!(
config = gpu_util::config();
library_benchmark_groups = artwork_group
);
@@ -1,21 +1,33 @@
//! Counts the instructions a document update costs when one stroke is added to its brush layer, the way the Brush tool appends strokes:
//! wrapping and compiling the changed graph, updating the executor and rendering the viewport, as the editor's runtime does for each change.
//! Rendering the same document with an empty brush cache is measured alongside, showing how much of the earlier render the cache saves.
//!
//! The graph renders on a software Vulkan device (lavapipe), so CI runners without a GPU can measure it and the counts include the "GPU" work.
mod gpu_util;
use glam::{DAffine2, DVec2};
use gpu_util::{GpuDocument, VIEWPORT, callgrind};
use core_types::transform::{Footprint, RenderQuality};
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::graphene_compiler::Compiler;
use graphene_std::application_io::RenderConfig;
use graphene_std::brush::basic_brush::{basic_brush, basic_brush_pipeline};
use graphene_std::brush::{BrushCache, Channel, Stroke, brush_strokes};
use graphene_std::graphic;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use graphene_std::uuid::NodeId;
use graphene_std::{Color, Context};
use gungraun::prelude::*;
use gungraun::{Callgrind, EntryPoint};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::hint::black_box;
use std::sync::Arc;
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
/// Small enough to keep Valgrind runs short, since the full-frame passes scale with it.
const VIEWPORT: UVec2 = UVec2::new(960, 540);
/// Samples in the added stroke.
const STROKE_SAMPLES: usize = 128;
/// Samples in each stroke already in the document.
@@ -26,7 +38,11 @@ const SAMPLE_SPACING: f64 = 4.;
const STROKES_PER_GROUP: usize = 8;
pub struct Session {
gpu: GpuDocument,
gpu: WgpuExecutor,
editor_api: Arc<PlatformEditorApi>,
runtime: AsyncRuntime,
preprocessor: preprocessor::Preprocessor,
executor: DynamicExecutor,
/// The document graph for the measured update.
document: NodeNetwork,
}
@@ -35,18 +51,42 @@ impl Session {
/// Opens lavapipe and renders the finished document once through a brush cache that is then discarded,
/// so that the device's shaders are compiled and its textures allocated before anything is measured.
fn open(after: &[Group]) -> Self {
let gpu = lavapipe();
let mut session = Self {
gpu: GpuDocument::new(),
editor_api: Arc::new(PlatformEditorApi {
application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))),
}),
gpu,
runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)),
preprocessor: preprocessor::Preprocessor::new(),
executor: DynamicExecutor::default(),
document: NodeNetwork::default(),
};
session.update(brush_layer(&BrushCache::default(), after));
session
}
/// Recompiles the document graph and renders the viewport, as the runtime does after an edit.
/// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit.
fn update(&mut self, document: NodeNetwork) {
self.gpu.compile(document);
self.gpu.render(DAffine2::IDENTITY);
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
self.executor.update(proto_network).expect("Failed to update the executor");
let render_config = RenderConfig {
viewport: Footprint {
transform: DAffine2::IDENTITY,
resolution: VIEWPORT,
quality: RenderQuality::Full,
},
scale: 1.,
..Default::default()
};
let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context());
assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}");
// Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands
let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely());
let _ = black_box(output);
}
}
@@ -70,6 +110,29 @@ fn setup_render_layer(existing: usize) -> Session {
session
}
/// Opens lavapipe, refusing a hardware device, whose work Callgrind can't see.
fn lavapipe() -> WgpuExecutor {
let context = futures::executor::block_on(WgpuContextBuilder::new().with_backends(wgpu::Backends::VULKAN).build())
.expect("No Vulkan device; install lavapipe (mesa-vulkan-drivers) and point VK_DRIVER_FILES at its ICD");
let info = context.adapter.get_info();
assert_eq!(
info.device_type,
wgpu::DeviceType::Cpu,
"Picked {} instead of a software device, which would make the counts meaningless; point VK_DRIVER_FILES at lavapipe's ICD",
info.name
);
WgpuExecutor::with_context(context).expect("Failed to create the GPU executor")
}
/// Runs spawned work to completion on the spot, so everything the graph starts happens in the measured section.
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
futures::executor::block_on(task);
}
}
/// The `Brush Strokes` settings of a group, as the Brush tool starts a new group whenever its settings change.
#[derive(Clone, Copy)]
struct Style {
@@ -216,6 +279,47 @@ impl Random {
}
}
/// Callgrind's client requests for switching instrumentation, which unlike collection applies to every thread.
/// Outside Valgrind these are a few no-op rotations.
mod callgrind {
/// `VG_USERREQ_TOOL_BASE('C', 'T')` in `callgrind.h`, followed by `DUMP_STATS`, `ZERO_STATS`, `TOGGLE_COLLECT` and `DUMP_STATS_AT`
const START_INSTRUMENTATION: u64 = ((b'C' as u64) << 24 | (b'T' as u64) << 16) + 4;
const STOP_INSTRUMENTATION: u64 = START_INSTRUMENTATION + 1;
pub fn start() {
request(START_INSTRUMENTATION);
}
pub fn stop() {
request(STOP_INSTRUMENTATION);
}
/// The x86-64 form of `VALGRIND_DO_CLIENT_REQUEST_EXPR` in `valgrind.h`, which Valgrind recognizes by the preamble's rotations of `rdi` (adding up to a full turn).
#[cfg(target_arch = "x86_64")]
fn request(code: u64) {
let args = [code, 0, 0, 0, 0, 0];
// SAFETY: The rotations leave `rdi` as it was and `xchg rbx, rbx` changes nothing, so natively this only reads `args`; under Valgrind, the request writes `rdx`
unsafe {
std::arch::asm!(
"rol rdi, 3",
"rol rdi, 13",
"rol rdi, 61",
"rol rdi, 51",
"xchg rbx, rbx",
in("rax") args.as_ptr(),
inout("rdx") 0_u64 => _,
out("rdi") _,
options(nostack),
);
}
}
#[cfg(not(target_arch = "x86_64"))]
fn request(_code: u64) {
panic!("This benchmark only knows how to reach Valgrind on x86-64");
}
}
#[library_benchmark]
#[benches::existing_strokes(args = [0, 16, 256], setup = setup_add_stroke)]
pub fn add_stroke(session: Session) -> Session {
@@ -241,6 +345,12 @@ fn measure(mut session: Session) -> Session {
library_benchmark_group!(name = brush_stroke_group; benchmarks = add_stroke, render_layer);
main!(
config = gpu_util::config();
// Only what runs between `callgrind::start` and `callgrind::stop` is measured, on every thread,
// since the device works on its own queue thread, which the default entry point (collecting on the benchmark's thread alone) would leave out
config = LibraryBenchmarkConfig::default()
.pass_through_env("VK_DRIVER_FILES")
// Rasterizing on the queue thread alone keeps the counts independent of the runner's core count
.env("LP_NUM_THREADS", "0")
.tool(Callgrind::with_args(["--instr-atstart=no"]).entry_point(EntryPoint::None));
library_benchmark_groups = brush_stroke_group
);
@@ -1,148 +0,0 @@
//! Shared by the benchmarks that render documents the way the editor does, through Vello on a software Vulkan device (lavapipe),
//! so CI runners without a GPU can measure them and the counts include the "GPU" work.
use core_types::transform::{Footprint, RenderQuality};
use glam::{DAffine2, UVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::NodeNetwork;
use graph_craft::graphene_compiler::Compiler;
use graphene_std::application_io::{ExportFormat, RenderConfig};
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use gungraun::{Callgrind, EntryPoint, LibraryBenchmarkConfig};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::hint::black_box;
use std::sync::Arc;
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
/// Small enough to keep Valgrind runs short, since the full-frame passes scale with it.
pub const VIEWPORT: UVec2 = UVec2::new(960, 540);
/// Measures only what runs between [`callgrind::start`] and [`callgrind::stop`], on every thread,
/// since the device works on its own queue thread, which the default entry point (collecting on the benchmark's thread alone) would leave out.
pub fn config() -> LibraryBenchmarkConfig {
let mut config = LibraryBenchmarkConfig::default();
config
.pass_through_env("VK_DRIVER_FILES")
// Rasterizing on the queue thread alone keeps the counts independent of the runner's core count
.env("LP_NUM_THREADS", "0")
// Shaders compiled by an earlier run, such as the baseline's, would otherwise load from disk and lower the counts
.env("MESA_SHADER_CACHE_DISABLE", "true")
.tool(Callgrind::with_args(["--instr-atstart=no"]).entry_point(EntryPoint::None));
config
}
/// A document compiled into an executor that renders it through the editor's render chain, as the editor's runtime does.
pub struct GpuDocument {
gpu: WgpuExecutor,
editor_api: Arc<PlatformEditorApi>,
runtime: AsyncRuntime,
preprocessor: preprocessor::Preprocessor,
executor: DynamicExecutor,
}
impl GpuDocument {
pub fn new() -> Self {
let gpu = lavapipe();
Self {
editor_api: Arc::new(PlatformEditorApi {
application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))),
}),
gpu,
runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)),
preprocessor: preprocessor::Preprocessor::new(),
executor: DynamicExecutor::default(),
}
}
/// Wraps and compiles the document graph into the executor, as the runtime does after an edit.
pub fn compile(&mut self, document: NodeNetwork) {
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
self.executor.update(proto_network).expect("Failed to update the executor");
}
/// Renders the viewport with the document placed by `transform`, waiting for the device to finish.
pub fn render(&self, transform: DAffine2) {
let render_config = RenderConfig {
viewport: Footprint {
transform,
resolution: VIEWPORT,
quality: RenderQuality::Full,
},
scale: 1.,
export_format: ExportFormat::Raster,
..Default::default()
};
let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context());
assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}");
// Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands
let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely());
let _ = black_box(output);
}
}
/// Opens lavapipe, refusing a hardware device, whose work Callgrind can't see.
fn lavapipe() -> WgpuExecutor {
let context = futures::executor::block_on(WgpuContextBuilder::new().with_backends(wgpu::Backends::VULKAN).build())
.expect("No Vulkan device; install lavapipe (mesa-vulkan-drivers) and point VK_DRIVER_FILES at its ICD");
let info = context.adapter.get_info();
assert_eq!(
info.device_type,
wgpu::DeviceType::Cpu,
"Picked {} instead of a software device, which would make the counts meaningless; point VK_DRIVER_FILES at lavapipe's ICD",
info.name
);
WgpuExecutor::with_context(context).expect("Failed to create the GPU executor")
}
/// Runs spawned work to completion on the spot, so everything the graph starts happens in the measured section.
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
futures::executor::block_on(task);
}
}
/// Callgrind's client requests for switching instrumentation, which unlike collection applies to every thread.
/// Outside Valgrind these are a few no-op rotations.
pub mod callgrind {
/// `VG_USERREQ_TOOL_BASE('C', 'T')` in `callgrind.h`, followed by `DUMP_STATS`, `ZERO_STATS`, `TOGGLE_COLLECT` and `DUMP_STATS_AT`
const START_INSTRUMENTATION: u64 = ((b'C' as u64) << 24 | (b'T' as u64) << 16) + 4;
const STOP_INSTRUMENTATION: u64 = START_INSTRUMENTATION + 1;
pub fn start() {
request(START_INSTRUMENTATION);
}
pub fn stop() {
request(STOP_INSTRUMENTATION);
}
/// The x86-64 form of `VALGRIND_DO_CLIENT_REQUEST_EXPR` in `valgrind.h`, which Valgrind recognizes by the preamble's rotations of `rdi` (adding up to a full turn).
#[cfg(target_arch = "x86_64")]
fn request(code: u64) {
let args = [code, 0, 0, 0, 0, 0];
// SAFETY: The rotations leave `rdi` as it was and `xchg rbx, rbx` changes nothing, so natively this only reads `args`; under Valgrind, the request writes `rdx`
unsafe {
std::arch::asm!(
"rol rdi, 3",
"rol rdi, 13",
"rol rdi, 61",
"rol rdi, 51",
"xchg rbx, rbx",
in("rax") args.as_ptr(),
inout("rdx") 0_u64 => _,
out("rdi") _,
options(nostack),
);
}
}
#[cfg(not(target_arch = "x86_64"))]
fn request(_code: u64) {
panic!("The GPU benchmarks only know how to reach Valgrind on x86-64");
}
}
@@ -333,10 +333,19 @@ impl BorrowTree {
self.context_features.get(&id).copied().unwrap_or_default()
}
/// The node feeding an input of the proto node at this path, looking past the nodes wrapping it under the same path such as 'Memoize'.
pub fn input_node(&self, node_path: &[NodeId], input_index: usize) -> Result<NodeId, IntrospectError> {
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
let (_, _, inputs) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
inputs.get(input_index).copied().ok_or(IntrospectError::NoData)
let (mut id, _) = *self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
loop {
let (_, _, inputs) = self.nodes.get(&id).ok_or(IntrospectError::ProtoNodeNotFound(id))?;
let wrapped = inputs.first().filter(|first| self.nodes.get(first).is_some_and(|(_, path, _)| **path == *node_path));
match wrapped {
Some(&wrapped) => id = wrapped,
None => return inputs.get(input_index).copied().ok_or(IntrospectError::NoData),
}
}
}
/// The context this node was last evaluated with in the graph.
+32 -1
View File
@@ -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
@@ -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.