Compare commits

..
Author SHA1 Message Date
Dennis Kobert f484c97fc6 Add test coverage for the repeat nodes 2026-08-04 13:15:29 +02:00
Dennis Kobert 19bb36c3e0 Fix warnings 2026-08-04 13:15:28 +02:00
Dennis Kobert 479c2d2141 Address pr review 2026-08-04 13:15:28 +02:00
Dennis Kobert 11c9ffa301 Export the async-source flag from the macro and dispatch superseded type deltas in tests 2026-08-04 13:15:28 +02:00
Dennis Kobert 88795ff659 Fix wireing of async sources 2026-08-04 13:15:27 +02:00
Dennis Kobert 8b53983e9d Silence the dead-code warnings for groundwork the host wiring will use 2026-08-04 13:15:27 +02:00
Dennis Kobert fa29ddf357 Adapt the cutover to the reviewed core-types API 2026-08-04 13:15:26 +02:00
Dennis Kobert 76ec799496 Cut over to the graphene execution model 2026-08-04 13:15:21 +02:00
Dennis Kobert 7623b68318 Add the core execution types needed for the async refactor (#4390)
* Add the core execution types, the borrowed context, and the seeded u64 fx hasher

* Fix frame table key aliasing and arena handle offset truncation

* Drop arena entries in reverse allocation order and require Send + Sync payloads

* Draw arena generations from a global counter so foreign handles never upgrade

* Forward serialize through node wrappers and free abandoned frame table reservations

* Make arena generation exhaustion fallible with an unsafe counter rewind

* Guard the shared generation counter in tests and reject oversized batch ranges

* Park the arena during drop glue, guard filled batches, and normalize deserialized sources

* Make the sources fields private and normalize them on every mutation

* Remove the unused CtxSnapshot scope reconstruction
2026-08-04 13:14:09 +02:00
Dennis Kobert 837a374554 Async execution RFC (#4385)
* Draft async execution rfc

* Add note on async runtime <-> editor interaction

* Align async RFC runtime details with the implemented source wiring
2026-08-04 13:12:48 +02:00
19 changed files with 319 additions and 1095 deletions

No files matched your search

-5
View File
@@ -97,11 +97,6 @@ impl App {
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
let completion_render_sender = start_render_sender.clone();
DesktopWrapper::set_completion_notifier(move || {
let _ = completion_render_sender.try_send(());
});
Self {
render_state: None,
wgpu_context,
-4
View File
@@ -52,10 +52,6 @@ impl DesktopWrapper {
executor.execute()
}
pub fn set_completion_notifier(notifier: impl Fn() + Send + Sync + 'static) {
graphite_editor::node_graph_executor::set_completion_notifier(Arc::new(notifier));
}
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
let result = graphite_editor::node_graph_executor::run_node_graph().await;
match result {
+1 -15
View File
@@ -59,9 +59,6 @@ pub struct NodeGraphExecutor {
runtime_io: NodeRuntimeIO,
current_execution_id: u64,
futures: VecDeque<(u64, ExecutionContext)>,
/// The most recently consumed plain render execution, kept so a runtime-replayed response with the same id
/// (sent after an async source completion) finds its context again.
last_execution_context: Option<(u64, ExecutionContext)>,
node_graph_hash: u64,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
/// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in,
@@ -111,7 +108,6 @@ impl NodeGraphExecutor {
let node_executor = Self {
futures: Default::default(),
runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver),
last_execution_context: None,
node_graph_hash: 0,
current_execution_id: 0,
previous_node_to_inspect: Vec::new(),
@@ -381,19 +377,9 @@ impl NodeGraphExecutor {
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("front was just matched");
self.last_execution_context = Some((execution_id, execution_context.clone()));
execution_context
} else {
// A runtime-replayed response re-uses an already consumed id; only plain renders may re-apply.
match &self.last_execution_context {
Some((last_execution_id, execution_context)) if *last_execution_id == execution_id => {
if execution_context.export_config.is_some() || execution_context.measure_fill.is_some() {
continue;
}
execution_context.clone()
}
_ => panic!("InvalidGenerationId"),
}
panic!("InvalidGenerationId")
};
// TODO: Eventually remove this document upgrade code
+3 -78
View File
@@ -17,7 +17,7 @@ use graphene_std::ops::ConvertAsync;
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner, RuntimeHandle};
use graphene_std::transform::RenderQuality;
use graphene_std::vector::Vector;
use graphene_std::vector::style::RenderMode;
@@ -41,9 +41,8 @@ pub struct NodeRuntime {
editor_preferences: EditorPreferences,
old_graph: Option<NodeNetwork>,
update_thumbnails: bool,
#[expect(dead_code, reason = "read once the host wires a notifier onto the runtime")]
graph_runtime: Arc<DynGraphRuntime>,
/// The last plain render request, replayed when an async source completion marks the graph dirty.
last_render: Option<ExecutionRequest>,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
@@ -123,67 +122,9 @@ impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender {
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None));
#[cfg(not(target_family = "wasm"))]
pub struct TokioSpawner(Option<tokio::runtime::Runtime>);
#[cfg(not(target_family = "wasm"))]
impl TokioSpawner {
pub fn new() -> Self {
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
}
}
#[cfg(not(target_family = "wasm"))]
impl Default for TokioSpawner {
fn default() -> Self {
Self::new()
}
}
#[cfg(not(target_family = "wasm"))]
impl Spawner for TokioSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
let runtime = self.0.as_ref().expect("runtime lives until drop");
let _guard = runtime.enter();
if poll_once(&mut task) {
return true;
}
runtime.spawn(task);
false
}
}
/// Dropping a tokio runtime blocks on its tasks, which panics inside an async context; the tests drop
/// [`NodeRuntime`] from one, so shut down in the background instead.
#[cfg(not(target_family = "wasm"))]
impl Drop for TokioSpawner {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
#[cfg(target_family = "wasm")]
pub struct WasmSpawner;
#[cfg(target_family = "wasm")]
impl Spawner for WasmSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
wasm_bindgen_futures::spawn_local(task);
false
}
}
impl NodeRuntime {
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
#[cfg(not(target_family = "wasm"))]
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
#[cfg(target_family = "wasm")]
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
let spawner: Box<DynSpawner> = Box::new(NoopSpawner);
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(spawner));
let mut executor = DynamicExecutor::default();
executor.set_runtime(Arc::clone(&graph_runtime));
@@ -197,7 +138,6 @@ impl NodeRuntime {
resources: ResourceRegistry::default(),
update_thumbnails: true,
graph_runtime: Arc::clone(&graph_runtime),
last_render: None,
editor_api: PlatformEditorApi {
editor_preferences: Box::new(EditorPreferences::default()),
@@ -248,10 +188,6 @@ impl NodeRuntime {
}
let for_export = execution_request.render_config.for_export;
if !for_export {
self.last_render = Some(execution_request.clone());
}
execution = Some(request);
// If we get an export request we always execute it immedeatly otherwise it could get deduplicated
@@ -271,10 +207,6 @@ impl NodeRuntime {
eyedropper.render_config.pointer = execution.render_config.pointer;
}
if self.executor.take_dirty() && execution.is_none() {
execution = self.last_render.clone().map(GraphRuntimeRequest::ExecutionRequest);
}
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
for request in requests {
@@ -650,13 +582,6 @@ pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) {
}
}
pub fn set_completion_notifier(notifier: Arc<DynNotifier>) {
let node_runtime = NODE_RUNTIME.lock();
if let Some(node_runtime) = &*node_runtime {
node_runtime.graph_runtime.set_notifier(notifier);
}
}
impl NodeRuntime {
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
self.editor_api = PlatformEditorApi {
+31 -266
View File
@@ -369,40 +369,6 @@ impl ProtoNetwork {
nullification_node_id
}
/// Splices the selected `Ref` adapters between the consumer at `consumer_index` and its
/// producers, keeping the node vec topologically sorted and ids stable. `materialized` carries
/// the adapter ids already spliced during this update so shared producers get one adapter.
fn insert_ref_adapters(&mut self, consumer_index: usize, adapters: &[RefAdapter], materialized: &mut HashSet<NodeId>) {
let mut consumer_index = consumer_index;
for adapter in adapters {
let (_, consumer) = &self.nodes[consumer_index];
let producer = consumer.unwrap_construction_nodes()[adapter.input_index];
let mut path = consumer.original_location.path.clone();
// A path extension with a placeholder value which should not conflict with existing paths
if let Some(path) = path.as_mut() {
path.push(NodeId(11));
}
let node = ProtoNode {
construction_args: ConstructionArgs::Nodes(vec![producer]),
call_argument: concrete!(Context),
identifier: adapter.identifier.clone(),
original_location: OriginalLocation { path, ..Default::default() },
..Default::default()
};
let id = node.stable_node_id().expect("adapter nodes always produce a stable id");
if materialized.insert(id) {
self.nodes.insert(consumer_index, (id, node));
consumer_index += 1;
}
let (_, consumer) = &mut self.nodes[consumer_index];
if let ConstructionArgs::Nodes(args) = &mut consumer.construction_args {
args[adapter.input_index] = id;
}
}
}
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextModification, Option<NodeId>) {
let mut branch_dependencies = Vec::new();
let mut combined_deps = ContextModification::default();
@@ -691,39 +657,15 @@ impl TypingContext {
/// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes
/// and store them in the `inferred` field. The proto network has to be topologically sorted
/// and contain fully resolved stable node ids. When a node's inputs disagree with every
/// implementation only on `Ref`-ness, the matching lend/clone_out adapter is spliced into the
/// network and inference resumes with the adapter in place.
pub fn update(&mut self, network: &mut ProtoNetwork) -> Result<(), GraphErrors> {
let mut materialized_adapters = HashSet::new();
let mut index = 0;
while index < network.nodes.len() {
let (id, node) = &network.nodes[index];
match self.infer(*id, node) {
Ok(_) => index += 1,
Err(errors) => match self.select_ref_adapters(node) {
Some(adapters) => network.insert_ref_adapters(index, &adapters, &mut materialized_adapters),
None => return Err(errors),
},
}
/// and contain fully resolved stable node ids.
pub fn update(&mut self, network: &ProtoNetwork) -> Result<(), GraphErrors> {
for (id, node) in network.nodes.iter() {
self.infer(*id, node)?;
}
Ok(())
}
fn select_ref_adapters(&self, node: &ProtoNode) -> Option<Vec<RefAdapter>> {
let ConstructionArgs::Nodes(args) = &node.construction_args else { return None };
let inputs = args.iter().map(|id| self.inferred.get(id).map(NodeIOTypes::ty)).collect::<Option<Vec<_>>>()?;
let candidates: Vec<&NodeIOTypes> = self.lookup.get(&node.identifier)?.iter().map(|entry| &entry.io).collect();
let adapters = select_ref_adapters_over(&node.call_argument, &inputs, &candidates)?;
let constructible = adapters.iter().all(|adapter| {
self.lookup
.get(&adapter.identifier)
.is_some_and(|entries| entries.iter().any(|entry| entry.io.inputs.len() == 1 && valid_type(&inputs[adapter.input_index], &entry.io.inputs[0])))
});
constructible.then_some(adapters)
}
pub fn remove_inference(&mut self, node_id: NodeId) -> Option<NodeIOTypes> {
self.constructor.remove(&node_id);
self.inferred.remove(&node_id)
@@ -779,6 +721,33 @@ impl TypingContext {
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]);
}
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
fn valid_type(from: &Type, to: &Type) -> bool {
match (from, to) {
// Direct comparison of two concrete types.
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
// Direct comparison of two function types.
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
// This allows us to supply anything to a function that is satisfied with `()`.
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
// TODO: Add proper generic counting which is not based on the name
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
// Reject unknown type relationships.
_ => false,
}
}
// List of all implementations that match the input types
let valid_output_types = candidates
.iter()
@@ -881,87 +850,6 @@ impl TypingContext {
}
}
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
fn valid_type(from: &Type, to: &Type) -> bool {
match (from, to) {
// Direct comparison of two concrete types.
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
// Direct comparison of two function types.
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
// This allows us to supply anything to a function that is satisfied with `()`.
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
// A lend edge is substitutable exactly when the lent values are.
(Type::Ref(in1), Type::Ref(in2)) => valid_type(in1, in2),
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
// TODO: Add proper generic counting which is not based on the name
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
// Reject unknown type relationships.
_ => false,
}
}
#[derive(Clone, Debug)]
struct RefAdapter {
input_index: usize,
identifier: ProtoNodeIdentifier,
}
/// Picks the lend or clone_out adapter that reconciles a proposed edge with a wanted edge when they
/// differ only by one `Ref` layer around a concrete output.
fn ref_adapter(proposed: &Type, wanted: &Type) -> Option<ProtoNodeIdentifier> {
let (Type::Fn(_, proposed_output), Type::Fn(_, wanted_output)) = (proposed, wanted) else {
return None;
};
match (proposed_output.as_ref(), wanted_output.as_ref()) {
(Type::Ref(inner), wanted_output @ Type::Concrete(_)) if valid_type(inner, wanted_output) => Some(ProtoNodeIdentifier::new("graphene_core::debug::CloneNode")),
(proposed_output @ Type::Concrete(_), Type::Ref(inner)) if valid_type(proposed_output, inner) => Some(ProtoNodeIdentifier::new("graphene_core::memo::LendNode")),
_ => None,
}
}
/// Selects adapters for the single implementation the inputs match modulo `Ref`-ness, or `None`
/// when no or several implementations do.
fn select_ref_adapters_over(call_argument: &Type, inputs: &[Type], candidates: &[&NodeIOTypes]) -> Option<Vec<RefAdapter>> {
let mut selected = None;
for candidate in candidates {
if !valid_type(&candidate.call_argument, call_argument) || candidate.inputs.len() != inputs.len() {
continue;
}
let mut adapters = Vec::new();
let mut fits = true;
for (input_index, (proposed, wanted)) in inputs.iter().zip(&candidate.inputs).enumerate() {
if valid_type(proposed, wanted) {
continue;
}
match ref_adapter(proposed, wanted) {
Some(identifier) => adapters.push(RefAdapter { input_index, identifier }),
None => {
fits = false;
break;
}
}
}
if !fits || adapters.is_empty() {
continue;
}
if selected.is_some() {
return None;
}
selected = Some(adapters);
}
selected
}
/// Returns a list of all generic types used in the node
fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
let inputs = [&types.call_argument].into_iter().chain(types.inputs.iter().map(|x| x.nested_type()));
@@ -1273,126 +1161,3 @@ mod test {
}
}
}
#[cfg(test)]
mod ref_adapter_test {
use super::*;
fn adapter_lookup() -> &'static HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
static LOOKUP: std::sync::LazyLock<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>> = std::sync::LazyLock::new(|| {
let unused: NodeConstructor = |_| Err(ConstructionError::Arity { expected: 0, got: 0 });
[
(
ProtoNodeIdentifier::new("wants_ref"),
vec![RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), concrete!(String), vec![lend_edge_type::<String>()]),
constructor: unused,
}],
),
(
ProtoNodeIdentifier::new("wants_ref_ambiguously"),
vec![
RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), concrete!(String), vec![lend_edge_type::<String>()]),
constructor: unused,
},
RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), concrete!(f64), vec![lend_edge_type::<String>()]),
constructor: unused,
},
],
),
(
ProtoNodeIdentifier::new("graphene_core::memo::LendNode"),
vec![RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), ref_type::<String>(), vec![edge_type::<String>()]),
constructor: unused,
}],
),
]
.into_iter()
.collect()
});
&LOOKUP
}
fn string_value() -> ProtoNode {
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("lent".to_string()).into()), vec![])
}
fn consumer(identifier: &str, producer: NodeId) -> ProtoNode {
ProtoNode {
identifier: ProtoNodeIdentifier::with_owned_string(identifier.to_string()),
call_argument: concrete!(Context),
construction_args: ConstructionArgs::Nodes(vec![producer]),
..Default::default()
}
}
#[test]
fn a_ref_only_mismatch_splices_the_lend_adapter() {
let mut network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), string_value()), (NodeId(1), consumer("wants_ref", NodeId(0)))],
};
let mut typing = TypingContext::new(adapter_lookup());
typing.update(&mut network).unwrap();
assert_eq!(network.nodes.len(), 3);
let (adapter_id, adapter) = &network.nodes[1];
assert_eq!(adapter.identifier.as_str(), "graphene_core::memo::LendNode");
assert_eq!(adapter.unwrap_construction_nodes(), vec![NodeId(0)]);
assert_eq!(network.nodes[2].1.unwrap_construction_nodes(), vec![*adapter_id]);
assert_eq!(typing.type_of(*adapter_id).unwrap().return_value, ref_type::<String>());
assert_eq!(typing.type_of(NodeId(1)).unwrap().return_value, concrete!(String));
}
#[test]
fn consumers_sharing_a_producer_share_one_adapter() {
let mut network = ProtoNetwork {
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), string_value()),
(NodeId(1), consumer("wants_ref", NodeId(0))),
(NodeId(2), consumer("wants_ref", NodeId(0))),
],
};
let mut typing = TypingContext::new(adapter_lookup());
typing.update(&mut network).unwrap();
assert_eq!(network.nodes.len(), 4);
let adapters: Vec<NodeId> = network
.nodes
.iter()
.filter(|(_, node)| node.identifier.as_str() == "graphene_core::memo::LendNode")
.map(|(id, _)| *id)
.collect();
let [adapter_id] = adapters.as_slice() else {
panic!("expected exactly one shared adapter, got {adapters:?}");
};
let consumers: Vec<Vec<NodeId>> = network
.nodes
.iter()
.filter(|(_, node)| node.identifier.as_str() == "wants_ref")
.map(|(_, node)| node.unwrap_construction_nodes())
.collect();
assert_eq!(consumers, vec![vec![*adapter_id], vec![*adapter_id]]);
}
#[test]
fn an_ambiguous_ref_mismatch_stays_an_error() {
let mut network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), string_value()), (NodeId(1), consumer("wants_ref_ambiguously", NodeId(0)))],
};
let mut typing = TypingContext::new(adapter_lookup());
assert!(typing.update(&mut network).is_err());
assert_eq!(network.nodes.len(), 2, "an ambiguous mismatch must not materialize adapters");
}
}
+11 -23
View File
@@ -10,28 +10,18 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
use std::error::Error;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::time::Duration;
const SOURCE_COMPLETION_TIMEOUT: Duration = Duration::from_secs(30);
fn execute_until_final(executor: &DynamicExecutor, render_config: RenderConfig, completion: &Receiver<()>) -> Result<TaggedValue, Box<dyn Error>> {
loop {
while completion.try_recv().is_ok() {}
match executor.execute(render_config)? {
GPoll::Final(value) => return Ok(value),
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
log::warn!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
return Ok(value);
}
GPoll::Partial(_) | GPoll::Pending => {
completion
.recv_timeout(SOURCE_COMPLETION_TIMEOUT)
.map_err(|_| format!("Timed out after {}s waiting for async sources to complete", SOURCE_COMPLETION_TIMEOUT.as_secs()))?;
}
GPoll::Error(error) => return Err(format!("Node graph evaluation failed: {error:?}").into()),
fn execute_to_final(executor: &DynamicExecutor, render_config: RenderConfig) -> Result<TaggedValue, Box<dyn Error>> {
match executor.execute(render_config)? {
GPoll::Final(value) => Ok(value),
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
log::warn!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
Ok(value)
}
GPoll::Partial(_) | GPoll::Pending => Err("Node graph evaluation did not complete".into()),
GPoll::Error(error) => Err(format!("Node graph evaluation failed: {error:?}").into()),
}
}
@@ -62,7 +52,6 @@ pub fn export_document(
scale: f64,
(width, height): (Option<u32>, Option<u32>),
transparent: bool,
completion: &Receiver<()>,
) -> Result<(), Box<dyn Error>> {
// Determine export format based on file type
let export_format = match file_type {
@@ -84,7 +73,7 @@ pub fn export_document(
}
// Execute the graph
let result = execute_until_final(executor, render_config, completion)?;
let result = execute_to_final(executor, render_config)?;
// Handle the result based on output type
match result {
@@ -183,7 +172,6 @@ pub fn export_gif(
scale: f64,
(width, height): (Option<u32>, Option<u32>),
animation: AnimationParams,
completion: &Receiver<()>,
) -> Result<(), Box<dyn Error>> {
use image::codecs::gif::{GifEncoder, Repeat};
use image::{Frame, RgbaImage};
@@ -223,7 +211,7 @@ pub fn export_gif(
}
// Execute the graph for this frame
let result = execute_until_final(executor, render_config, completion)?;
let result = execute_to_final(executor, render_config)?;
// Extract RGBA data from result
let (data, img_width, img_height) = match result {
+4 -37
View File
@@ -13,7 +13,7 @@ use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::load_network;
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner, RuntimeHandle};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::error::Error;
@@ -28,35 +28,6 @@ impl NodeGraphUpdateSender for UpdateLogger {
}
}
struct TokioSpawner(Option<tokio::runtime::Runtime>);
impl TokioSpawner {
fn new() -> Result<Self, std::io::Error> {
Ok(Self(Some(tokio::runtime::Runtime::new()?)))
}
}
impl Spawner for TokioSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
let runtime = self.0.as_ref().expect("runtime lives until drop");
let _guard = runtime.enter();
if poll_once(&mut task) {
return true;
}
runtime.spawn(task);
false
}
}
/// Dropping a tokio runtime blocks on its tasks, which panics inside the async main; shut down in the background instead.
impl Drop for TokioSpawner {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
#[derive(Debug, Parser)]
#[clap(name = "graphene-cli", version)]
pub struct App {
@@ -208,11 +179,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let preferences = EditorPreferences {
max_render_region_size: EditorPreferences::default().max_render_region_size,
};
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()?) as Box<DynSpawner>));
let (completion_sender, completion_receiver) = std::sync::mpsc::channel();
graph_runtime.set_notifier(Arc::new(move || {
let _ = completion_sender.send(());
}));
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>));
let editor_api = Arc::new(PlatformEditorApi {
application_io: Some(application_io_for_api),
node_graph_message_sender: Box::new(UpdateLogger {}),
@@ -259,9 +226,9 @@ fn main() -> Result<(), Box<dyn Error>> {
// Perform export based on file type
if file_type == export::FileType::Gif {
let animation = export::AnimationParams::new(fps, frames, duration);
export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation, &completion_receiver)?;
export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation)?;
} else {
export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent, &completion_receiver)?;
export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent)?;
}
}
_ => unreachable!("All other commands should be handled before this match statement is run"),
@@ -71,9 +71,9 @@ pub struct ResolvedDocumentNodeTypesDelta {
}
impl DynamicExecutor {
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
pub fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
typing_context.update(&mut proto_network)?;
typing_context.update(&proto_network)?;
let output = proto_network.output;
let sources = proto_network.source_ids();
let tree = BorrowTree::new(proto_network, &typing_context)?;
@@ -102,9 +102,9 @@ impl DynamicExecutor {
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
#[cfg_attr(debug_assertions, inline(never))]
pub fn update(&mut self, mut proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
self.output = proto_network.output;
self.typing_context.update(&mut proto_network).map_err(|e| {
self.typing_context.update(&proto_network).map_err(|e| {
// If there is an error then get types that have been resolved before the error
let add = proto_network
.nodes
@@ -482,9 +482,7 @@ mod test {
struct InertSpawner;
impl Spawner for InertSpawner {
fn spawn(&self, _task: SourceFuture) -> bool {
false
}
fn spawn(&self, _task: SourceFuture) {}
}
#[test]
@@ -546,75 +544,4 @@ mod test {
let result: Option<GPoll<u32>> = tree.eval(NodeId(0), &ctx);
assert_eq!(result, Some(GPoll::Final(2)));
}
fn proto_node(identifier: &'static str, args: Vec<NodeId>) -> ProtoNode {
let mut node = ProtoNode::default();
node.identifier = graph_craft::ProtoNodeIdentifier::new(identifier);
node.call_argument = core_types::concrete!(core_types::context::Context);
node.construction_args = ConstructionArgs::Nodes(args);
node
}
fn string_value(value: &str) -> ProtoNode {
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(value.to_string()).into()), vec![])
}
#[test]
fn a_lend_adapter_is_spliced_between_a_value_and_a_ref_consumer() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![
(NodeId(0), string_value("lent")),
(NodeId(1), proto_node("graphene_core::debug::CloneNode", vec![NodeId(0)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("lent".to_string())));
}
#[test]
fn a_flipped_ref_parameter_gets_its_producer_lend_spliced() {
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
(NodeId(1), ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(4).into()), vec![])),
(NodeId(2), proto_node("raster_nodes::image_color_palette::ImageColorPaletteNode", vec![NodeId(0), NodeId(1)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let result: Option<GPoll<graphene_std::list::List<graphene_std::raster::color::Color>>> = executor.tree().eval(NodeId(2), &ctx);
assert!(matches!(result, Some(GPoll::Final(_))), "the palette must evaluate through the spliced lend, got {result:?}");
}
#[test]
fn a_clone_out_adapter_is_spliced_between_a_lending_producer_and_an_owned_consumer() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: vec![
(NodeId(0), string_value("memoized")),
(NodeId(1), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(0)])),
(NodeId(2), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(1)])),
(NodeId(3), proto_node("graphene_core::debug::CloneNode", vec![NodeId(2)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("memoized".to_string())));
assert_eq!(
(&executor).execute(()).unwrap(),
GPoll::Final(TaggedValue::String("memoized".to_string())),
"the frame memo lend path must replay across evaluations"
);
}
}
@@ -13,14 +13,14 @@ use graphene_std::raster::GPU;
use graphene_std::raster::color::Color;
use graphene_std::raster::*;
use graphene_std::raster::{CPU, Raster};
use graphene_std::registry::{ConstructionError, EdgeHandle, ErasedLendNode, ErasedNode, NodeIOTypes, RegistryEntry, lend_edge_type, ref_type};
use graphene_std::registry::{ConstructionError, EdgeHandle, ErasedNode, NodeIOTypes, RegistryEntry};
use graphene_std::render_node::RenderIntermediate;
use graphene_std::runtime::RuntimeHandle;
use graphene_std::transform::Footprint;
use graphene_std::uuid::NodeId;
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Context, Graphic, ProtoNodeIdentifier, SourceId, concrete, fn_type};
use node_registry_macros::{async_node, clone_node, convert_node, frame_memo_node, into_node, lend_node};
use node_registry_macros::{async_node, convert_node, into_node};
use std::collections::HashMap;
#[cfg(feature = "gpu")]
use wgpu_executor::WgpuExecutorHandle;
@@ -295,270 +295,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuExecutorHandle]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<wgpu_executor::WgpuExecutorHandle>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache]),
// ============
// REF ADAPTERS
// ============
lend_node!(()),
clone_node!(()),
frame_memo_node!(()),
lend_node!(RuntimeHandle),
clone_node!(RuntimeHandle),
frame_memo_node!(RuntimeHandle),
lend_node!(SourceId),
clone_node!(SourceId),
frame_memo_node!(SourceId),
lend_node!(bool),
clone_node!(bool),
frame_memo_node!(bool),
lend_node!(List<Artboard>),
clone_node!(List<Artboard>),
frame_memo_node!(List<Artboard>),
lend_node!(List<Graphic>),
clone_node!(List<Graphic>),
frame_memo_node!(List<Graphic>),
lend_node!(List<Vector>),
clone_node!(List<Vector>),
frame_memo_node!(List<Vector>),
lend_node!(List<Raster<CPU>>),
clone_node!(List<Raster<CPU>>),
frame_memo_node!(List<Raster<CPU>>),
lend_node!(List<Color>),
clone_node!(List<Color>),
frame_memo_node!(List<Color>),
lend_node!(Image<Color>),
clone_node!(Image<Color>),
frame_memo_node!(Image<Color>),
lend_node!(List<GradientStops>),
clone_node!(List<GradientStops>),
frame_memo_node!(List<GradientStops>),
lend_node!(List<String>),
clone_node!(List<String>),
frame_memo_node!(List<String>),
lend_node!(List<NodeId>),
clone_node!(List<NodeId>),
frame_memo_node!(List<NodeId>),
lend_node!(List<f64>),
clone_node!(List<f64>),
frame_memo_node!(List<f64>),
lend_node!(List<u8>),
clone_node!(List<u8>),
frame_memo_node!(List<u8>),
lend_node!(List<bool>),
clone_node!(List<bool>),
frame_memo_node!(List<bool>),
lend_node!(List<DAffine2>),
clone_node!(List<DAffine2>),
frame_memo_node!(List<DAffine2>),
lend_node!(List<BlendMode>),
clone_node!(List<BlendMode>),
frame_memo_node!(List<BlendMode>),
lend_node!(List<graphene_std::vector::style::GradientType>),
clone_node!(List<graphene_std::vector::style::GradientType>),
frame_memo_node!(List<graphene_std::vector::style::GradientType>),
lend_node!(List<graphene_std::vector::style::GradientSpreadMethod>),
clone_node!(List<graphene_std::vector::style::GradientSpreadMethod>),
frame_memo_node!(List<graphene_std::vector::style::GradientSpreadMethod>),
lend_node!(AttributeDyn),
clone_node!(AttributeDyn),
frame_memo_node!(AttributeDyn),
lend_node!(AttributeValueDyn),
clone_node!(AttributeValueDyn),
frame_memo_node!(AttributeValueDyn),
lend_node!(ListDyn),
clone_node!(ListDyn),
frame_memo_node!(ListDyn),
#[cfg(target_family = "wasm")]
lend_node!(CanvasHandle),
#[cfg(target_family = "wasm")]
clone_node!(CanvasHandle),
#[cfg(target_family = "wasm")]
frame_memo_node!(CanvasHandle),
lend_node!(f64),
clone_node!(f64),
frame_memo_node!(f64),
lend_node!(f32),
clone_node!(f32),
frame_memo_node!(f32),
lend_node!(u32),
clone_node!(u32),
frame_memo_node!(u32),
lend_node!(u64),
clone_node!(u64),
frame_memo_node!(u64),
lend_node!(DVec2),
clone_node!(DVec2),
frame_memo_node!(DVec2),
lend_node!(String),
clone_node!(String),
frame_memo_node!(String),
lend_node!(DAffine2),
clone_node!(DAffine2),
frame_memo_node!(DAffine2),
lend_node!(Footprint),
clone_node!(Footprint),
frame_memo_node!(Footprint),
lend_node!(RenderOutput),
clone_node!(RenderOutput),
frame_memo_node!(RenderOutput),
lend_node!(std::sync::Arc<PlatformEditorApi>),
clone_node!(std::sync::Arc<PlatformEditorApi>),
frame_memo_node!(std::sync::Arc<PlatformEditorApi>),
#[cfg(feature = "gpu")]
lend_node!(List<Raster<GPU>>),
#[cfg(feature = "gpu")]
clone_node!(List<Raster<GPU>>),
#[cfg(feature = "gpu")]
frame_memo_node!(List<Raster<GPU>>),
lend_node!(Option<f64>),
clone_node!(Option<f64>),
frame_memo_node!(Option<f64>),
lend_node!(Option<Color>),
clone_node!(Option<Color>),
frame_memo_node!(Option<Color>),
lend_node!(Graphic),
clone_node!(Graphic),
frame_memo_node!(Graphic),
lend_node!(glam::f32::Vec2),
clone_node!(glam::f32::Vec2),
frame_memo_node!(glam::f32::Vec2),
lend_node!(glam::f32::Affine2),
clone_node!(glam::f32::Affine2),
frame_memo_node!(glam::f32::Affine2),
lend_node!(graphene_std::vector::style::Stroke),
clone_node!(graphene_std::vector::style::Stroke),
frame_memo_node!(graphene_std::vector::style::Stroke),
lend_node!(graphene_std::text::Font),
clone_node!(graphene_std::text::Font),
frame_memo_node!(graphene_std::text::Font),
lend_node!(List<BrushStroke>),
clone_node!(List<BrushStroke>),
frame_memo_node!(List<BrushStroke>),
lend_node!(DocumentNode),
clone_node!(DocumentNode),
frame_memo_node!(DocumentNode),
lend_node!(graphene_std::ContextModification),
clone_node!(graphene_std::ContextModification),
frame_memo_node!(graphene_std::ContextModification),
lend_node!(graphene_std::transform::Footprint),
clone_node!(graphene_std::transform::Footprint),
frame_memo_node!(graphene_std::transform::Footprint),
lend_node!(Box<graphene_std::vector::VectorModification>),
clone_node!(Box<graphene_std::vector::VectorModification>),
frame_memo_node!(Box<graphene_std::vector::VectorModification>),
lend_node!(graphene_std::blending::BlendMode),
clone_node!(graphene_std::blending::BlendMode),
frame_memo_node!(graphene_std::blending::BlendMode),
lend_node!(graphene_std::raster::LuminanceCalculation),
clone_node!(graphene_std::raster::LuminanceCalculation),
frame_memo_node!(graphene_std::raster::LuminanceCalculation),
lend_node!(graphene_std::vector::QRCodeErrorCorrectionLevel),
clone_node!(graphene_std::vector::QRCodeErrorCorrectionLevel),
frame_memo_node!(graphene_std::vector::QRCodeErrorCorrectionLevel),
lend_node!(graphene_std::extract_xy::XY),
clone_node!(graphene_std::extract_xy::XY),
frame_memo_node!(graphene_std::extract_xy::XY),
lend_node!(graphene_std::text_nodes::StringCapitalization),
clone_node!(graphene_std::text_nodes::StringCapitalization),
frame_memo_node!(graphene_std::text_nodes::StringCapitalization),
lend_node!(graphene_std::raster::RedGreenBlue),
clone_node!(graphene_std::raster::RedGreenBlue),
frame_memo_node!(graphene_std::raster::RedGreenBlue),
lend_node!(graphene_std::raster::RedGreenBlueAlpha),
clone_node!(graphene_std::raster::RedGreenBlueAlpha),
frame_memo_node!(graphene_std::raster::RedGreenBlueAlpha),
lend_node!(graphene_std::animation::RealTimeMode),
clone_node!(graphene_std::animation::RealTimeMode),
frame_memo_node!(graphene_std::animation::RealTimeMode),
lend_node!(graphene_std::raster::NoiseType),
clone_node!(graphene_std::raster::NoiseType),
frame_memo_node!(graphene_std::raster::NoiseType),
lend_node!(graphene_std::raster::FractalType),
clone_node!(graphene_std::raster::FractalType),
frame_memo_node!(graphene_std::raster::FractalType),
lend_node!(graphene_std::raster::CellularDistanceFunction),
clone_node!(graphene_std::raster::CellularDistanceFunction),
frame_memo_node!(graphene_std::raster::CellularDistanceFunction),
lend_node!(graphene_std::raster::CellularReturnType),
clone_node!(graphene_std::raster::CellularReturnType),
frame_memo_node!(graphene_std::raster::CellularReturnType),
lend_node!(graphene_std::raster::DomainWarpType),
clone_node!(graphene_std::raster::DomainWarpType),
frame_memo_node!(graphene_std::raster::DomainWarpType),
lend_node!(graphene_std::raster::RelativeAbsolute),
clone_node!(graphene_std::raster::RelativeAbsolute),
frame_memo_node!(graphene_std::raster::RelativeAbsolute),
lend_node!(graphene_std::raster::SelectiveColorChoice),
clone_node!(graphene_std::raster::SelectiveColorChoice),
frame_memo_node!(graphene_std::raster::SelectiveColorChoice),
lend_node!(graphene_std::vector::misc::GridType),
clone_node!(graphene_std::vector::misc::GridType),
frame_memo_node!(graphene_std::vector::misc::GridType),
lend_node!(graphene_std::vector::misc::ArcType),
clone_node!(graphene_std::vector::misc::ArcType),
frame_memo_node!(graphene_std::vector::misc::ArcType),
lend_node!(graphene_std::vector::misc::RowsOrColumns),
clone_node!(graphene_std::vector::misc::RowsOrColumns),
frame_memo_node!(graphene_std::vector::misc::RowsOrColumns),
lend_node!(graphene_std::vector::misc::MergeByDistanceAlgorithm),
clone_node!(graphene_std::vector::misc::MergeByDistanceAlgorithm),
frame_memo_node!(graphene_std::vector::misc::MergeByDistanceAlgorithm),
lend_node!(graphene_std::vector::misc::ExtrudeJoiningAlgorithm),
clone_node!(graphene_std::vector::misc::ExtrudeJoiningAlgorithm),
frame_memo_node!(graphene_std::vector::misc::ExtrudeJoiningAlgorithm),
lend_node!(graphene_std::vector::misc::PointSpacingType),
clone_node!(graphene_std::vector::misc::PointSpacingType),
frame_memo_node!(graphene_std::vector::misc::PointSpacingType),
lend_node!(graphene_std::vector::style::StrokeCap),
clone_node!(graphene_std::vector::style::StrokeCap),
frame_memo_node!(graphene_std::vector::style::StrokeCap),
lend_node!(graphene_std::vector::style::StrokeJoin),
clone_node!(graphene_std::vector::style::StrokeJoin),
frame_memo_node!(graphene_std::vector::style::StrokeJoin),
lend_node!(graphene_std::vector::style::StrokeAlign),
clone_node!(graphene_std::vector::style::StrokeAlign),
frame_memo_node!(graphene_std::vector::style::StrokeAlign),
lend_node!(graphene_std::vector::style::PaintOrder),
clone_node!(graphene_std::vector::style::PaintOrder),
frame_memo_node!(graphene_std::vector::style::PaintOrder),
lend_node!(graphene_std::vector::style::GradientType),
clone_node!(graphene_std::vector::style::GradientType),
frame_memo_node!(graphene_std::vector::style::GradientType),
lend_node!(graphene_std::vector::style::GradientSpreadMethod),
clone_node!(graphene_std::vector::style::GradientSpreadMethod),
frame_memo_node!(graphene_std::vector::style::GradientSpreadMethod),
lend_node!(Option<DAffine2>),
clone_node!(Option<DAffine2>),
frame_memo_node!(Option<DAffine2>),
lend_node!(graphene_std::transform::ReferencePoint),
clone_node!(graphene_std::transform::ReferencePoint),
frame_memo_node!(graphene_std::transform::ReferencePoint),
lend_node!(graphene_std::vector::misc::CentroidType),
clone_node!(graphene_std::vector::misc::CentroidType),
frame_memo_node!(graphene_std::vector::misc::CentroidType),
lend_node!(graphene_std::vector::misc::BooleanOperation),
clone_node!(graphene_std::vector::misc::BooleanOperation),
frame_memo_node!(graphene_std::vector::misc::BooleanOperation),
lend_node!(graphene_std::text::TextAlign),
clone_node!(graphene_std::text::TextAlign),
frame_memo_node!(graphene_std::text::TextAlign),
lend_node!(graphene_std::transform::ScaleType),
clone_node!(graphene_std::transform::ScaleType),
frame_memo_node!(graphene_std::transform::ScaleType),
lend_node!(graphene_std::vector::misc::InterpolationDistribution),
clone_node!(graphene_std::vector::misc::InterpolationDistribution),
frame_memo_node!(graphene_std::vector::misc::InterpolationDistribution),
lend_node!(RenderIntermediate),
clone_node!(RenderIntermediate),
frame_memo_node!(RenderIntermediate),
lend_node!(wgpu_executor::WgpuExecutorHandle),
clone_node!(wgpu_executor::WgpuExecutorHandle),
frame_memo_node!(wgpu_executor::WgpuExecutorHandle),
lend_node!(Option<wgpu_executor::WgpuExecutorHandle>),
clone_node!(Option<wgpu_executor::WgpuExecutorHandle>),
frame_memo_node!(Option<wgpu_executor::WgpuExecutorHandle>),
lend_node!(wgpu_executor::WgpuPipelineCache),
clone_node!(wgpu_executor::WgpuPipelineCache),
frame_memo_node!(wgpu_executor::WgpuPipelineCache),
];
// =============
// CONVERT NODES
@@ -750,67 +486,7 @@ mod node_registry_macros {
};
}
macro_rules! lend_node {
($type:ty) => {
(
ProtoNodeIdentifier::new("graphene_core::memo::LendNode"),
RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), ref_type::<$type>(), vec![fn_type!(Context, $type)]),
constructor: |inputs| {
if inputs.len() != 1 {
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let node = graphene_core::memo::LendNode::new(inputs.next().unwrap().downcast::<$type>()?);
Ok(EdgeHandle::new_ref(std::sync::Arc::new(node) as std::sync::Arc<ErasedLendNode<$type>>))
},
},
)
};
}
macro_rules! clone_node {
($type:ty) => {
(
ProtoNodeIdentifier::new("graphene_core::debug::CloneNode"),
RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), concrete!($type), vec![lend_edge_type::<$type>()]),
constructor: |inputs| {
if inputs.len() != 1 {
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let node = graphene_core::debug::CloneNode::new(inputs.next().unwrap().downcast_lend::<$type>()?);
Ok(EdgeHandle::new(std::sync::Arc::new(node) as std::sync::Arc<ErasedNode<$type>>))
},
},
)
};
}
macro_rules! frame_memo_node {
($type:ty) => {
(
ProtoNodeIdentifier::new("graphene_core::memo::FrameMemoNode"),
RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), ref_type::<$type>(), vec![fn_type!(Context, $type)]),
constructor: |inputs| {
if inputs.len() != 1 {
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let node = graphene_core::memo::FrameMemoNode::new(inputs.next().unwrap().downcast::<$type>()?);
Ok(EdgeHandle::new_ref(std::sync::Arc::new(node) as std::sync::Arc<ErasedLendNode<$type>>))
},
},
)
};
}
pub(crate) use async_node;
pub(crate) use clone_node;
pub(crate) use convert_node;
pub(crate) use frame_memo_node;
pub(crate) use into_node;
pub(crate) use lend_node;
}
@@ -88,12 +88,8 @@ pub fn edge_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(T)))
}
pub fn ref_type<T: 'static>() -> Type {
Type::Ref(Box::new(concrete!(T)))
}
pub fn lend_edge_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(ref_type::<T>()))
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Ref(Box::new(concrete!(T)))))
}
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
+25 -96
View File
@@ -16,8 +16,7 @@ pub type DynRuntime = dyn Runtime + Send + Sync;
pub type DynRuntime = dyn Runtime;
pub trait Runtime {
/// Returns true when the future completed during the call, so its result is already observable.
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool;
fn spawn(&self, source: SourceId, future: SourceFuture);
}
#[derive(Clone)]
@@ -41,14 +40,7 @@ impl graphene_hash::CacheHash for RuntimeHandle {
}
pub trait Spawner {
/// Returns true when the task completed during the call, so its result is already observable.
fn spawn(&self, task: SourceFuture) -> bool;
}
/// Polls `task` once with a no-op waker, returning true if it completed.
pub fn poll_once(task: &mut SourceFuture) -> bool {
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
task.as_mut().poll(&mut context).is_ready()
fn spawn(&self, task: SourceFuture);
}
#[cfg(not(target_family = "wasm"))]
@@ -62,7 +54,7 @@ pub type DynNotifier = dyn Fn() + Send + Sync;
pub type DynNotifier = dyn Fn();
impl<S: Spawner + ?Sized> Spawner for Box<S> {
fn spawn(&self, task: SourceFuture) -> bool {
fn spawn(&self, task: SourceFuture) {
(**self).spawn(task)
}
}
@@ -71,12 +63,11 @@ impl<S: Spawner + ?Sized> Spawner for Box<S> {
pub struct NoopSpawner;
impl Spawner for NoopSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
fn spawn(&self, mut task: SourceFuture) {
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
if task.as_mut().poll(&mut context).is_pending() {
log::warn!("async source is not immediately ready and no host spawner is wired; the task is dropped");
}
log::warn!("async source is not immediately ready and no host spawner is wired; the task is dropped");
false
}
}
@@ -141,26 +132,21 @@ impl<S> GraphRuntime<S> {
}
impl<S: Spawner> Runtime for GraphRuntime<S> {
fn spawn(&self, source: SourceId, mut future: SourceFuture) -> bool {
fn spawn(&self, source: SourceId, future: SourceFuture) {
let generations = Arc::clone(&self.generations);
let dirty = Arc::clone(&self.dirty);
let notifier = Arc::clone(&self.notifier);
let mut first = true;
self.spawner.spawn(Box::pin(std::future::poll_fn(move |task_context| {
let poll = future.as_mut().poll(task_context);
if poll.is_ready() && !first {
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(generation) = generations.get_mut(&source) {
*generation += 1;
dirty.store(true, Ordering::Release);
drop(generations);
let notifier = Arc::clone(&notifier.lock().unwrap_or_else(PoisonError::into_inner));
notifier();
}
self.spawner.spawn(Box::pin(async move {
future.await;
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(generation) = generations.get_mut(&source) {
*generation += 1;
dirty.store(true, Ordering::Release);
drop(generations);
let notifier = Arc::clone(&notifier.lock().unwrap_or_else(PoisonError::into_inner));
notifier();
}
first = false;
poll
})))
}));
}
}
@@ -181,9 +167,8 @@ mod tests {
}
impl Runtime for MockRuntime {
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool {
fn spawn(&self, source: SourceId, future: SourceFuture) {
self.futures.lock().unwrap().push((source, future));
false
}
}
@@ -207,34 +192,11 @@ mod tests {
}
impl Spawner for CollectSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
fn spawn(&self, task: SourceFuture) {
self.tasks.lock().unwrap().push(task);
false
}
}
struct YieldOnce(bool);
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, task_context: &mut std::task::Context<'_>) -> std::task::Poll<()> {
if self.0 {
return std::task::Poll::Ready(());
}
self.0 = true;
task_context.waker().wake_by_ref();
std::task::Poll::Pending
}
}
fn yield_once() -> YieldOnce {
YieldOnce(false)
}
impl CollectSpawner {
fn drain(&self) -> usize {
let tasks = std::mem::take(&mut *self.tasks.lock().unwrap());
@@ -451,7 +413,7 @@ mod tests {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
assert_eq!(runtime.snapshot(), vec![(7, 0)], "no bump before the future completes");
assert!(!runtime.take_dirty());
@@ -472,7 +434,7 @@ mod tests {
observed.store(dirty_at_notify.load(Ordering::Acquire), Ordering::Relaxed);
}));
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
assert_eq!(runtime.spawner().drain(), 1);
assert!(observed_dirty.load(Ordering::Relaxed), "the notifier must observe the dirty flag already set");
}
@@ -485,7 +447,7 @@ mod tests {
let flag = Arc::clone(&notified);
runtime.set_notifier(Arc::new(move || flag.store(true, Ordering::Relaxed)));
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
runtime.retain_sources(&[]);
assert_eq!(runtime.spawner().drain(), 1);
assert!(!notified.load(Ordering::Relaxed));
@@ -496,7 +458,7 @@ mod tests {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
runtime.retain_sources(&[]);
assert_eq!(runtime.spawner().drain(), 1);
@@ -508,7 +470,7 @@ mod tests {
fn retain_sources_preserves_live_generations() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
runtime.spawner().drain();
runtime.retain_sources(&[7, 9]);
@@ -520,42 +482,9 @@ mod tests {
#[node_macro::node(category(""))]
async fn epilogue_double(_: impl Ctx, value: f64) -> f64 {
yield_once().await;
value * 2.
}
#[node_macro::node(category(""))]
async fn inline_double(_: impl Ctx, value: f64) -> f64 {
value * 2.
}
#[test]
fn an_immediately_ready_task_completes_inline_without_invalidating() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
assert!(Runtime::spawn(&runtime, 7, Box::pin(async {})));
assert_eq!(runtime.spawner().drain(), 0);
assert_eq!(runtime.snapshot(), vec![(7, 0)], "inline completion must not bump the generation");
assert!(!runtime.take_dirty());
}
#[test]
fn an_immediately_ready_kernel_returns_final_on_the_first_eval() {
let arena = Arena::new(64).unwrap();
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[13]);
let graph = InlineDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(13u64));
let snapshot = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
let ctx = ContextImpl::root(&scope);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
assert!(!runtime.take_dirty());
assert_eq!(runtime.snapshot(), vec![(13, 0)]);
assert_eq!(runtime.spawner().drain(), 0);
}
#[test]
fn a_source_slot_lands_through_the_runtime_while_downstream_keys_invalidate() {
let arena = Arena::new(64).unwrap();
+20 -111
View File
@@ -633,27 +633,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
]);
}
let has_lend = parsed.fields.iter().any(|field| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. })));
let declared_arena_lifetime = ctx_param.and_then(|ctx_param| {
ctx_param.bounds.iter().find_map(|bound| {
let TypeParamBound::Trait(trait_bound) = bound else { return None };
let segment = trait_bound.path.segments.last()?;
if segment.ident != "ExtractArena" {
return None;
}
let PathArguments::AngleBracketed(args) = &segment.arguments else { return None };
match args.args.first() {
Some(GenericArgument::Lifetime(lifetime)) => Some(lifetime.clone()),
_ => None,
}
})
});
let introduced_lend_lifetime = (has_lend && declared_arena_lifetime.is_none()).then(|| Lifetime::new("'__lend", proc_macro2::Span::call_site()));
let lend_lifetime = declared_arena_lifetime.or_else(|| introduced_lend_lifetime.clone());
if let Some(lifetime) = &introduced_lend_lifetime {
ctx_bounds.push(quote!(#core_types::context::ExtractArena<ArenaRef = &#lifetime #core_types::arena::Arena>));
}
let derives = ctx_param.is_some_and(|ctx_param| {
ctx_param.bounds.iter().any(|bound| match bound {
TypeParamBound::Trait(trait_bound) => trait_bound.path.segments.last().is_some_and(|segment| segment.ident == "DeriveCtx"),
@@ -676,9 +655,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
if ctx_param.is_none() {
generics.push(ctx_generic);
}
if let Some(lifetime) = &introduced_lend_lifetime {
generics.insert(0, quote!(#lifetime));
}
let fn_name = &parsed.fn_name;
let mod_name = format_ident!("_{}_mod", parsed.mod_name);
@@ -726,7 +702,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let kernel_params = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).map(|field| {
let pat = &field.pat_ident;
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(#pat: &#ty),
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#pat: #ty),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) if raw_lazy => {
let bound = lazy_bound(output_type);
@@ -740,10 +715,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
});
let node_bounds = regular_fields.iter().zip(&node_generics).map(|(field, node_generic)| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => {
let lifetime = lend_lifetime.as_ref().expect("lend fields imply the lend lifetime");
quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = &#lifetime #ty>)
}
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = #ty>),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
let bound = lazy_bound(output_type);
@@ -751,23 +722,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
}
});
let mut lend_outlives: Vec<TokenStream2> = regular_fields
.iter()
.filter_map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => {
let lifetime = lend_lifetime.as_ref().expect("lend fields imply the lend lifetime");
Some(quote!(#ty: #lifetime))
}
_ => None,
})
.collect();
if let Type::Reference(reference) = &trait_output
&& let Some(lifetime) = &reference.lifetime
{
let inner = &reference.elem;
lend_outlives.push(quote!(#inner: #lifetime));
}
let mut async_bounds = match (async_fn, future_kernel) {
(false, false) => Vec::new(),
(false, true) => vec![quote!(#trait_output: Clone)],
@@ -978,22 +932,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
},
_ => quote!(#core_types::gpoll::GPoll::Final(__future.await)),
};
let spawn_tail = |completion: TokenStream2, fallback: TokenStream2| {
quote! {
self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, None);
let __slot = std::sync::Arc::clone(&self.slot);
if _runtime.0.spawn(_source, Box::pin(async move {
let __value = #completion;
__slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, Some(__value));
})) {
let __entries = self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(Some(__value)) = __entries.get(&__key) {
return __cell.merge(__value.clone());
}
}
#fallback
}
};
let eval_tail = match (async_fn, future_kernel) {
(false, false) => lift,
(true, _) => {
@@ -1004,12 +942,17 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
.chain(data_names.iter().map(|name| quote!(self.#name.clone())))
.chain(kernel_value_names.iter().map(|name| quote!(#name.clone())));
let completion = future_completion(&parsed.output_type);
let tail = spawn_tail(completion, inflight.clone());
quote! {
#slot_check
self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, None);
let __slot = std::sync::Arc::clone(&self.slot);
#(#snapshot_binding)*
let __future = self::#fn_name(#(#future_args),*);
#tail
_runtime.0.spawn(_source, Box::pin(async move {
let __value = #completion;
__slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, Some(__value));
}));
#inflight
}
}
(false, true) => {
@@ -1034,12 +977,17 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
_ => unreachable!("guarded by future_kernel"),
};
let completion = future_completion(&payload);
let tail = spawn_tail(completion, spawn_return);
quote! {
#slot_check
#placeholder_binding
#acquire
#tail
self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, None);
let __slot = std::sync::Arc::clone(&self.slot);
_runtime.0.spawn(_source, Box::pin(async move {
let __value = #completion;
__slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, Some(__value));
}));
#spawn_return
}
}
};
@@ -1053,7 +1001,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
impl<#(#generics,)* #(#node_generics,)*> #core_types::node::Node<#ctx_ident> for #mod_name::#struct_name<#(#struct_type_params,)*>
where
#(#node_bounds,)*
#(#lend_outlives,)*
#(#clampable_bounds,)*
#(#async_bounds,)*
#(#where_predicates,)*
@@ -1228,60 +1175,22 @@ fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic
return quote!();
}
let ref_output_inner = match slot_value_type(&parsed.output_type) {
Type::Reference(reference) => Some((*reference.elem).clone()),
_ => None,
};
if let Some(inner) = &ref_output_inner {
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
let open_generics = parsed.fn_generics.iter().filter_map(|param| match param {
GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() => Some(&type_param.ident),
_ => None,
});
if open_generics.into_iter().any(|generic| type_contains_ident(inner, generic)) {
return quote!();
}
}
let fn_name = &parsed.fn_name;
let entries_name = format_ident!("{}_entries", fn_name);
let arity = regular_fields.len();
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
let lend_flags: Vec<bool> = regular_fields
.iter()
.map(|field| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. })))
.collect();
let entries = rows.iter().map(|row| {
let input_types = row.iter().zip(&lend_flags).map(|(ty, lend)| match lend {
true => quote!(gcore::registry::lend_edge_type::<#ty>()),
false => quote!(gcore::registry::edge_type::<#ty>()),
});
let edge_types = row.iter().zip(&lend_flags).map(|(ty, lend)| match lend {
true => quote!(gcore::registry::SharedEdge<gcore::registry::ErasedLendNode<#ty>>),
false => quote!(gcore::registry::SharedEdge<gcore::registry::ErasedNode<#ty>>),
});
let types = row.iter();
let edge_types = row.iter().map(|ty| quote!(gcore::registry::SharedEdge<gcore::registry::ErasedNode<#ty>>));
let output = quote!(<#struct_name<#(#edge_types),*> as gcore::node::Node<gcore::context::ContextImpl<'static>>>::Output);
let (io_output, construct) = match &ref_output_inner {
Some(inner) => (
quote!(gcore::registry::ref_type::<#inner>()),
quote!(Ok(gcore::registry::EdgeHandle::new_ref(::std::sync::Arc::new(#struct_name::new(#(#names),*)) as ::std::sync::Arc<gcore::registry::ErasedLendNode<#inner>>))),
),
None => (
quote!(gcore::concrete!(#output)),
quote!(Ok(gcore::registry::EdgeHandle::new(::std::sync::Arc::new(#struct_name::new(#(#names),*)) as ::std::sync::Arc<gcore::registry::ErasedNode<#output>>))),
),
};
let downcasts = names.iter().zip(row.iter()).zip(&lend_flags).map(|((name, ty), lend)| match lend {
true => quote!(let #name = inputs.next().unwrap().downcast_lend::<#ty>()?;),
false => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
});
let downcasts = names.iter().zip(row.iter()).map(|(name, ty)| quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;));
quote! {
gcore::registry::RegistryEntry {
io: gcore::registry::NodeIOTypes::new(
gcore::concrete!(gcore::context::ContextImpl<'static>),
#io_output,
vec![#(#input_types),*],
gcore::concrete!(#output),
vec![#(gcore::registry::edge_type::<#types>()),*],
),
constructor: |inputs| {
if inputs.len() != #arity {
@@ -1289,7 +1198,7 @@ fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
#construct
Ok(gcore::registry::EdgeHandle::new(::std::sync::Arc::new(#struct_name::new(#(#names),*)) as ::std::sync::Arc<gcore::registry::ErasedNode<#output>>))
},
}
}
-15
View File
@@ -240,8 +240,6 @@ impl Parse for NumberRange {
#[derive(Clone, Debug)]
pub struct RegularParsedField {
pub ty: Type,
/// The original reference tokens when the parameter was written `&T`; `ty` holds the peeled inner type.
pub lend: Option<syn::TypeReference>,
pub exposed: bool,
pub value_source: ParsedValueSource,
pub number_soft_min: Option<NumberBound>,
@@ -906,11 +904,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
.transpose()?
.unwrap_or_default();
let (ty, lend) = match ty {
Type::Reference(reference) => ((*reference.elem).clone(), Some(reference)),
ty => (ty, None),
};
// Error if a float literal is given for a bound on an integer-typed field
if is_integer_type(&ty) {
let bound_attrs = [
@@ -943,7 +936,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
number_hard_max,
number_mode_range,
ty,
lend,
value_source,
implementations,
gpu_image,
@@ -1056,7 +1048,6 @@ impl ParsedNodeFn {
widget_override: ParsedWidgetOverride::Hidden,
ty: ParsedFieldType::Regular(RegularParsedField {
ty,
lend: None,
exposed: false,
value_source,
number_soft_min: None,
@@ -1227,7 +1218,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64),
exposed: false,
value_source: ParsedValueSource::None,
@@ -1318,7 +1308,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(DVec2),
exposed: false,
value_source: ParsedValueSource::None,
@@ -1391,7 +1380,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64),
exposed: false,
value_source: ParsedValueSource::Default(quote!(50.)),
@@ -1462,7 +1450,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64),
exposed: false,
value_source: ParsedValueSource::None,
@@ -1545,7 +1532,6 @@ mod tests {
description: String::from("b"),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64),
exposed: false,
value_source: ParsedValueSource::None,
@@ -1631,7 +1617,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(String),
exposed: true,
value_source: ParsedValueSource::None,
@@ -232,7 +232,6 @@ impl PerPixelAdjustCodegen<'_> {
widget_override: Default::default(),
ty: ParsedFieldType::Regular(RegularParsedField {
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
lend: None,
exposed: true,
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))),
number_soft_min: None,
-25
View File
@@ -12,7 +12,6 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
validate_min_max,
validate_range_slider_bounds,
validate_async_source,
validate_lend_fields,
];
for validator in validators {
@@ -64,30 +63,6 @@ fn validate_async_source(parsed: &ParsedNodeFn) {
}
}
fn validate_lend_fields(parsed: &ParsedNodeFn) {
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
for field in &parsed.fields {
let ParsedFieldType::Regular(RegularParsedField { lend: Some(reference), .. }) = &field.ty else {
continue;
};
if let Some(mutability) = &reference.mutability {
emit_error!(mutability.span(), "reference parameters are read-only lends; `&mut` is not supported");
}
if let Some(lifetime) = &reference.lifetime {
emit_error!(lifetime.span(), "reference parameters use the eval lifetime implicitly; write a bare `&T`");
}
if field.is_data_field {
emit_error!(field.pat_ident.span(), "`#[data]` fields are node-resident state and cannot be references");
}
if parsed.is_async || future_kernel {
emit_error!(
field.pat_ident.span(),
"source kernels move their inputs into the spawned task, so they cannot take reference parameters"
);
}
}
}
fn validate_min_max(parsed: &ParsedNodeFn) {
for field in &parsed.fields {
if let ParsedField {
+2 -2
View File
@@ -29,8 +29,8 @@ fn unwrap_option<T: Default>(_: impl Ctx, #[implementations(Option<f64>, Option<
input.unwrap_or_default()
}
/// Clones the value borrowed from a lending edge. Doubles as the checker-inserted clone-out adapter.
/// Meant for debugging purposes, not general use. Clones the input value.
#[node_macro::node(category("Debug"))]
fn clone<T: Clone>(_: impl Ctx, #[implementations(List<Raster<CPU>>)] value: &T) -> T {
fn clone<'i, T: Clone + 'i>(_: impl Ctx, #[implementations(&List<Raster<CPU>>)] value: &'i T) -> T {
value.clone()
}
+1 -7
View File
@@ -1,5 +1,5 @@
use core_types::arena::{Arena, ArenaCell};
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll, ExtractArena};
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll};
use core_types::frame_table::{FrameTable, Lookup};
use core_types::gpoll::{Extent, Finality, GPoll, Interrupt};
use core_types::graphene_hash::CacheHash;
@@ -102,12 +102,6 @@ pub fn park<T: Send + Sync>(arena: &Arena, result: GPoll<T>) -> GPoll<&T> {
}
}
/// Adapts an owned edge to a lending one by parking each result in the eval arena.
#[node_macro::node(category(""), path(graphene_core::memo), skip_impl)]
fn lend<'e, T: Send + Sync>(ctx: impl Ctx + ExtractArena<'e>, value: T) -> GPoll<&'e T> {
park(ctx.arena(), GPoll::Final(value))
}
type MonitorValue<T> = Arc<Mutex<Option<Arc<IORecord<CtxSnapshot, T>>>>>;
/// The Monitor node is used by the editor to access the data flowing through it.
@@ -6,7 +6,7 @@ use raster_types::{CPU, Raster};
#[node_macro::node(category("Color"))]
fn image_color_palette(
_: impl Ctx,
image: &List<Raster<CPU>>,
image: List<Raster<CPU>>,
#[default(4)]
#[hard(1..)]
count: u32,
+212
View File
@@ -0,0 +1,212 @@
# Summary
Replace the boxed-future execution model with synchronous, poll-based evaluation. Nodes return a `GPoll<T>` state instead of futures. Async work runs to completion on an executor outside the graph; completion bumps a per-source generation counter which is injected into the context and hashed by memo nodes, so cache invalidation along the downstream cone is an ordinary cache miss. Asynchrony is modeled as a context feature, reusing the fine-grained context nullification pass to scope invalidation. All mechanisms described here have been validated in a standalone prototype; figures quoted below are measurements from it.
# Motivation
In the current model every node's `eval` returns a `DynFuture` (`Pin<Box<dyn Future>>`), even for trivial arithmetic, and the whole graph evaluation is one large future driven per render request. Costs:
- **Allocation per edge**: every eval boxes a future; pure nodes pay async machinery they never use.
- **No progressive rendering**: one slow async operation stalls the entire evaluation; there is no placeholder or partial result.
- **Wasted evaluations**: driving async work through graph re-evaluation costs a full traversal per poll.
- **Poor error semantics**: errors propagate as panics caught with `catch_unwind` at the root.
- **Blocks the precompiled future**: emitting the graph as Rust source running against a minimal runtime cannot be built on a box per edge.
# Guide-level explanation
## Evaluation states
Node evaluation is synchronous and always returns immediately:
```rs
enum GPoll<T> {
/// Waiting on at least one future, with no placeholder to compute with.
Pending,
Final(T),
/// Computed from provisional data; recomputed once the source generation bumps.
Partial(T),
/// An error occurred; the boxed value is a stand-in, downstream keeps computing.
Fallback(Box<(T, GraphError)>),
/// An error occurred and no stand-in exists; the cone cannot compute this frame.
Error(Box<GraphError>),
}
```
The variants split into "has a value" (`Final`, `Partial`, `Fallback`) and "has no value" (`Pending`, `Error`). Value-carrying statuses flow through computation: a node receiving `Partial` computes normally and downgrades its own output; a node receiving `Fallback` computes on the stand-in and forwards the error. Valueless statuses stop the cone for this frame. Statuses combine with a meet (`Final ∧ Final = Final`, anything else drags the result down; `Error` dominates `Pending`).
`meet(Partial, Fallback)` collapses to `Fallback`, which alone would make an error from a still-incomplete source indistinguishable from a final document error. Finality therefore rides a separate `Finality` (`AllFinal ∧ Partial`) tracked beside the status rather than a sixth variant, so the executor can withhold provisional errors from the document without widening `GPoll`.
Layout: one tag plus one payload word for pointer-sized values (`GPoll<Arc<T>>` is 16 bytes); the stand-in and its error share a box, and `Error` boxes the error alone, so it crosses node boundaries without reallocating. Progress percentages are deliberately not part of the value: they change at high frequency and must not invalidate the dataflow, so they ride the monitor side channel.
`GraphError` records the path from the error source upward as a list of input indices (names are ambiguous; a node can have two inputs of the same type). Its kind is structured: `ErrorKind::Node(&'static str)` for node-declared failures versus operational failures such as `ErrorKind::ArenaExhausted`, which the executor answers by resetting or growing the arena and re-rendering, never by reporting a document error.
## Writing nodes
Node authors write plain Rust functions; the macro generates the node struct, the trait impl, and all status plumbing. The function must compile standalone; the generated eval calls it. Four return tiers:
- `-> T`: pure kernel over evaluated inputs. The macro meets input statuses; the author never sees them.
- `-> Result<T, Interrupt>`: for kernels that evaluate lazy inputs themselves or fail. `Interrupt = Pending | Error(Box<GraphError>)`, with `From<GraphError>`, so semantic errors and input bail-outs share the `?` operator.
- `-> Result<T, (T, GraphError)>`: an error with an explicit stand-in value.
- `-> GPoll<T>`: full manual control (memo-class nodes).
Lazy inputs (`content: impl Node<Output = T>`) expose `eval(ctx) -> Result<T, Interrupt>`. The status mapping is the meet in imperative form: `Final(v)` is `Ok(v)`; `Partial(v)` and `Fallback(v, e)` are also `Ok(v)`, recording partiality or the first error in a status cell owned by the generated eval (a stack-local threaded by reference into the input handles); `Pending` and `Error` are `Err(Interrupt::...)`, and the kernel bails with `?`, the only thing it could do without a value. After the kernel returns, the generated eval folds the cell into the result, and converts `Err(Interrupt)` back into `GPoll::Pending`/`Error`. Trace indices are pushed by the handles, which know their input position, never by author code.
Because only actually-evaluated inputs touch the cell, an untaken `switch` branch does not drag the status down. `#[node(no_partial)]`, for nodes where placeholder data is semantically nonsense, is a one-line change in the handle mapping: `Partial` maps to `Interrupt::Pending`. Errors produced while any input was non-`Final` are provisional and must not be reported as document errors.
A migrated node body changes mechanically: delete `async`, replace `.eval(ctx).await` with `.eval(ctx)?`, return `Result<T, Interrupt>`.
## Async nodes
An `async fn` node is an external source. It extracts and clones everything it needs, spawns a `'static` future onto the runtime, and immediately returns a placeholder:
```rs
#[node(placeholder = get_placeholder)]
async fn get(url: String) -> String { ... }
fn get_placeholder(url: &str) -> String {
format!("Waiting for response on GET {url}")
}
```
The generated struct holds a slot map keyed by the context hash. On eval: completed slot, return `Final`; in-flight slot, return `Partial(placeholder)`; no slot, insert a marker, spawn, return the placeholder. The graph never suspends; every evaluation runs to completion and produces a frame. Async bodies cannot touch the context (the future must be `'static`); the generated code checks input statuses before spawning, so no request is issued from provisional data.
## Invalidation by generation
Each async node is a source identified by its stable node id (injected like monitor paths, so identity survives recompiles and deduplicated nodes share a source). The runtime maps source id to a shared generation counter; the spawn wrapper captures its own counter:
```rs
future.await; // write result into the node's slot
*generations.lock() // bump under the table lock; absent means the
.get_mut(&source)? += 1; // source was dropped, so the epilogue is inert
dirty.store(true, Release); // request a re-render (coalesced)
```
The slot map is `Arc<Mutex<HashMap<ContextHash, Option<GPoll<T>>>>>`, cloned into the spawned future rather than borrowed from the node, so a task still in flight when `BorrowTree` rebuilds the node writes into live storage. `Option` carries the in-flight marker: absent is "never spawned", `None` is "spawned, not landed", `Some` is the landed value. The same mutex that guards the map publishes the write to the next `eval`, so neither the slot nor the generation needs a separate release/acquire protocol.
At the start of each evaluation the runtime injects a snapshot of `(SourceId, generation)` pairs into the root context, sorted by id so hashing is deterministic. Memos hash the context as usual, generations included, so after a bump exactly the memos downstream of that source miss, and every other branch hits. No cache-tracking logic, no runtime graph walking, identical behavior in the interpreter and a precompiled DAG.
The re-render typically runs with the same context except the bumped generation, so the async node finds its completed slot: a source's own generation must not be part of its slot key, which the compiler pass below guarantees.
## Asynchrony as a context feature
Which generations a subgraph observes is determined at compile time by the same branch analysis as context nullification; the feature domain is the set of upstream `SourceId`s instead of a fixed bitflag. Requirements propagate rootward (a node's set is the union of its children's, minus what it injects). At branch convergence a dependency mismatch inserts a context modification node whose payload carries a generation retain set alongside the feature bitflags: no new node kind, no separate pass. The edge into an async node retains only sources strictly upstream of it, which excludes its own generation from its slot key by construction.
## Caching
Memo nodes hash the (retain-filtered) context, generations included. `Final` and `Partial` are both cached; partials are safe because the finalizing bump changes the key. `Pending` and `Error` are never cached. Two memo tiers exist with different contracts: the persistent memo owns its entries and is a bounded LRU (contexts that change every evaluation would otherwise grow it without bound), while the frame memo stores entries in the per-evaluation arena, lends borrows on hits, and is invalidated en masse by the arena generation bump, which makes compiler-inserted caching effectively free.
## Runtime
Two layers, so the runtime stays minimal and the executor swappable:
```rs
/// Node-facing scope input.
trait Runtime { fn spawn(&self, source: SourceId, future: BoxFuture); }
/// Host-provided task executor with no graph knowledge.
trait Spawner { fn spawn(&self, task: BoxFuture); }
struct GraphRuntime<S: Spawner> {
generations: Arc<Mutex<HashMap<SourceId, u64>>>,
dirty: Arc<AtomicBool>,
spawner: S,
}
```
`GraphRuntime` wraps each task with the completion epilogue. The `Spawner` is tokio or a thread pool on desktop, `spawn_local` on wasm, or the host polling a task list in the precompiled case. The runtime reaches async nodes as a scope input (construction-time, not part of the context); a graph with zero async sources compiles to no runtime at all.
The execution path itself is synchronous: executor construction, update, and `execute` are plain fns, and hosts compile and evaluate without an async runtime of their own. All asynchrony lives in source kernels behind the spawner; `execute` surfaces the poll state (`GPoll`) and each host maps it at its boundary. The one genuine await is the GPU readback, which wasm cannot block on; sync hosts block on that future, with a dedicated device-poll thread driving completion.
Wakers are deliberately not the graph-level notification mechanism: wakers resume suspended computations and this graph never suspends; a re-evaluation is a fresh call. Wake also does not mean completion, and wakers do not survive composition across host executors. The host avoids busy-waiting with one coarse notification (park/unpark or event-loop message) shared by task wakes and the dirty epilogue.
Scheduling semantics: generations are read once per evaluation (completions landing mid-frame affect the next one); the dirty flag is drained once per frame (N completions, one re-render); on recompile, `retain_sources` drops removed sources from the table, so their epilogue still runs but finds no entry and bumps nothing, neither invalidating nor waking the host. Tasks are not cancelled; they are made inert.
# Reference-level explanation
## Node trait
```rs
pub trait Node<Input> {
type Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output>;
/// Rank polymorphism extension point, scalar (`Free`) by default.
fn extent(&self, input: &Input) -> GPoll<Extent> { ... }
/// Batched evaluation; the default body is the per-lane spec loop.
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>,
scratch: Option<&'a mut [MaybeUninit<Self::Output>]>)
-> BatchStatus<'a, Self::Output>
where Input: InjectIndex + Copy { ... }
}
```
Three load-bearing shape decisions:
- **Plain `&self` receiver.** An `&'i self` receiver forces the forwarding impl `impl Node for &'i N`, tying the node borrow to the eval lifetime, which makes shared references unable to satisfy higher-ranked bounds. With `&self`, sharing, erasure, and stack-scoped derived contexts compose. The price: nodes cannot lend their own storage; all lending rides the eval lifetime through the arena carried in the context (a node-resident value costs one clone into the arena per arena generation).
- **No lifetime parameter on the trait.** With `&self`, any lifetime in the output can only come from the input type, so lending impls quantify over it: `impl<'e> Node<Context<'e>> for Lend { type Output = &'e T; }`. `GPoll` is fixed in the signature the way `Poll` is fixed in `Future`.
- **Input by reference.** `Input` is the owned context type; calls pass `&Context`. A modifying node keeps one mutable local, mutates it between calls (per-lane index stepping is one u64 store), and lends `&local` down; sound because inputs are second-class (never stored). This halved erased-edge cost versus by-value contexts (48 bytes of ABI traffic became one pointer).
The batching law: `eval` is the sole semantic interface, and any `eval_batch` override must be indistinguishable from the default per-lane loop; overrides are optimization, never semantics. `extent` reports a node's domain (`Free` for index-invariant, `Exactly(n)` for bounded), with uncertainty riding the `GPoll` status axis like any other value.
## Context
Contexts are borrow-based `Copy` values. Eval is synchronous, so context lifetime is strictly stack-shaped, and every axis lives where its modification frequency is natural. The production shape (48 bytes, built 2026-07-25 in `core-types/src/context.rs`):
```rs
struct ContextImpl<'e> {
index: IndexLink<'e>, // per lane: inline head, mutable in place
position: Option<&'e PositionLink<'e>>, // per push: frame-resident cons cell
varargs: Option<&'e VarArgLink<'e>>, // per scope: chain of &[DynSlot] links
footprint: Option<&'e Footprint>, // per transform: borrowed from the modifier's frame
scope: &'e EvalScope<'e>, // per frame/scope: timing, generations, arena, cached hash
}
struct IndexLink<'e> { index: u64, outer: Option<&'e IndexLink<'e>> }
```
Leveled axes are cons cells: the field holds the innermost level, `outer` chains through the frames of the structure nodes that pushed the enclosing levels. Only the index keeps its head inline (and non-optional; an unindexed evaluation reads as canonical lane 0), because it is the one per-lane-mutable axis: `set_index` is a branchless u64 store, which is what lets the trait's generic default `eval_batch` run without per-lane context rebuilds. Measured against a by-ref head, where every lane must materialize a fresh context because an erased callee may legally retain the pointer: 1.5 vs 3.6 ns/lane on the erased per-lane path, and an identical 0.11 ns/lane once the batch body is visible to the compiler (`benches/context_shape.rs`).
Derivation has exactly two moves. Replace copies the context and overwrites a field; the original leaves the chain, so its contribution vanishes with the copy standing in (no masking machinery). Push spills the current head to the pusher's frame and chains a new head onto it. Mixing both stacks a shadowed copy and a push, two frame values.
`EvalScope` groups everything scope-constant (timing, pointer position, the generation table, the arena) behind one pointer, together with a hash computed at construction. Modifiers of scope axes spill a new scope to their frame with the hash recomputed; in particular the retain filter stores only the filtered-generations hash, so contexts carry no retain slice and memo visits stop walking the generation list. The general discipline: hash at write time, mix at read time. Replace-not-compose remains sound because the nullification pass computes each edge's set absolutely. Context hashing must use a seeded fast hasher (zero-initialized fx absorbs leading zero words, which produced a real wrong-value memo hit in the prototype; hash-only memo keys make collisions correctness bugs). Hash values owe no compatibility to the owned context; the invariants are pinned by the property suite in `context.rs` (axis sensitivity, level order, axis-boundary disambiguation, retain scoping).
Varargs are frame-lent references (`DynSlot = &dyn AnyHash`), never boxes: the injecting node owns the values and lends a slice from its frame, and nested scope injections chain, concatenating innermost-first.
The trait never names this type. Capabilities are extract-style bounds on the generic input (`Ctx`, `ExtractIndex`, `InjectIndex`, `ExtractArena`), matching production's context traits. Borrow-returning extracts carry the eval lifetime through an associated type (`ExtractArena<ArenaRef = &'e Arena>`, written `ExtractArena<'e>` in the macro's sugar): a lifetime in an associated-type equality is a constrained impl parameter, while a trait lifetime parameter in a plain predicate is rejected (E0207), so generated impls stay generic over the input type even for lending nodes. The authoring rule is one sentence: a named lifetime in a node fn is the eval lifetime; it enters through an extract bound and exits through `&'e` in the signature. Everything else, including "nodes cannot lend their own storage", is ordinary borrow checking of the author's standalone function.
## Compiler pass
Extends `find_context_dependencies`. Per node, alongside the `ContextFeatures` bitflags, track the set of upstream source ids. The existing convergence rule triggers insertion of a retain filter (a `context_modification` node with a generation-retain payload) exactly as nullification nodes are inserted today. Infrastructure (memo, lend, clone_out, monitor) is inserted as ordinary proto nodes, exactly as main inserts memo and nullification nodes; their registry rows are generated from a central type census (one macro invocation over the supported-type list, TaggedValue-derived plus a hand-maintained remainder) rather than written per type by hand. The wire itself carries no behavior: an edge handle is a typed erased node plus its `Type`, and every constructor is an ordinary registry row.
## Generated code and overhead
Codegen requirements: the stand-in and error share a box, the status axis is flattened into `GPoll` (together: `GPoll<u32>` is 16 bytes instead of 48), and the status plumbing is `#[inline(always)]` (a plain hint loses to the inliner cost model on the error drop-glue branches). With these, a fused pure region compiles to native arithmetic plus a final tag store; a nine-node add/mul graph evaluates behind `#[inline(never)]` as four adds and two stores, with all `Pending` checks and status meets const-folded away. A fixed-output type-erased edge (`dyn for<'a> Node<Context<'a>, Output = u32>`) is one indirect tail-call with values unboxed; lending edges erase the same way. Measured on the wired prototype: erased edges 1.8ns versus ~9ns for the per-eval box-and-downcast model; batch lend paths reach the memory bandwidth floor; steady-state interpreted frames are allocation-free (nodes in a graph arena, contexts on the stack, values and scratch in the eval arena, memo hits lending).
# Drawbacks
- **Double computation on the provisional path**: the cone downstream of an async node computes once on the placeholder and again on the real value. Inherent to progressive rendering; `#[node(no_partial)]` is the escape hatch.
- **`'static` futures cannot lazily evaluate their inputs**: everything a future needs is evaluated and cloned before spawning.
- **Migration is a cutover**: the macro, registry, and executor flip together (see the integration plan); node bodies migrate mechanically but the landing is one large reviewed unit.
- **Slot and cache memory**: slot maps and LRU caches hold completed values per context hash; eviction policy needs tuning.
# Rationale and alternatives
- **Inline pinned futures** (store each node's future unboxed, poll once per graph evaluation): rejected; `Pin`-through-`Mutex` soundness arguments, a trait bifurcation, conflicts with `BorrowTree` moving nodes, and graph evaluations as polling iterations.
- **Poll-once compatibility shims** for existing `async fn` bodies: rejected in favor of the mechanical `?` edit; genuine IO must move to the source tier anyway (a poll-once body would silently re-issue requests every frame), and the cosmetic sites are few.
- **Bail on `Partial`/`Fallback`** (all statuses through `Err`): rejected as the default; it kills progressive rendering and stand-in propagation, and a value-carrying error type does not typecheck across inputs. It survives as the `no_partial` mapping.
- **`Cow`-shaped wire values** (each edge carries owned-or-borrowed): rejected by measurement, 2.27 to 5.08 ns/edge on the cheapest chain, a graph-wide tax versus coercion adapters that cost only where inserted.
- **Waker as completion signal**: wake does not mean completion, wakers do not compose across host executors, and there is no suspended continuation to resume.
- **Manual downstream cache clearing on completion**: needs runtime topology introspection and cache-tracking logic; generation-in-hash gets the same effect through the compiler pass and works unchanged precompiled.
- **Per-evaluation scope mutation for memo GC**: scope inputs are construction-time and must not be per-frame channels; bounded LRU needs no external signal.
# Unresolved questions
- Partial epochs: futures that publish intermediate data (streams, progressive decode) want a weaker invalidation than completion.
- Arena ownership and reset policy in the editor executor (the largest undesigned integration piece).
- LRU capacity policy; exact policy for provisional errors.
- `Send`/wasm: spawned futures need `Send` on native only; the arena's concurrency claims need loom before any multi-threaded executor.
# Future possibilities
- **Rank polymorphism via extents**: lists as index-functions with the index carried in the context, domains reported by `extent`, batching as the interpreter's amortization; reserved here by the defaulted `extent` method. One `Add` implementation then covers scalar-scalar, scalar-list, and list-list with no monomorphization, and broadcasting is cheap because index-nullification lets the scalar branch memoize once per domain.
- **Precompiled DAG emission**: node structs in topological order as Rust source; the runtime shrinks to the generation table, a spawner hook, and a dirty flag.
- **JIT of graph regions**: the remaining gap between chunked interpretation and monomorphized code is unfused loop passes, the JIT's job, not the ABI's.