Free executor nodes once no output reaches them, and let an export keep its output instead of blocking the runtime

This commit is contained in:
Timon committed 2026-12-05 23:31:32 +00:00
1 parent c7e9aaa016
commit 6a0f39e8ad
5 files changed
+380 -196

No files matched your search

+14 -16
View File
@@ -506,16 +506,11 @@ impl NodeGraphExecutor {
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
while let Some(&(queued_execution_id, _)) = self.futures.front() {
if queued_execution_id < execution_id {
self.futures.pop_front();
} else {
break;
}
}
self.futures
.retain(|(queued_execution_id, execution_context)| *queued_execution_id >= execution_id || execution_context.export_config.is_some());
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
let execution_context = if let Some(index) = self.futures.iter().position(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
let (_, execution_context) = self.futures.remove(index).expect("the index was just found");
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() {
self.pending = Some((execution_id, execution_context.clone()));
}
@@ -636,17 +631,18 @@ impl NodeGraphExecutor {
let node_graph_output = match node_graph_output {
Ok(output) => output,
Err(message) => {
if let Some(message) = &message {
log::error!("Node graph evaluation failed:\n{message}");
}
if execution_context.export_config.is_some() {
responses.add(export_failure_dialog(message));
continue;
}
// Clear the click targets while the graph is in an un-renderable state
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new());
if let Some(message) = &message {
log::error!("Node graph evaluation failed:\n{message}");
}
if execution_context.export_config.is_some() {
responses.add(export_failure_dialog(message));
}
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break;
}
@@ -772,6 +768,8 @@ impl NodeGraphExecutor {
if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) {
responses.add(export_failure_dialog(None));
}
self.futures
.retain(|(execution_id, execution_context)| *execution_id != execution_response.execution_id || execution_context.export_config.is_none());
all_dropped_thumbnails.extend(execution_response.dropped_thumbnails);
}
@@ -18,8 +18,8 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
editor.dispatch(Message::Wake);
}
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops
/// for one more update, so a first update clears those of the graph before it.
/// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network
/// an update replaces for one more update, so a first update clears the nodes of the graph before it.
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
compile_and_run(editor).await;
compile_and_run(editor).await;
+349 -158
View File
@@ -43,25 +43,33 @@ pub struct NodeRuntime {
pub(super) executor: DynamicExecutor,
#[cfg(not(test))]
executor: DynamicExecutor,
output: OutputHandle,
receiver: Receiver<GraphRuntimeRequest>,
sender: Sender<NodeGraphUpdate>,
editor_wake: Wake,
dirty: Arc<AtomicBool>,
output: Option<OutputHandle>,
previous: Option<OutputHandle>,
pending: Option<ExecutionRequest>,
pending_export: Option<ExecutionRequest>,
pending_exports: Vec<(ExecutionRequest, OutputHandle)>,
pending_eyedropper: Option<ExecutionRequest>,
pending_thumbnails: Option<DocumentId>,
viewport_artwork: Option<ViewportArtwork>,
/// The network the executor last compiled successfully, with previews applied.
old_graph: Option<NodeNetwork>,
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
compile_failed: bool,
async_runtime: Option<AsyncRuntime>,
async_runtime: Option<AsyncRuntime>,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
thumbnails: Thumbnails,
observer: Observer<ObservationKey>,
/// Whether an observation changed since its results were last sent.
@@ -69,13 +77,9 @@ pub struct NodeRuntime {
preprocessor: preprocessor::Preprocessor,
/// Cached surface for Wasm viewport rendering (reused across frames)
#[cfg(all(target_family = "wasm", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle,
/// The viewport's latest artwork.
viewport_artwork: Option<ViewportArtwork>,
/// The layers from the render of the viewport's latest artwork.
rendered_layers: RenderedLayers,
/// The latest overlays, rendered again over each new artwork.
overlays: Option<OverlayContext>,
/// Whether the overlays or the artwork changed since the overlays were last rendered.
@@ -83,6 +87,10 @@ pub struct NodeRuntime {
overlays_canvas: VelloCanvas,
/// The latest rendered overlays.
overlays_texture: Option<Texture>,
/// Cached surface for Wasm viewport rendering (reused across frames)
#[cfg(all(target_family = "wasm", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle,
}
/// What the viewport shows beneath its overlays.
@@ -149,20 +157,26 @@ impl NodeRuntime {
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>, editor_wake: Wake) -> Self {
Self {
executor: DynamicExecutor::default(),
output: OutputHandle::default(),
receiver,
sender,
editor_wake,
dirty: Default::default(),
output: None,
previous: None,
pending: None,
pending_export: None,
pending_exports: Vec::new(),
pending_eyedropper: None,
pending_thumbnails: None,
old_graph: None,
compile_failed: false,
resources: ResourceRegistry::default(),
async_runtime: None,
viewport_artwork: None,
old_graph: None,
async_runtime: None,
editor_api: PlatformEditorApi {
#[cfg(not(test))]
application_io: None,
@@ -171,41 +185,71 @@ impl NodeRuntime {
application_io: Some(PlatformApplicationIo::default().into()),
}
.into(),
resources: ResourceRegistry::default(),
node_graph_errors: Vec::new(),
node_graph_warnings: Vec::new(),
thumbnails: Thumbnails::new(),
observer: Observer::default(),
observations_changed: false,
preprocessor: preprocessor::Preprocessor::new(),
#[cfg(all(target_family = "wasm", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(),
viewport_artwork: None,
rendered_layers: RenderedLayers::default(),
overlays: None,
overlays_stale: false,
overlays_canvas: VelloCanvas::default(),
overlays_texture: None,
#[cfg(all(target_family = "wasm", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(),
}
}
pub fn update(&mut self) {
if self.pending_export.is_some() {
return;
}
let mut graph = None;
for request in self.receiver.try_iter() {
while let Ok(request) = self.receiver.try_recv() {
match request {
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => {
self.pending_export = Some(request);
self.dirty.store(true, Ordering::Release);
break;
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
mut network,
resources,
previewed,
layers,
observations,
}) => {
apply_previews(&mut network, &previewed);
write_layer_paths(&mut network, &layers);
self.observer.replace_all(observations);
self.resources = resources;
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(network.clone());
if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor);
self.old_graph = Some(network);
}
let node_graph_errors = self.node_graph_errors.clone();
let node_graph_warnings = self.node_graph_warnings.clone();
self.sender
.send(NodeGraphUpdate::CompilationResponse(CompilationResponse {
result,
node_graph_errors,
node_graph_warnings,
}))
.expect("Failed to send response");
}
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => match self.output.clone() {
Some(output) => {
self.pending_exports.push((request, output));
self.dirty.store(true, Ordering::Release);
}
None => self.send_result(request.execution_id, ExecutionResult::Uncompiled),
},
GraphRuntimeRequest::ExecutionRequest(request) => {
self.pending = Some(request);
self.dirty.store(true, Ordering::Release);
@@ -214,15 +258,10 @@ impl NodeRuntime {
self.thumbnails.set_in_view(layers);
self.pending_thumbnails = Some(document_id);
}
// 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::Observe { key, 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");
@@ -233,82 +272,47 @@ impl NodeRuntime {
}
}
}
let Some(GraphUpdate {
mut network,
resources,
previewed,
layers,
observations,
}) = graph
else {
return;
};
apply_previews(&mut network, &previewed);
write_layer_paths(&mut network, &layers);
self.observer.replace_all(observations);
self.resources = resources;
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(network.clone());
self.compile_failed = result.is_err();
if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor);
self.old_graph = Some(network);
}
let node_graph_errors = self.node_graph_errors.clone();
let node_graph_warnings = self.node_graph_warnings.clone();
self.sender
.send(NodeGraphUpdate::CompilationResponse(CompilationResponse {
result,
node_graph_errors,
node_graph_warnings,
}))
.expect("Failed to send response");
}
pub async fn run(&mut self) -> Option<Texture> {
let dirty = self.dirty.swap(false, Ordering::Acquire);
let mut texture = None;
if let Some(export) = self.pending_export {
if dirty {
self.run_export(export).await;
if dirty {
for (request, output) in std::mem::take(&mut self.pending_exports) {
self.run_export(request, output).await;
}
} else {
let viewport = if dirty { self.pending } else { None };
}
if let Some(document_id) = self.pending_thumbnails.take()
&& viewport.is_none()
&& !self.compile_failed
{
let mut responses = VecDeque::new();
self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await;
if !responses.is_empty() {
self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response");
}
}
let viewport = if dirty { self.pending } else { None };
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(document_id) = self.pending_thumbnails.take()
&& viewport.is_none()
&& self.output.is_some()
{
let mut responses = VecDeque::new();
self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await;
if !responses.is_empty() {
self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response");
}
}
if let Some(eyedropper) = self.pending_eyedropper.take() {
self.run_eyedropper(eyedropper).await;
}
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(viewport) = viewport {
self.run_viewport(viewport).await;
}
if let Some(eyedropper) = self.pending_eyedropper.take() {
self.run_eyedropper(eyedropper).await;
}
// Overlays that changed without new artwork are drawn over the artwork already shown
if self.overlays_stale {
texture = self.composite_viewport_frame();
}
if let Some(viewport) = viewport {
self.run_viewport(viewport).await;
}
// Overlays that changed without new artwork are drawn over the artwork already shown
if self.overlays_stale {
texture = self.composite_viewport_frame();
}
(self.editor_wake)();
@@ -318,7 +322,11 @@ impl NodeRuntime {
async fn run_viewport(&mut self, request: ExecutionRequest) {
self.thumbnails.set_scale(request.render_config.scale);
let Some(mut result) = self.evaluate(request) else { return };
let result = match self.output.clone() {
Some(output) => self.evaluate(&output, request),
None => Some(ExecutionResult::Uncompiled),
};
let Some(mut result) = result else { return };
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
if let Some(RenderOutput { data, metadata }) = result.render_output() {
@@ -378,15 +386,14 @@ impl NodeRuntime {
Some(frame)
}
async fn run_export(&mut self, request: ExecutionRequest) {
let result = self.evaluate(request);
if matches!(result, Some(ExecutionResult::Pending)) {
async fn run_export(&mut self, request: ExecutionRequest, output: OutputHandle) {
let result = self.evaluate(&output, request);
if matches!(result, Some(ExecutionResult::Pending | ExecutionResult::Partial(_))) {
self.pending_exports.push((request, output));
return;
}
self.pending_export = None;
let Some(mut result) = result else { return };
self.dirty.store(true, Ordering::Release);
if let Some(RenderOutput { data, .. }) = result.render_output()
&& let RenderOutputType::Texture(texture) = data
@@ -405,7 +412,8 @@ impl NodeRuntime {
request.render_config.pointer = viewport.render_config.pointer;
}
if let Some(mut result) = self.evaluate(request)
if let Some(output) = self.output.clone()
&& let Some(mut result) = self.evaluate(&output, request)
&& let Some(RenderOutput {
data: RenderOutputType::Texture(texture),
..
@@ -416,11 +424,7 @@ impl NodeRuntime {
}
}
fn evaluate(&mut self, request: ExecutionRequest) -> Option<ExecutionResult> {
if self.compile_failed {
return Some(ExecutionResult::Uncompiled);
}
fn evaluate(&mut self, output: &OutputHandle, request: ExecutionRequest) -> Option<ExecutionResult> {
let ExecutionRequest { execution_id, mut render_config } = request;
// Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active
@@ -429,39 +433,46 @@ impl NodeRuntime {
}
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) {
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(output, context))) {
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
Ok(Ok(Poll::Fallback(boxed))) => {
let (value, error) = *boxed;
ExecutionResult::Fallback(value, self.resolve_errors(&error))
ExecutionResult::Fallback(value, self.resolve_errors(output, &error))
}
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(output, &error)),
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
Err(payload) => {
let response = ExecutionResponse {
execution_id,
result: ExecutionResult::Panic(payload),
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
observations: HashMap::new(),
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info: None,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
self.send_result(execution_id, ExecutionResult::Panic(payload));
return None;
}
};
Some(result)
}
fn send_result(&self, execution_id: u64, result: ExecutionResult) {
let response = ExecutionResponse {
execution_id,
result,
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
observations: HashMap::new(),
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info: None,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
let mut responses = VecDeque::new();
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
let dropped_thumbnails = if self.output.is_none() || request.render_config.for_export {
Vec::new()
} else {
self.update_thumbnails(&mut responses).await
};
#[cfg(all(target_family = "wasm", feature = "wasm"))]
let mut result = result;
@@ -507,6 +518,10 @@ impl NodeRuntime {
}
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
if let Some(output) = self.output.take() {
self.previous = Some(output);
}
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
@@ -530,7 +545,7 @@ impl NodeRuntime {
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let updated = self.executor.update(proto_network).map(|(output, types)| {
self.output = output;
self.output = Some(output);
types
});
let result = updated.map_err(|(types, e)| {
@@ -541,7 +556,7 @@ impl NodeRuntime {
result
}
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
fn resolve_errors(&self, output: &OutputHandle, error: &NodeError) -> EvaluationErrors {
let source_map = self.executor.tree().source_map();
let paths = |node: NodeId| -> NodePaths {
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
@@ -549,7 +564,7 @@ impl NodeRuntime {
paths.into()
};
let mut errors = Vec::new();
let output = self.output.node();
let output = output.node();
let mut pending = vec![(vec![paths(output)], output, error)];
while let Some((mut trace, node, error)) = pending.pop() {
let passed = self.executor.trace_error(node, error);
@@ -744,11 +759,50 @@ mod tests {
});
}
async fn run(editor: &mut EditorTestUtils) -> Option<Texture> {
editor.runtime.update();
editor.runtime.run().await
}
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
fn last_request(editor: &EditorTestUtils) -> Option<u64> {
editor.runtime.pending.map(|request| request.execution_id)
}
fn respond_to_last_request(editor: &mut EditorTestUtils, result: ExecutionResult) -> Vec<FrontendMessage> {
let response = ExecutionResponse {
execution_id: last_request(editor).unwrap(),
result,
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
observations: HashMap::new(),
};
editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).unwrap();
editor.dispatch(Message::Wake)
}
fn failed(messages: &[FrontendMessage]) -> bool {
messages.iter().any(|message| matches!(message, FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }))
}
fn drawn_in(messages: &[FrontendMessage]) -> Option<&str> {
messages.iter().find_map(|message| match message {
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg.as_str()),
_ => None,
})
}
fn empty_svg() -> RenderOutputType {
RenderOutputType::Svg {
svg: String::new(),
image_data: Vec::new(),
}
}
fn rendered(data: RenderOutputType) -> TaggedValue {
TaggedValue::RenderOutput(RenderOutput { data, metadata: Default::default() })
}
#[tokio::test]
async fn only_update_reads_the_channel() {
let mut editor = editor().await;
@@ -1032,28 +1086,63 @@ mod tests {
assert!(shows_dialog, "the export should show why it saved nothing");
}
#[tokio::test]
async fn an_export_goes_ahead_of_what_was_sent_after_it() {
let mut editor = editor().await;
let last = last_request(&editor);
send_export(&mut editor, FileType::Svg);
send_update(&mut editor);
fn rectangle_node(editor: &EditorTestUtils) -> NodeId {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use graphene_std::vector::generator_nodes::rectangle;
editor.runtime.update();
assert!(editor.runtime.pending_export.is_some());
assert_eq!(last_request(&editor), last, "the request sent after the export was read ahead of it");
let interface = &editor.active_document().network_interface;
let nodes = interface.document_network().nodes.keys().copied();
let reference = Some(DefinitionIdentifier::ProtoNode(rectangle::IDENTIFIER));
nodes.into_iter().find(|node_id| interface.reference(node_id, &[]) == reference).unwrap()
}
editor.runtime.run().await;
assert!(exported(&mut editor));
editor.runtime.update();
assert_ne!(last_request(&editor), last);
editor.runtime.run().await;
assert!(evaluated(&mut editor), "the request sent after the export was lost");
fn set_layer_visible(editor: &mut EditorTestUtils, visible: bool) {
let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node();
editor.active_document_mut().network_interface.set_visibility(&layer, &[], visible);
}
#[tokio::test]
async fn a_parked_export_holds_back_everything_sent_after_it() {
async fn an_export_shows_the_network_it_was_sent_with_whatever_was_sent_after_it() {
let mut editor = editor().await;
set_layer_visible(&mut editor, false);
send_export(&mut editor, FileType::Svg);
set_layer_visible(&mut editor, true);
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
let exported = messages.iter().find_map(|message| match message {
FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.clone().into_vec()).unwrap()),
_ => None,
});
assert!(exported.is_some_and(|svg| !svg.contains("<path")), "the export should leave out the rectangle hidden when it was sent");
assert!(drawn_in(&messages).is_some_and(|svg| svg.contains("<path")), "the update sent after the export should be drawn");
}
#[tokio::test]
async fn a_parked_export_holds_back_nothing_sent_after_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
add_traced_noise_layer(&mut editor).await;
send_export(&mut editor, FileType::Svg);
run(&mut editor).await;
editor.dispatch(Message::Wake);
assert!(!editor.runtime.pending_exports.is_empty(), "the export took a single evaluation");
let last = last_request(&editor);
set_layer_visible(&mut editor, false);
send_update(&mut editor);
run(&mut editor).await;
assert_ne!(last_request(&editor), last, "the parked export held back the request sent after it");
assert!(evaluated(&mut editor), "the request sent after the parked export was not evaluated");
}
#[tokio::test]
async fn an_export_that_finishes_after_what_was_sent_after_it_is_still_saved() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
@@ -1062,24 +1151,126 @@ mod tests {
send_export(&mut editor, FileType::Svg);
editor.runtime.update();
editor.runtime.run().await;
assert!(editor.runtime.pending_export.is_some(), "the export took a single evaluation");
assert!(!editor.runtime.pending_exports.is_empty(), "the export took a single evaluation");
let last = last_request(&editor);
send_update(&mut editor);
let mut saved = false;
let mut runs = 0;
while editor.runtime.pending_export.is_some() {
while !editor.runtime.pending_exports.is_empty() {
editor.runtime.update();
assert_eq!(last_request(&editor), last, "a request got ahead of the parked export");
editor.runtime.run().await;
saved |= exported(&mut editor);
runs += 1;
assert!(runs < 100_000, "the export never finished");
}
assert!(exported(&mut editor));
assert!(saved, "the export was lost");
}
#[tokio::test]
async fn two_exports_sent_together_are_both_saved() {
let mut editor = editor().await;
send_export(&mut editor, FileType::Svg);
send_export(&mut editor, FileType::Svg);
run(&mut editor).await;
let messages = editor.dispatch(Message::Wake);
let saved = messages.iter().filter(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }));
assert_eq!(saved.count(), 2);
}
#[tokio::test]
async fn a_failed_export_leaves_the_frame_that_follows_it_shown() {
let mut editor = editor().await;
send_update(&mut editor);
run(&mut editor).await;
editor.dispatch(Message::Wake);
send_export(&mut editor, FileType::Svg);
let failed_export = ExecutionResponse {
execution_id: editor.portfolio_message_handler().executor.futures.back().unwrap().0,
result: ExecutionResult::Error(EvaluationErrors(Box::new([]))),
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
observations: HashMap::new(),
};
editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(failed_export))).unwrap();
let messages = respond_to_last_request(&mut editor, ExecutionResult::Value(rendered(empty_svg())));
let shows_dialog = messages.iter().any(|message| matches!(message, FrontendMessage::DisplayDialog { .. }));
assert!(shows_dialog, "the export should say it failed");
assert!(!failed(&messages), "the failed export marked the viewport's render as failed");
assert!(drawn_in(&messages).is_some(), "the frame that followed the failed export was dropped");
}
#[tokio::test]
async fn the_nodes_only_a_finished_export_kept_lose_their_types_at_the_next_network_update() {
let mut editor = editor().await;
let rectangle = rectangle_node(&editor);
let typed = |editor: &EditorTestUtils| editor.active_document().network_interface.resolved_types.types.contains_key(&vec![rectangle]);
send_export(&mut editor, FileType::Svg);
set_layer_visible(&mut editor, false);
send_update(&mut editor);
editor.runtime.update();
assert_ne!(last_request(&editor), last);
editor.runtime.run().await;
assert!(evaluated(&mut editor), "the request sent after the export was lost");
send_update(&mut editor);
run(&mut editor).await;
assert!(exported(&mut editor));
assert!(typed(&editor), "the rectangle's nodes should outlive the export until the network is updated");
send_update(&mut editor);
run(&mut editor).await;
editor.dispatch(Message::Wake);
assert!(!typed(&editor), "the hidden rectangle kept the type of the network the export held on to");
}
/// Feeds the rectangle into an 'Add' node, which takes numbers, so the graph compiles but fails to type check.
fn break_type_check(editor: &mut EditorTestUtils) {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use graphene_std::math_nodes::add;
let rectangle = rectangle_node(editor);
let content = InputConnector::node_at_index(editor.active_document().metadata().all_layers().next().unwrap().to_node(), 1);
let add_node = NodeId::new();
let template = resolve_proto_node_type(add::IDENTIFIER).unwrap().default_node_template();
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.insert_node(add_node, template, &[]);
network_interface.set_input(&InputConnector::node_at_index(add_node, 0), NodeInput::node(rectangle, 0), &[]);
network_interface.set_input(&content, NodeInput::node(add_node, 0), &[]);
}
#[tokio::test]
async fn a_network_that_fails_to_type_check_leaves_no_output_and_keeps_the_last_one_that_did() {
let mut editor = editor().await;
send_update(&mut editor);
run(&mut editor).await;
let output = editor.runtime.output.as_ref().expect("the network should compile").node();
break_type_check(&mut editor);
send_update(&mut editor);
run(&mut editor).await;
assert!(editor.runtime.output.is_none(), "a rectangle should not type check as a number");
assert_eq!(editor.runtime.previous.as_ref().map(OutputHandle::node), Some(output));
}
#[tokio::test]
async fn a_layer_hidden_and_shown_again_finds_its_nodes_again() {
let mut editor = editor().await;
let rectangle = rectangle_node(&editor);
let compiled = |editor: &EditorTestUtils| {
let tree = editor.runtime.executor.tree();
tree.source_map().get([rectangle].as_slice()).and_then(|(node, _)| tree.get(*node))
};
send_update(&mut editor);
run(&mut editor).await;
let before = compiled(&editor).expect("the rectangle should be compiled");
for visible in [false, true] {
set_layer_visible(&mut editor, visible);
send_update(&mut editor);
run(&mut editor).await;
}
let after = compiled(&editor).expect("the rectangle should be compiled again");
assert!(Arc::ptr_eq(&before, &after), "the rectangle was built again");
}
#[tokio::test]
@@ -19,8 +19,6 @@ pub struct DynamicExecutor {
typing_context: TypingContext,
/// The outputs of the networks, kept alive by the executor as long as there are handles to them.
outputs: Vec<Weak<NodeId>>,
// Kept for one more update, so a node that comes back is reused
orphaned_nodes: HashSet<NodeId>,
}
#[derive(Clone, Debug, Default)]
@@ -38,7 +36,6 @@ impl Default for DynamicExecutor {
tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
outputs: Vec::new(),
orphaned_nodes: HashSet::new(),
}
}
}
@@ -121,16 +118,13 @@ impl DynamicExecutor {
pending.extend(inputs.iter());
}
}
let orphaned = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
for node_id in old_to_remove {
if self.orphaned_nodes.contains(&node_id) {
let path = self.tree.free_node(node_id);
self.typing_context.remove_inference(node_id);
if let Some(path) = path {
remove.push(path);
}
let orphaned: Vec<NodeId> = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
let mut remove = Vec::new();
for node_id in orphaned {
let path = self.tree.free_node(node_id);
self.typing_context.remove_inference(node_id);
if let Some(path) = path {
remove.push(path);
}
}
remove
@@ -1240,18 +1240,19 @@ fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
drop(output);
executor.update(source_network(2)).unwrap();
assert_eq!(kept(&executor), [true; 2], "orphaned for one more update");
executor.update(source_network(2)).unwrap();
assert_eq!(kept(&executor), [false; 2]);
}
#[test]
fn a_source_is_listed_for_as_long_as_its_node_lives() {
let mut executor = DynamicExecutor::default();
executor.update(source_network(0)).unwrap();
let (output, _) = executor.update(source_network(0)).unwrap();
let listed = |executor: &DynamicExecutor| executor.sources().any(|source| *source == SourceId(0));
for _ in 0..3 {
executor.update(source_network(1)).unwrap();
assert_eq!(executor.sources().any(|source| *source == SourceId(0)), executor.tree().get(NodeId(0)).is_some());
}
executor.update(source_network(1)).unwrap();
assert!(listed(&executor));
drop(output);
executor.update(source_network(1)).unwrap();
assert!(!listed(&executor));
}