Limit number of instant graph reevaluations (#4758)

* Defer re-evaluations triggered by finished tasks to the next frame once the frame budget is spent, and abort the tasks of removed sources

* Clean up the frame budget change: share the Instant clock, drop redundant scheduling calls and comments

* Treat a zero frame budget as unlimited, let render signals cut the deferred-frame wait short, and fix the RFC's Runtime::spawn signature
This commit is contained in:
Dennis Kobert authored and GitHub committed 2026-10-30 17:20:36 +01:00
1 parent b574a6c9f3
commit ef3b45ae79
13 files changed
+364 -80

No files matched your search

+4 -1
View File
@@ -111,7 +111,10 @@ impl App {
loop {
let texture = async_runtime.block_on(node_runtime.run());
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
let _ = start_render_receiver.recv_timeout(Duration::from_millis(10));
let timeout = node_runtime.until_next_frame().unwrap_or(Duration::from_millis(10));
if start_render_receiver.recv_timeout(timeout).is_err() {
node_runtime.begin_frame();
}
if exiting_clone.load(Ordering::Relaxed) {
break;
}
+2 -1
View File
@@ -8,6 +8,7 @@ use graphite_editor::node_graph_executor::NodeRuntime;
use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc;
use std::time::Instant;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
@@ -63,7 +64,7 @@ impl DesktopWrapper {
.with_resource_storage(resource_storage)
.with_document_store(document_store),
)
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
.with_runtime(RuntimeBuilder::new(Arc::new(Instant::now())).with_wake(runtime_wake).with_application_io(application_io))
.with_spawner(spawner)
.with_random_seed(random_seed)
.build();
+28 -11
View File
@@ -2,7 +2,7 @@ use crate::application::{Editor, Environment};
use crate::dispatcher::Dispatcher;
use crate::messages::prelude::*;
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
use crate::task::{Spawn, Spawner};
use crate::task::{Clock, Scheduling, Spawn, Spawner};
use document_container::store::DocumentStore;
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
@@ -96,6 +96,8 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
let RuntimeBuilder {
wake: runtime_wake,
mut application_io,
scheduling,
clock,
} = runtime;
graphene_std::uuid::set_uuid_seed(random_seed);
@@ -107,7 +109,8 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
node_runtime.replace_application_io(application_io);
node_runtime.replace_task_executor(spawner, runtime_wake);
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
node_runtime.set_scheduling(scheduling);
(Editor { dispatcher }, node_runtime)
}
@@ -184,17 +187,18 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
pub struct RuntimeBuilder<W = (), A = ()> {
wake: W,
application_io: A,
clock: Arc<dyn Clock>,
scheduling: Scheduling,
}
impl RuntimeBuilder {
pub fn new() -> Self {
Self { wake: (), application_io: () }
}
}
impl Default for RuntimeBuilder {
fn default() -> Self {
Self::new()
pub fn new(clock: Arc<dyn Clock>) -> Self {
Self {
wake: (),
application_io: (),
clock,
scheduling: Scheduling::default(),
}
}
}
@@ -204,12 +208,25 @@ impl<A> RuntimeBuilder<(), A> {
RuntimeBuilder {
wake: Arc::new(wake),
application_io: self.application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W> RuntimeBuilder<W, ()> {
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
RuntimeBuilder { wake: self.wake, application_io }
RuntimeBuilder {
wake: self.wake,
application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W, A> RuntimeBuilder<W, A> {
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
Self { scheduling, ..self }
}
}
+113 -19
View File
@@ -1,7 +1,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 crate::task::{Scheduling, Spawn, Spawner, Task};
use glam::{DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
@@ -18,15 +18,15 @@ use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime;
use graphene_std::runtime::{AsyncRuntime, Clock};
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 interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use std::time::Duration;
use thumbnails::Thumbnails;
mod thumbnails;
@@ -42,12 +42,15 @@ pub struct NodeRuntime {
receiver: Receiver<GraphRuntimeRequest>,
sender: Sender<NodeGraphUpdate>,
editor_wake: Wake,
dirty: Arc<AtomicBool>,
/// A re-evaluation waiting for the next frame, or for the end of an export.
rerun: bool,
pending: Option<ExecutionRequest>,
pending_export: Option<ExecutionRequest>,
/// The network the executor last compiled successfully, with previews applied.
old_graph: Option<NodeNetwork>,
async_runtime: Option<AsyncRuntime>,
scheduling: Scheduling,
frame_start: Duration,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
@@ -125,12 +128,14 @@ impl NodeRuntime {
receiver,
sender,
editor_wake,
dirty: Default::default(),
rerun: false,
pending: None,
pending_export: None,
old_graph: None,
resources: ResourceRegistry::default(),
async_runtime: None,
scheduling: Scheduling::default(),
frame_start: Duration::ZERO,
editor_api: PlatformEditorApi {
#[cfg(not(test))]
@@ -216,8 +221,13 @@ impl NodeRuntime {
}
}
if self.dirty.swap(false, Ordering::Acquire) && execution.is_none() {
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
let rerun = std::mem::take(&mut self.rerun) | self.async_runtime().take_bumped();
if rerun && execution.is_none() {
if self.frame_has_budget() {
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
} else {
self.rerun = true;
}
}
// Eydropper should use the same time and pointer to not invalidate the cache
@@ -312,7 +322,7 @@ impl NodeRuntime {
self.pending_export = Some(request);
return None;
}
(true, _) => self.dirty.store(true, Ordering::Release),
(true, _) => self.rerun = true,
_ => {}
}
@@ -567,33 +577,54 @@ impl NodeRuntime {
.into();
}
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake) {
let spawn = NodeTaskExecutor {
spawner,
dirty: self.dirty.clone(),
wake,
};
self.async_runtime = Some(AsyncRuntime::new(Arc::new(spawn)));
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake, clock: Arc<dyn Clock>) {
self.async_runtime = Some(AsyncRuntime::new(Arc::new(NodeTaskExecutor { spawner, wake }), clock));
self.begin_frame();
}
fn async_runtime(&self) -> &AsyncRuntime {
pub fn set_scheduling(&mut self, scheduling: Scheduling) {
self.scheduling = scheduling;
}
/// Called by the host once the previous output was presented.
pub fn begin_frame(&mut self) {
self.frame_start = self.async_runtime().clock().now();
}
/// How long a deferred re-evaluation waits for the next frame.
pub fn until_next_frame(&self) -> Option<Duration> {
let budget = self.frame_budget()?;
let elapsed = self.frame_elapsed().as_nanos() % budget.as_nanos();
self.rerun.then(|| budget - Duration::from_nanos(elapsed as u64))
}
fn frame_elapsed(&self) -> Duration {
self.async_runtime().clock().now().saturating_sub(self.frame_start)
}
fn frame_budget(&self) -> Option<Duration> {
self.scheduling.frame_budget.filter(|budget| !budget.is_zero())
}
fn frame_has_budget(&self) -> bool {
self.frame_budget().is_none_or(|budget| self.frame_elapsed() < budget)
}
pub(crate) fn async_runtime(&self) -> &AsyncRuntime {
self.async_runtime.as_ref().expect("the task executor is installed before the first graph update")
}
}
struct NodeTaskExecutor {
spawner: Spawner,
dirty: Arc<AtomicBool>,
wake: Wake,
}
impl Spawn for NodeTaskExecutor {
fn spawn(&self, task: Task) {
let dirty = self.dirty.clone();
let wake = self.wake.clone();
self.spawner.spawn(Box::pin(async move {
task.await;
dirty.store(true, Ordering::Release);
wake();
}));
}
@@ -702,7 +733,10 @@ impl InspectState {
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::{EditorTestUtils, FakeClock};
use graph_craft::document::DocumentNode;
use graphene_std::SourceId;
use graphene_std::runtime::Runtime;
#[test]
fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
@@ -727,4 +761,64 @@ mod tests {
assert_eq!(network.exports.first().and_then(|export| export.as_node()), Some(previewed_node));
}
const SOURCE: SourceId = SourceId(1);
async fn editor(clock: &Arc<FakeClock>) -> EditorTestUtils {
let mut editor = EditorTestUtils::create_with(Scheduling::default(), clock.clone());
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.runtime.async_runtime().retain_sources(&[SOURCE]);
editor.runtime.begin_frame();
editor
}
fn finish_task(editor: &EditorTestUtils) {
editor.runtime.async_runtime().spawn(SOURCE, Box::pin(async {}));
}
async fn evaluates(editor: &mut EditorTestUtils) -> bool {
editor.runtime.run().await;
let messages = editor.editor.handle_message(Message::Wake);
messages.iter().any(|message| matches!(message, FrontendMessage::UpdateDocumentArtwork { .. }))
}
#[tokio::test]
async fn reevaluations_past_the_frame_budget_wait_for_the_next_frame() {
let clock = Arc::new(FakeClock::default());
let mut editor = editor(&clock).await;
finish_task(&editor);
finish_task(&editor);
assert!(evaluates(&mut editor).await);
assert!(!evaluates(&mut editor).await, "two finished tasks re-evaluated twice");
clock.advance(Duration::from_millis(20));
finish_task(&editor);
assert!(!evaluates(&mut editor).await);
assert_eq!(editor.runtime.until_next_frame(), Some(Duration::from_millis(12)));
editor.runtime.begin_frame();
assert!(evaluates(&mut editor).await);
assert_eq!(editor.runtime.until_next_frame(), None);
}
#[tokio::test]
async fn explicit_requests_ignore_the_frame_budget() {
let clock = Arc::new(FakeClock::default());
let mut editor = editor(&clock).await;
clock.advance(Duration::from_millis(100));
finish_task(&editor);
let portfolio = &mut editor.editor.dispatcher.message_handlers.portfolio_message_handler;
let document_id = portfolio.active_document_id.unwrap();
let document = portfolio.documents.get_mut(&document_id).unwrap();
portfolio
.executor
.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO)
.unwrap();
assert!(evaluates(&mut editor).await);
assert!(!evaluates(&mut editor).await, "the finished task re-evaluated after the explicit request");
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
pub use graphene_std::runtime::{Spawn, Task};
pub use graphene_std::runtime::{Clock, Scheduling, Spawn, Task};
use std::sync::Arc;
pub type Spawner = Arc<dyn Spawn + Send + Sync>;
+30 -3
View File
@@ -10,16 +10,18 @@ use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::Instrumented;
use crate::node_graph_executor::{EvaluationErrors, NodeRuntime};
use crate::task::{Spawn, Task};
use crate::task::{Scheduling, Spawn, Task};
use crate::test_utils::test_prelude::LayerNodeIdentifier;
use document_container::store::MemoryStore;
use glam::{DVec2, UVec2};
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::raster::color::Color;
use graphene_std::runtime::Clock;
use graphene_std::uuid::NodeId;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
/// A set of utility functions to make the writing of editor test more declarative
pub struct EditorTestUtils {
@@ -30,6 +32,10 @@ pub struct EditorTestUtils {
impl EditorTestUtils {
pub fn create() -> Self {
Self::create_with(Scheduling::UNLIMITED, Arc::new(FakeClock::default()))
}
pub fn create_with(scheduling: Scheduling, clock: Arc<dyn Clock>) -> Self {
init_test_logger();
let woken = Arc::new(AtomicBool::new(false));
@@ -42,7 +48,12 @@ impl EditorTestUtils {
.with_resource_storage(Arc::new(HashMapResourceStorage::new()))
.with_document_store(Arc::new(MemoryStore::default())),
)
.with_runtime(RuntimeBuilder::new().with_wake(|| {}).with_application_io(PlatformApplicationIo::default()))
.with_runtime(
RuntimeBuilder::new(clock)
.with_wake(|| {})
.with_application_io(PlatformApplicationIo::default())
.with_scheduling(scheduling),
)
.with_spawner(BlockingSpawner)
.with_random_seed(0)
.build();
@@ -493,6 +504,22 @@ pub fn capture_logged_errors<T>(operation: impl FnOnce() -> T) -> (T, Vec<String
(result, errors)
}
/// A clock that only moves when advanced.
#[derive(Debug, Default)]
pub struct FakeClock(Mutex<Duration>);
impl FakeClock {
pub fn advance(&self, by: Duration) {
*self.0.lock().unwrap_or_else(PoisonError::into_inner) += by;
}
}
impl Clock for FakeClock {
fn now(&self) -> Duration {
*self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
+1 -1
View File
@@ -37,7 +37,7 @@ serde-wasm-bindgen = { workspace = true }
js-sys = { workspace = true }
wasm-bindgen-futures = { workspace = true }
wgpu = { workspace = true, optional = true }
web-sys = { workspace = true }
web-sys = { workspace = true, features = ["Performance"] }
serde_json = { workspace = true }
spin = { workspace = true, optional = true }
tsify = { workspace = true }
+13 -2
View File
@@ -81,7 +81,11 @@ impl EditorWrapper {
.with_resource_storage(storage)
.with_document_store(document_store),
)
.with_runtime(RuntimeBuilder::new().with_wake(crate::helpers::wake_runtime).with_application_io(application_io))
.with_runtime(
RuntimeBuilder::new(std::sync::Arc::new(crate::helpers::PerformanceClock))
.with_wake(crate::helpers::wake_runtime)
.with_application_io(application_io),
)
.with_spawner(crate::helpers::WasmSpawner)
.with_random_seed(uuid_random_seed)
.build();
@@ -193,7 +197,14 @@ impl EditorWrapper {
*g.borrow_mut() = Some(Closure::new(move |_timestamp| {
#[cfg(not(feature = "native"))]
wasm_bindgen_futures::spawn_local(run_node_runtime());
{
if let Some(mut runtime) = crate::NODE_RUNTIME.try_lock()
&& let Some(runtime) = runtime.as_mut()
{
runtime.begin_frame();
}
wasm_bindgen_futures::spawn_local(run_node_runtime());
}
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
wrapper(|wrapper| {
+11 -1
View File
@@ -7,7 +7,7 @@ use editor::messages::input_mapper::utility_types::keyboard::Key;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::messages::prelude::*;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::task::{Spawn, Task};
use editor::task::{Clock, Spawn, Task};
use js_sys::{Object, Reflect};
use std::cell::RefCell;
use std::collections::HashSet;
@@ -70,6 +70,16 @@ impl Spawn for WasmSpawner {
}
}
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub(crate) struct PerformanceClock;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
impl Clock for PerformanceClock {
fn now(&self) -> Duration {
let performance = window().and_then(|window| window.performance()).expect("the editor runs in a window with `performance`");
Duration::from_secs_f64(performance.now() / 1000.)
}
}
/// Web editor wake: queues a microtask that dispatches [`Message::Wake`].
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub(crate) fn wake_editor() {
+1 -1
View File
@@ -190,7 +190,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
application_io: Some(application_io_for_api),
});
let spawner = Arc::new(TokioSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(std::time::Instant::now()));
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref(), runtime.handle())?;
match app.command {
@@ -3,14 +3,14 @@ use criterion::measurement::Measurement;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use graphene_std::runtime::{AsyncRuntime, Clock, Spawn, Task};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let network = load_from_name(name);
let editor_api = std::sync::Arc::new(EditorApi::default());
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner), std::sync::Arc::new(NoClock)).handle());
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
@@ -33,3 +33,10 @@ struct DummySpawner;
impl Spawn for DummySpawner {
fn spawn(&self, _task: Task) {}
}
struct NoClock;
impl Clock for NoClock {
fn now(&self) -> std::time::Duration {
std::time::Duration::ZERO
}
}
+145 -32
View File
@@ -1,13 +1,16 @@
use crate::poll::Poll;
use crate::uuid::NodeId;
use dyn_any::WasmNotSend;
use futures::future::{AbortHandle, Abortable};
pub use futures::future::AbortHandle;
use futures::future::Abortable;
use std::collections::HashMap;
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Waker};
use std::time::Duration;
#[cfg(not(target_family = "wasm"))]
pub type Task = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
@@ -18,6 +21,36 @@ pub trait Spawn {
fn spawn(&self, task: Task);
}
/// Monotonic time since an arbitrary origin.
pub trait Clock: Send + Sync {
fn now(&self) -> Duration;
}
#[cfg(not(target_family = "wasm"))]
impl Clock for std::time::Instant {
fn now(&self) -> Duration {
self.elapsed()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Scheduling {
/// How far into a frame a re-evaluation caused by finished tasks may start. `None` never defers it.
pub frame_budget: Option<Duration>,
}
impl Scheduling {
pub const UNLIMITED: Self = Self { frame_budget: None };
}
impl Default for Scheduling {
fn default() -> Self {
Self {
frame_budget: Some(Duration::from_millis(16)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, graphene_hash::CacheHash, dyn_any::DynAny)]
pub struct SourceId(pub u64);
@@ -33,15 +66,22 @@ impl SourceId {
pub type Generations = Arc<[(SourceId, u64)]>;
pub trait Runtime {
fn spawn(&self, source: SourceId, task: Task);
/// Bumps the generation of `source` once `task` finishes, unless it was aborted or the source was removed first.
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle;
}
#[derive(Clone, dyn_any::DynAny)]
pub struct RuntimeHandle(Arc<RuntimeInner>);
impl RuntimeHandle {
pub fn clock(&self) -> &dyn Clock {
&*self.0.clock
}
}
impl Runtime for RuntimeHandle {
fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task);
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
self.0.spawn(source, task)
}
}
@@ -64,28 +104,43 @@ impl graphene_hash::CacheHash for RuntimeHandle {
pub struct AsyncRuntime(Arc<RuntimeInner>);
impl AsyncRuntime {
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self {
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>, clock: Arc<dyn Clock>) -> Self {
Self(Arc::new(RuntimeInner {
generations: Mutex::default(),
sources: Mutex::default(),
next_task: AtomicU64::new(0),
bumped: AtomicBool::new(false),
spawner,
clock,
}))
}
/// Aborts the unfinished tasks of removed sources.
pub fn retain_sources(&self, live: &[SourceId]) {
let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
generations.retain(|source, _| live.contains(source));
let mut sources = self.0.lock();
for (_, state) in sources.extract_if(|source, _| !live.contains(source)) {
state.tasks.values().for_each(AbortHandle::abort);
}
for source in live {
generations.entry(*source).or_insert(0);
sources.entry(*source).or_default();
}
}
pub fn snapshot(&self) -> Generations {
let generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
let sources = self.0.lock();
let mut snapshot: Vec<_> = sources.iter().map(|(source, state)| (*source, state.generation)).collect();
snapshot.sort_unstable();
snapshot.into()
}
/// Whether any generation was bumped since the last call.
pub fn take_bumped(&self) -> bool {
self.0.bumped.swap(false, Ordering::AcqRel)
}
pub fn clock(&self) -> &dyn Clock {
&*self.0.clock
}
#[must_use]
pub fn handle(&self) -> RuntimeHandle {
RuntimeHandle(Arc::clone(&self.0))
@@ -93,25 +148,50 @@ impl AsyncRuntime {
}
impl Runtime for AsyncRuntime {
fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task);
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
self.0.spawn(source, task)
}
}
/// A live source's generation and its unfinished tasks.
#[derive(Default)]
struct SourceState {
generation: u64,
tasks: HashMap<u64, AbortHandle>,
}
struct RuntimeInner {
generations: Mutex<HashMap<SourceId, u64>>,
sources: Mutex<HashMap<SourceId, SourceState>>,
next_task: AtomicU64,
bumped: AtomicBool,
spawner: Arc<dyn Spawn + Send + Sync>,
clock: Arc<dyn Clock>,
}
impl RuntimeInner {
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) {
fn lock(&self) -> MutexGuard<'_, HashMap<SourceId, SourceState>> {
self.sources.lock().unwrap_or_else(PoisonError::into_inner)
}
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) -> AbortHandle {
let (handle, registration) = AbortHandle::new_pair();
let id = self.next_task.fetch_add(1, Ordering::Relaxed);
if let Some(state) = self.lock().get_mut(&source) {
state.tasks.insert(id, handle.clone());
}
let inner = Arc::clone(self);
self.spawner.spawn(Box::pin(async move {
task.await;
if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) {
*generation += 1;
let finished = Abortable::new(task, registration).await.is_ok();
if let Some(state) = inner.lock().get_mut(&source)
&& state.tasks.remove(&id).is_some()
&& finished
{
state.generation += 1;
inner.bumped.store(true, Ordering::Release);
}
}));
handle
}
}
@@ -167,14 +247,12 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
return state;
}
let (handle, registration) = AbortHandle::new_pair();
let slots = Arc::downgrade(&self.0);
runtime.spawn(
let handle = runtime.spawn(
source,
Box::pin(async move {
if let Ok(state) = Abortable::new(future, registration).await
&& let Some(slots) = slots.upgrade()
{
let state = future.await;
if let Some(slots) = slots.upgrade() {
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
}
}),
@@ -193,7 +271,14 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
struct NoClock;
impl Clock for NoClock {
fn now(&self) -> Duration {
Duration::ZERO
}
}
fn poll_once(task: &mut Task) -> bool {
task.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_ready()
@@ -246,7 +331,7 @@ mod tests {
#[test]
fn a_completion_bumps_its_generation() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
runtime.handle().spawn(SOURCE, Box::pin(YieldOnce(false)));
@@ -259,7 +344,7 @@ mod tests {
#[test]
fn retaining_sources_keeps_live_generations() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
spawner.drain();
@@ -274,7 +359,7 @@ mod tests {
#[test]
fn an_inline_completion_and_a_dropped_source_bump_nothing() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let slots = Slots::default();
@@ -291,7 +376,7 @@ mod tests {
#[test]
fn a_slot_serves_the_placeholder_until_the_response_lands() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = || async {
@@ -308,7 +393,7 @@ mod tests {
#[test]
fn a_blocking_spawner_lands_the_slot_in_the_same_resolve() {
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner));
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = || async {
@@ -323,7 +408,7 @@ mod tests {
#[test]
fn a_clone_keeps_the_task_running() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
let slots = Slots::default();
let fetch = || async {
YieldOnce(false).await;
@@ -340,7 +425,7 @@ mod tests {
#[test]
fn dropping_the_last_clone_aborts_the_task() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
let slots = Slots::default();
let finished = Arc::new(AtomicBool::new(false));
let fetch = || {
@@ -357,4 +442,32 @@ mod tests {
assert_eq!(spawner.drain(), 1);
assert!(!finished.load(Ordering::Relaxed));
}
#[test]
fn finished_tasks_bump_once() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
assert_eq!(spawner.drain(), 2);
assert!(runtime.take_bumped());
assert!(!runtime.take_bumped());
}
#[test]
fn aborted_tasks_bump_nothing() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE, SourceId(9)]);
runtime.spawn(SOURCE, Box::pin(std::future::pending())).abort();
let removed = runtime.spawn(SourceId(9), Box::pin(std::future::pending()));
runtime.retain_sources(&[SOURCE]);
assert!(removed.is_aborted());
assert_eq!(spawner.drain(), 2);
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
assert!(!runtime.take_bumped());
}
}
+6 -5
View File
@@ -215,13 +215,13 @@ pub trait Spawn {
/// Node-facing scope input.
pub trait Runtime {
fn spawn(&self, source: SourceId, task: Task);
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle;
}
```
`Task` is a boxed `'static` future that is `Send` on native targets only. The editor owns an `AsyncRuntime`, which updates the live sources (`retain_sources`) and takes snapshots of the generations (`snapshot`). Nodes get a cloneable `RuntimeHandle` to the same state through the `runtime` scope input, which is always present. Graphs without async nodes never read it.
The host provides the `Spawn` implementation: a tokio runtime on desktop and `spawn_local` on the web. The editor wraps it so that a finished task sets a dirty flag and calls the runtime's wake callback (a channel send on desktop, a queued runtime run on the web).
The host provides the `Spawn` implementation (a tokio runtime on desktop and `spawn_local` on the web) and a `Clock` (`Instant` on desktop, `performance.now()` on the web), which nodes can read through `RuntimeHandle::clock`. The editor wraps the spawner so that a finished task calls the runtime's wake callback (a channel send on desktop, a queued runtime run on the web). `Runtime::spawn` returns an abort handle; an aborted task bumps nothing.
Executor construction, update, and execution are plain functions, and `execute` returns `Poll<TaggedValue>`. The only await left in the editor runtime is the GPU readback for exports and the eyedropper, which can't block on the web. On desktop, the runtime runs on its own thread under `block_on`, and the readback polls the device until the copy is done.
@@ -230,10 +230,11 @@ We don't use wakers to notify the graph. A waker resumes a suspended computation
## Scheduling
- Generations are read once per evaluation. A task that finishes during an evaluation takes effect in the next one.
- The dirty flag is checked once per runtime run, so N finished tasks cause one re-render of the last viewport request.
- On recompile, `retain_sources` removes sources that no longer exist and adds new ones at generation zero. Nodes that were removed drop their slots, which aborts their tasks.
- The bump flag is checked once per runtime run, so N finished tasks cause one re-render of the last viewport request.
- The host marks frames with `begin_frame` (each animation frame on the web, the runtime thread's loop on desktop). A re-evaluation caused by finished tasks only starts while the frame is within `Scheduling::frame_budget` (16 ms by default), otherwise it waits for the next frame. Without this, a chain of immediately finishing tasks on the web would run entirely within one microtask checkpoint and the browser would never paint. Graph updates and explicit execution requests are never deferred.
- On recompile, `retain_sources` removes sources that no longer exist (aborting their tasks) and adds new ones at generation zero. Nodes that were removed drop their slots, which aborts their tasks.
The editor maps the top-level `Poll` to an `ExecutionResult`: `Pending`, `Value`, `Fallback(value, errors)`, `Error(errors)`, or `Panic`. A `Pending` result keeps the last frame and its errors on screen. An export treats `Partial` like `Pending`: it is parked and re-run on every dirty wake until the result is final, and the runtime doesn't process other requests until then.
The editor maps the top-level `Poll` to an `ExecutionResult`: `Pending`, `Value`, `Fallback(value, errors)`, `Error(errors)`, or `Panic`. A `Pending` result keeps the last frame and its errors on screen. An export treats `Partial` like `Pending`: it is parked and re-run on every wake after a bump until the result is final, and the runtime doesn't process other requests until then.
## Overhead