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
48 changed files with 1005 additions and 492 deletions

No files matched your search

Generated
-4
View File
@@ -4880,15 +4880,11 @@ dependencies = [
"core-types",
"dyn-any",
"glam",
"graphene-core",
"graphic-types",
"kurbo",
"log",
"node-macro",
"raster-types",
"serde",
"tokio",
"vector-nodes",
"vector-types",
]
-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 {
@@ -246,10 +246,10 @@ fn test_nested_network_flattening() {
#[test]
fn test_metadata_preservation() {
// Create a network with nodes that have non-default metadata
let context_features = ContextDependencies {
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
..Default::default()
};
let context_features = ContextDependencies::new(
core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
core_types::context::ContextFeatures::empty(),
);
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
@@ -95,34 +95,6 @@ impl NodeNetworkInterface {
}
}
}
/// Append the hidden runtime and source-id inputs to async-source protonodes saved before their injection.
/// Runs after the identifier replacement pass, so it matches only current identifier spellings.
pub fn migrate_async_source_inputs(&mut self) {
const PRE_INJECTION_ARITIES: [(&str, usize); 5] = [
("graphene_std::platform_application_io::GetRequestNode", 4),
("graphene_std::platform_application_io::PostRequestNode", 5),
("graphene_std::platform_application_io::LoadResourceNode", 2),
("graphene_std::platform_application_io::RasterizeNode", 3),
("graphene_std::platform_application_io::ResourceNode", 2),
];
fix_network(self.document_network_mut());
fn fix_network(network: &mut NodeNetwork) {
for node in network.nodes.values_mut() {
if let Some(network) = node.implementation.get_network_mut() {
fix_network(network);
}
if let DocumentNodeImplementation::ProtoNode(protonode) = &node.implementation
&& let Some(base) = protonode.as_str().split('<').next()
&& let Some((_, arity)) = PRE_INJECTION_ARITIES.iter().find(|(identifier, _)| *identifier == base)
&& node.inputs.len() == *arity
{
node.inputs.push(NodeInput::scope("graphene_std::runtime::RuntimeNode"));
node.inputs.push(NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId));
}
}
}
}
}
// Public immutable getters for the network interface
@@ -1148,8 +1148,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
document.network_interface.migrate_async_source_inputs();
// The "Brush" wrapper network was replaced with the `brush` proto node directly. Convert old `Network("Brush")` instances to the proto node, forwarding all 3 inputs (Background, Trace, Cache) one-to-one.
// This must run as a pre-pass before the recursive iteration below: replacing the outer Brush's network impl orphans its child paths, and the recursive iteration would log errors for those stale paths.
let brush_layers: Vec<(NodeId, Vec<NodeId>)> = document
+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
+8 -68
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};
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,57 +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, task: SourceFuture) {
self.0.as_ref().expect("runtime lives until drop").spawn(task);
}
}
/// 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, task: SourceFuture) {
wasm_bindgen_futures::spawn_local(task);
}
}
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));
@@ -187,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()),
@@ -217,6 +167,11 @@ impl NodeRuntime {
}
}
#[cfg(test)]
pub fn take_dirty(&self) -> bool {
self.executor.take_dirty()
}
pub async fn run(&mut self) -> Option<Texture> {
let mut preferences = None;
let mut graph = None;
@@ -233,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
@@ -256,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 {
@@ -635,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 {
+21
View File
@@ -53,6 +53,27 @@ impl EditorTestUtils {
}
runtime.run().await;
// An async source reports `Pending` on the evaluation that starts it and marks the runtime dirty once
// it completes, so the value only reaches the render on a follow-up evaluation. The superseded response's
// `Pending` error is ignored, but its messages carry the incremental resolved-types delta and must be
// dispatched, or the editor's type map desyncs permanently.
while runtime.take_dirty() {
let mut superseded_messages = VecDeque::new();
let _ = editor.poll_node_graph_evaluation(&mut superseded_messages);
for message in superseded_messages {
editor.handle_message(message);
}
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
}
runtime.run().await;
}
let mut messages = VecDeque::new();
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
return Err(format!("Graph should render\n\n{e}"));
+1 -1
View File
@@ -1008,7 +1008,7 @@ impl NodeNetwork {
DocumentNodeMetadata::SourceId => {
let source_id = Self::source_id_for_path(path);
if let Some(context_features) = context_features.as_deref_mut() {
core_types::context::merge_sorted_sources(&mut context_features.sources, &[source_id]);
context_features.add_sources(&[source_id]);
}
(TaggedValue::U64(source_id).into(), false)
}
+9 -9
View File
@@ -295,7 +295,7 @@ impl ProtoNetwork {
}
pub fn source_ids(&self) -> Vec<SourceId> {
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources.iter().copied()).collect()
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources().iter().copied()).collect()
}
/// Inserts context nullification nodes to optimize caching.
@@ -374,10 +374,10 @@ impl ProtoNetwork {
let mut combined_deps = ContextModification::default();
let node_index = id.0 as usize;
let context_features = self.nodes[node_index].1.context_features.clone();
let own_deps = ContextModification {
features: context_features.extract,
sources: context_features.sources.clone(),
let (extract, inject, own_deps) = {
let dependencies = &self.nodes[node_index].1.context_features;
let own_deps = ContextModification::from_sources(dependencies.extract, dependencies.sources());
(dependencies.extract, dependencies.inject, own_deps)
};
let mut inputs = match &self.nodes[node_index].1.construction_args {
@@ -397,7 +397,7 @@ impl ProtoNetwork {
let mut new_deps = combined_deps.clone();
// Remove requirements which this node provides
new_deps &= !context_features.inject;
new_deps &= !inject;
// Add requirements we have
new_deps |= own_deps;
@@ -415,7 +415,7 @@ impl ProtoNetwork {
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
// Which dependencies do we supply (and don't need ourselves)?
let net_injections = context_features.inject.difference(context_features.extract);
let net_injections = inject.difference(extract);
// Which dependencies still need to be met after this node?
let remaining_deps_from_children = combined_deps.features.difference(net_injections);
@@ -1033,7 +1033,7 @@ mod test {
let value::TaggedValue::ContextModification(modification) = &**value else {
panic!("filter payload must be a context modification")
};
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources.clone())
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources().to_vec())
})
.collect()
}
@@ -1099,7 +1099,7 @@ mod test {
identifier: ProtoNodeIdentifier::with_owned_string(name.to_string()),
call_argument: concrete!(()),
construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]),
context_features: ContextDependencies { sources, ..Default::default() },
context_features: ContextDependencies::from_sources(&sources),
..Default::default()
};
ProtoNetwork {
+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::error!("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 -31
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};
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,29 +28,6 @@ impl NodeGraphUpdateSender for UpdateLogger {
}
}
struct TokioSpawner(Option<tokio::runtime::Runtime>);
impl TokioSpawner {
fn new() -> Self {
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
}
}
impl Spawner for TokioSpawner {
fn spawn(&self, task: SourceFuture) {
self.0.as_ref().expect("runtime lives until drop").spawn(task);
}
}
/// 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 {
@@ -202,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 {}),
@@ -253,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"),
@@ -1,6 +1,5 @@
use criterion::BenchmarkGroup;
use criterion::measurement::Measurement;
use futures::executor::block_on;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi;
@@ -14,10 +13,12 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap();
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
(executor, proto_network)
}
// Some benches in this module's include set drive the demos themselves.
#[allow(dead_code)]
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
where
F: Fn(&str, &mut BenchmarkGroup<M>),
@@ -2,6 +2,7 @@ mod benchmark_util;
use benchmark_util::{bench_for_each_demo, setup_network};
use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig;
fn subsequent_evaluations(c: &mut Criterion) {
@@ -9,9 +10,7 @@ fn subsequent_evaluations(c: &mut Criterion) {
let context = RenderConfig::default();
bench_for_each_demo(&mut group, |name, g| {
let (executor, _) = setup_network(name);
g.bench_function(name, |b| {
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap())
});
g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context)).unwrap()));
});
group.finish();
}
@@ -1,6 +1,7 @@
mod benchmark_util;
use benchmark_util::setup_network;
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig;
use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -11,7 +12,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
// Warm up the cache by running once
let context = RenderConfig::default();
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context));
let _ = Executor::execute(&&executor, context);
executor
}
@@ -20,7 +21,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
let context = RenderConfig::default();
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
// Return the executor so its teardown happens outside the measured section
executor
@@ -9,14 +9,11 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let network = load_from_name(name);
let proto_network = compile(network);
let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
c.bench_function(name, |b| {
b.iter_batched(
|| (executor.clone(), proto_network.clone()),
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|| (DynamicExecutor::new(ProtoNetwork::default()).unwrap(), proto_network.clone()),
|(mut executor, network)| executor.update(std::hint::black_box(network)),
criterion::BatchSize::SmallInput,
)
});
@@ -33,10 +30,10 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let network = load_from_name(name);
let proto_network = compile(network);
let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).unwrap();
let executor = DynamicExecutor::new(proto_network).unwrap();
let footprint = Footprint::default();
c.bench_function(name, |b| b.iter(|| futures::executor::block_on((&executor).execute(footprint))));
c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
}
fn run_once_demo(c: &mut Criterion) {
let mut g = c.benchmark_group("Run Once no render");
@@ -2,6 +2,7 @@ mod benchmark_util;
use benchmark_util::{bench_for_each_demo, setup_network};
use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig;
fn run_once(c: &mut Criterion) {
@@ -11,7 +12,7 @@ fn run_once(c: &mut Criterion) {
g.bench_function(name, |b| {
b.iter_batched(
|| setup_network(name),
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap(),
|(executor, _)| Executor::execute(&&executor, std::hint::black_box(context)).unwrap(),
criterion::BatchSize::SmallInput,
)
});
@@ -1,6 +1,7 @@
mod benchmark_util;
use benchmark_util::setup_network;
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io;
use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -15,7 +16,7 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
let context = application_io::RenderConfig::default();
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
// Return the executor so its teardown happens outside the measured section
executor
@@ -13,10 +13,10 @@ fn update_executor(c: &mut Criterion) {
|| {
let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
let executor = DynamicExecutor::new(empty).unwrap();
(executor, proto_network)
},
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|(mut executor, network)| executor.update(std::hint::black_box(network)),
criterion::BatchSize::SmallInput,
)
});
@@ -9,7 +9,7 @@ use std::hint::black_box;
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
let executor = DynamicExecutor::new(empty).unwrap();
(executor, proto_network)
}
@@ -17,7 +17,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
let (mut executor, network) = setup;
let _ = black_box(futures::executor::block_on(executor.update(black_box(network))));
let _ = black_box(executor.update(black_box(network)));
// Return the executor so its teardown happens outside the measured section
executor
@@ -17,6 +17,13 @@ use std::sync::{Arc, Mutex, PoisonError};
const ARENA_CAPACITY: usize = 1 << 20;
fn new_arena() -> Arena {
Arena::new(ARENA_CAPACITY).unwrap_or_else(|| {
log::error!("arena generations exhausted; continuing without frame caching");
Arena::parked()
})
}
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
pub struct DynamicExecutor {
output: NodeId,
@@ -42,7 +49,7 @@ impl Default for DynamicExecutor {
tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
orphaned_nodes: HashSet::new(),
arena: Mutex::new(Arena::new(ARENA_CAPACITY)),
arena: Mutex::new(new_arena()),
runtime: noop_runtime(),
live_sources: Vec::new(),
}
@@ -78,7 +85,7 @@ impl DynamicExecutor {
output,
typing_context,
orphaned_nodes: HashSet::new(),
arena: Mutex::new(Arena::new(ARENA_CAPACITY)),
arena: Mutex::new(new_arena()),
runtime,
live_sources: sources,
})
@@ -480,7 +487,7 @@ mod test {
#[test]
fn eval_root_builds_the_bare_root_with_the_call_argument_as_vararg_0() {
let mut arena = Arena::new(64);
let mut arena = Arena::new(64).unwrap();
let runtime = GraphRuntime::new(InertSpawner);
let argument = 21.5f64;
let result = eval_root(&mut arena, &runtime, &argument, |ctx| {
@@ -492,7 +499,7 @@ mod test {
#[test]
fn eval_root_resets_the_arena_at_eval_start() {
let mut arena = Arena::new(64);
let mut arena = Arena::new(64).unwrap();
let runtime = GraphRuntime::new(InertSpawner);
let cell = ArenaCell::new();
eval_root(&mut arena, &runtime, &(), |ctx| {
@@ -509,7 +516,7 @@ mod test {
#[test]
fn a_panicking_eval_reports_the_error_and_resets_the_arena() {
let mut arena = Arena::new(64);
let mut arena = Arena::new(64).unwrap();
let runtime = GraphRuntime::new(InertSpawner);
let cell = ArenaCell::new();
let result: GPoll<()> = eval_root(&mut arena, &runtime, &(), |ctx| {
@@ -530,7 +537,7 @@ mod test {
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
let _node = tree.get(NodeId(0)).unwrap();
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -189,11 +189,16 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
// Context nullification
#[cfg(feature = "gpu")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => std::sync::Arc<PlatformEditorApi>, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RuntimeHandle, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => SourceId, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderOutput, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeDyn, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<DAffine2>, Context => graphene_std::ContextModification]),
#[cfg(target_family = "wasm")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => CanvasHandle, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => std::sync::Arc<PlatformEditorApi>, Context => graphene_std::ContextModification]),
@@ -204,6 +209,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
// MEMO NODES
// ==========
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ()]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RuntimeHandle]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => SourceId]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => bool]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Artboard>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Graphic>]),
@@ -276,6 +283,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
+10 -31
View File
@@ -30,22 +30,14 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
call_argument: concrete!(Context),
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::VARARGS,
inject: ContextFeatures::INDEX,
..Default::default()
},
context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
..Default::default()
},
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
..Default::default()
},
DocumentNode {
@@ -56,22 +48,14 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(1), 0),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::VARARGS,
..Default::default()
},
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::VARARGS),
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
..Default::default()
},
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS),
..Default::default()
},
DocumentNode {
@@ -81,23 +65,18 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(3), 0),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
..Default::default()
},
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::node(NodeId(4), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
context_features: graphene_std::ContextDependencies {
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
extract: ContextFeatures::INDEX | ContextFeatures::VARARGS,
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
..Default::default()
},
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
context_features: graphene_std::ContextDependencies::new(
ContextFeatures::INDEX | ContextFeatures::VARARGS,
ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
),
..Default::default()
},
]
+169 -24
View File
@@ -4,6 +4,15 @@ use std::mem::MaybeUninit;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
/// Handle word layout: 24 generation bits above 40 offset bits, so a 1 TiB arena is
/// addressable and generations run out after ~3 days of 60fps resets.
const OFFSET_BITS: u32 = 40;
const OFFSET_MASK: u64 = (1 << OFFSET_BITS) - 1;
const GENERATION_MASK: u64 = (1 << (64 - OFFSET_BITS)) - 1;
/// Out of the encodable range, so no handle, including `NULL`, matches it.
const PARKED_GENERATION: u64 = GENERATION_MASK + 1;
pub struct Arena {
generation: AtomicU64,
offset: AtomicUsize,
@@ -24,22 +33,66 @@ struct DropEntry {
// SAFETY: disjoint regions are handed out by an atomic bump; a region is written
// only by its allocating caller before publication, and cross-thread hand-off is
// ordered by the Release/Acquire pair on the published handle word.
// ordered by the Release/Acquire pair on the published handle word. Payloads are
// `Send + Sync` by the bound on every allocating method.
unsafe impl Sync for Arena {}
unsafe impl Send for Arena {}
impl std::panic::UnwindSafe for Arena {}
impl std::panic::RefUnwindSafe for Arena {}
/// Shared by all arenas, so a foreign handle misses like a stale one.
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
static LIVE_ARENAS: AtomicUsize = AtomicUsize::new(0);
/// `None` past [`GENERATION_MASK`], where a reissued generation would let an ancient
/// handle upgrade against a current arena. Recovered by `reset_generation_counter`.
fn next_generation() -> Option<u64> {
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
(generation <= GENERATION_MASK).then_some(generation)
}
/// Rewinds the shared generation counter so previously issued values are reused.
/// Returns `false` without rewinding when an [`Arena`] is live at the time of the
/// check, which is a debugging aid rather than a guarantee.
///
/// # Safety
///
/// No [`ArenaWeak`] minted before this call may be upgraded afterwards. Dropping
/// every [`Arena`] is not sufficient, since nodes also hold handles in
/// [`ArenaCell`]s; those nodes must be dropped too. No arena may be constructed
/// concurrently either, since the live check and the rewind are separate steps.
pub unsafe fn reset_generation_counter() -> bool {
if LIVE_ARENAS.load(Ordering::Acquire) != 0 {
return false;
}
NEXT_GENERATION.store(1, Ordering::Release);
true
}
impl Arena {
pub fn new(capacity: usize) -> Self {
pub fn new(capacity: usize) -> Option<Self> {
let generation = next_generation()?;
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
Self {
// Starts at 1 so the null handle word (0) can never upgrade.
generation: AtomicU64::new(1),
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Some(Self {
generation: AtomicU64::new(generation),
offset: AtomicUsize::new(0),
buf,
drops: Mutex::new(Vec::new()),
})
}
/// An arena that refuses every allocation and resolves no handle, so a caller that
/// cannot fail can degrade instead of propagating exhaustion.
pub fn parked() -> Self {
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Self {
generation: AtomicU64::new(PARKED_GENERATION),
offset: AtomicUsize::new(0),
buf: Box::new([]),
drops: Mutex::new(Vec::new()),
}
}
@@ -68,8 +121,11 @@ impl Arena {
Some(start)
}
pub fn alloc<T>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
pub fn alloc<T: Send + Sync>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
// Built before the write so an unencodable offset drops `value` here
// rather than stranding it in the arena without drop glue.
let weak = ArenaWeak::new(self.generation(), offset)?;
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
unsafe { ptr.write(value) };
@@ -80,10 +136,10 @@ impl Arena {
self.drops.lock().unwrap().push(DropEntry { offset, drop_fn: glue::<T> });
}
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
Some((unsafe { &*ptr }, ArenaWeak::new(self.generation(), offset)))
Some((unsafe { &*ptr }, weak))
}
pub fn alloc_slice_copy<T: Copy>(&self, src: &[T]) -> Option<&[T]> {
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
let buf = self.alloc_scratch::<T>(src.len())?;
for (slot, &value) in buf.iter_mut().zip(src) {
slot.write(value);
@@ -95,7 +151,7 @@ impl Arena {
// Not drop-tracked: callers must either consume every written lane or
// restrict themselves to `Copy` payloads (leak, not UB, otherwise).
#[allow(clippy::mut_from_ref)]
pub fn alloc_scratch<T>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
let size = size_of::<T>().checked_mul(len)?;
let offset = self.reserve(size, align_of::<T>())?;
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
@@ -104,21 +160,28 @@ impl Arena {
Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
}
pub fn reset(&mut self) {
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
/// where every handle misses and further allocation is refused.
pub fn reset(&mut self) -> bool {
let base = self.base();
for entry in self.drops.get_mut().unwrap().drain(..) {
let entries = std::mem::take(self.drops.get_mut().unwrap());
self.generation.store(PARKED_GENERATION, Ordering::Release);
for entry in entries.into_iter().rev() {
// SAFETY: registered at alloc time; insert-only means the region was
// never overwritten within this generation.
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
}
*self.offset.get_mut() = 0;
self.generation.fetch_add(1, Ordering::Release);
let Some(generation) = next_generation() else { return false };
self.generation.store(generation, Ordering::Release);
true
}
}
impl Drop for Arena {
fn drop(&mut self) {
self.reset();
LIVE_ARENAS.fetch_sub(1, Ordering::Release);
}
}
@@ -137,20 +200,22 @@ impl<T> Copy for ArenaWeak<T> {}
impl<T> ArenaWeak<T> {
pub const NULL: Self = ArenaWeak { word: 0, _marker: PhantomData };
fn new(generation: u64, offset: usize) -> Self {
debug_assert!(offset < u32::MAX as usize);
Self {
word: ((generation & 0xFFFF_FFFF) << 32) | offset as u64,
/// `None` once either field leaves its encodable range, so an oversized or parked
/// arena refuses to hand out a handle rather than truncating it to a live address.
fn new(generation: u64, offset: usize) -> Option<Self> {
let offset = u64::try_from(offset).ok().filter(|offset| *offset <= OFFSET_MASK)?;
(generation <= GENERATION_MASK).then_some(Self {
word: (generation << OFFSET_BITS) | offset,
_marker: PhantomData,
}
})
}
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
let generation = self.word >> 32;
if generation != arena.generation() & 0xFFFF_FFFF {
let generation = self.word >> OFFSET_BITS;
if generation != arena.generation() {
return None;
}
let offset = (self.word & 0xFFFF_FFFF) as usize;
let offset = (self.word & OFFSET_MASK) as usize;
// SAFETY: same generation means the entry was fully written before its
// word was published (Release) and cannot move or be overwritten within
// a generation (insert-only); the Acquire load that produced this word
@@ -209,11 +274,13 @@ impl<T> ArenaCell<T> {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::PoisonError;
use std::sync::atomic::AtomicU32;
#[test]
fn alloc_upgrade_reset_miss() {
let mut arena = Arena::new(1024);
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let (value, weak) = arena.alloc(41u32).unwrap();
assert_eq!(*value, 41);
@@ -225,7 +292,8 @@ mod tests {
#[test]
fn capacity_survives_reset() {
let mut arena = Arena::new(64 + align_of::<u32>() - 1);
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(64 + align_of::<u32>() - 1).unwrap();
for _ in 0..10 {
for _ in 0..16 {
assert!(arena.alloc(0u32).is_some());
@@ -237,6 +305,7 @@ mod tests {
#[test]
fn panics_leave_the_arena_coherent() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
assert_ref_unwind_safe::<Arena>();
@@ -247,7 +316,7 @@ mod tests {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024);
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let result = std::panic::catch_unwind(|| {
let (_, weak) = arena.alloc(Probe("pre-panic".into())).unwrap();
@@ -262,8 +331,84 @@ mod tests {
assert!(arena.alloc(0u32).is_some(), "the arena stays usable");
}
#[test]
fn a_panicking_destructor_leaves_no_resolvable_handle() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
panic!("payload destructor");
}
}
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let (_, weak) = arena.alloc(Bomb).unwrap();
cell.store(weak);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
assert!(unwound.is_err(), "the panic must propagate out of reset");
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
}
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
/// is never observed by a concurrently constructing test.
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
#[test]
fn an_exhausted_reset_parks_the_arena_and_refuses_handles() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let (_, weak) = arena.alloc(41u32).unwrap();
let restore = NEXT_GENERATION.swap(GENERATION_MASK + 1, Ordering::Relaxed);
assert!(!arena.reset(), "an exhausted counter must report failure");
NEXT_GENERATION.store(restore, Ordering::Relaxed);
assert_eq!(weak.upgrade(&arena), None, "a parked arena resolves no handle");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&arena), None, "not even the null handle");
assert!(arena.alloc(0u32).is_none(), "a parked arena refuses allocation");
}
#[test]
fn the_generation_counter_rewinds_only_without_live_arenas() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let arena = Arena::new(64).unwrap();
assert!(!unsafe { reset_generation_counter() }, "a live arena must block the rewind");
drop(arena);
}
#[test]
fn handles_do_not_upgrade_against_a_foreign_arena() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let first = Arena::new(1024).unwrap();
let second = Arena::new(1024).unwrap();
let (_, weak) = first.alloc(41u32).unwrap();
assert_eq!(weak.upgrade(&first), Some(&41));
assert_eq!(weak.upgrade(&second), None, "a handle must not resolve against another arena");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&second), None, "the null handle never upgrades");
}
#[test]
fn reset_drops_dependents_before_their_dependencies() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static ORDER: Mutex<Vec<u32>> = Mutex::new(Vec::new());
struct Probe(u32);
impl Drop for Probe {
fn drop(&mut self) {
ORDER.lock().unwrap().push(self.0);
}
}
let mut arena = Arena::new(1024).unwrap();
for id in 0..3 {
arena.alloc(Probe(id)).unwrap();
}
arena.reset();
assert_eq!(*ORDER.lock().unwrap(), vec![2, 1, 0], "later allocations may borrow earlier ones, so they drop first");
}
#[test]
fn drop_glue_runs_on_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
impl Drop for Probe {
@@ -271,7 +416,7 @@ mod tests {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024);
let mut arena = Arena::new(1024).unwrap();
arena.alloc(Probe("owns heap".into())).unwrap();
arena.alloc(Probe("me too".into())).unwrap();
assert_eq!(DROPS.load(Ordering::Relaxed), 0);
+101 -31
View File
@@ -199,17 +199,63 @@ impl ContextFeatures {
pub struct ContextDependencies {
pub extract: ContextFeatures,
pub inject: ContextFeatures,
/// Must stay sorted.
#[cfg_attr(feature = "serde", serde(default))]
pub sources: Vec<SourceId>,
#[cfg_attr(feature = "serde", serde(default, deserialize_with = "deserialize_sorted_sources"))]
sources: Vec<SourceId>,
}
impl ContextDependencies {
pub fn new(extract: ContextFeatures, inject: ContextFeatures) -> Self {
Self { extract, inject, sources: Vec::new() }
}
pub fn sources(&self) -> &[SourceId] {
&self.sources
}
pub fn add_sources(&mut self, sources: &[SourceId]) {
merge_sorted_sources(&mut self.sources, sources);
}
pub fn from_sources(sources: &[SourceId]) -> Self {
let mut dependencies = Self::default();
dependencies.add_sources(sources);
dependencies
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, graphene_hash::CacheHash, dyn_any::DynAny, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ContextModification {
pub features: ContextFeatures,
/// Must stay sorted.
pub sources: Vec<SourceId>,
#[cfg_attr(feature = "serde", serde(deserialize_with = "deserialize_sorted_sources"))]
sources: Vec<SourceId>,
}
impl ContextModification {
pub fn sources(&self) -> &[SourceId] {
&self.sources
}
pub fn add_sources(&mut self, sources: &[SourceId]) {
merge_sorted_sources(&mut self.sources, sources);
}
pub fn from_sources(features: ContextFeatures, sources: &[SourceId]) -> Self {
let mut modification = Self { features, sources: Vec::new() };
modification.add_sources(sources);
modification
}
}
/// Restores the sorted-and-deduplicated invariant that `contains` and `difference`
/// rely on for binary search, which arbitrary serialized input can violate.
#[cfg(feature = "serde")]
fn deserialize_sorted_sources<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<SourceId>, D::Error> {
use serde::Deserialize;
let mut sources = Vec::deserialize(deserializer)?;
sources.sort_unstable();
sources.dedup();
Ok(sources)
}
impl core::ops::BitOrAssign<&ContextModification> for ContextModification {
@@ -239,10 +285,12 @@ impl core::ops::BitAndAssign<ContextFeatures> for ContextModification {
impl ContextModification {
pub fn contains(&self, other: &Self) -> bool {
debug_assert!(self.sources.is_sorted() && other.sources.is_sorted());
self.features.contains(other.features) && other.sources.iter().all(|id| self.sources.binary_search(id).is_ok())
}
pub fn difference(&self, other: &Self) -> Self {
debug_assert!(other.sources.is_sorted());
Self {
features: self.features.difference(other.features),
sources: self.sources.iter().copied().filter(|id| other.sources.binary_search(id).is_err()).collect(),
@@ -254,12 +302,12 @@ impl ContextModification {
}
}
/// Sorts and deduplicates unconditionally, so the result is ordered no matter what
/// order the inputs arrived in.
pub fn merge_sorted_sources(sources: &mut Vec<SourceId>, other: &[SourceId]) {
for &id in other {
if let Err(insert_at) = sources.binary_search(&id) {
sources.insert(insert_at, id);
}
}
sources.extend_from_slice(other);
sources.sort_unstable();
sources.dedup();
}
impl From<&[ContextFeature]> for ContextDependencies {
@@ -734,8 +782,8 @@ pub struct CtxSnapshot {
real_time: Option<f64>,
animation_time: Option<f64>,
pointer_position: Option<DVec2>,
index: Vec<usize>,
positions: Vec<DVec2>,
index: Option<Vec<usize>>,
positions: Option<Vec<DVec2>>,
varargs: Vec<Vec<OwnedSlot>>,
generations: Vec<(SourceId, u64)>,
}
@@ -750,8 +798,8 @@ impl CtxSnapshot {
real_time: ctx.try_real_time(),
animation_time: ctx.try_animation_time(),
pointer_position: ctx.try_pointer_position(),
index: ctx.try_index().map(|levels| levels.collect()).unwrap_or_default(),
positions: ctx.try_position().map(|positions| positions.collect()).unwrap_or_default(),
index: ctx.try_index().map(|levels| levels.collect()),
positions: ctx.try_position().map(|positions| positions.collect()),
varargs: std::iter::successors(ctx.varargs_head(), |link| link.outer)
.map(|link| link.args.iter().map(|slot| slot.clone_slot()).collect())
.collect(),
@@ -762,10 +810,6 @@ impl CtxSnapshot {
pub fn generations(&self) -> &[(SourceId, u64)] {
&self.generations
}
pub fn scope<'s>(&'s self, arena: &'s Arena) -> EvalScope<'s> {
EvalScope::new(self.real_time, self.animation_time, self.pointer_position, &self.generations, arena)
}
}
impl ExtractFootprint for CtxSnapshot {
@@ -794,13 +838,13 @@ impl ExtractPointerPosition for CtxSnapshot {
impl ExtractIndex for CtxSnapshot {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
Some(self.index.iter().copied())
self.index.as_ref().map(|levels| levels.iter().copied())
}
}
impl ExtractPosition for CtxSnapshot {
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>> {
Some(self.positions.iter().copied())
self.positions.as_ref().map(|positions| positions.iter().copied())
}
}
@@ -1125,7 +1169,7 @@ mod context_impl_tests {
#[test]
fn equal_contexts_hash_equal() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [(0, 1), (1, 3)];
let scope = scope_fixture(&generations, &arena);
let a = ContextImpl::root(&scope);
@@ -1135,7 +1179,7 @@ mod context_impl_tests {
#[test]
fn each_axis_changes_the_hash() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [(0, 1)];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1159,7 +1203,7 @@ mod context_impl_tests {
#[test]
fn index_level_order_matters() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1177,7 +1221,7 @@ mod context_impl_tests {
#[test]
fn axis_boundaries_are_unambiguous() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1195,7 +1239,7 @@ mod context_impl_tests {
#[test]
fn retain_scopes_generation_invalidation() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let initial = [(0, 1), (1, 3)];
let bumped_unretained = [(0, 2), (1, 3)];
let bumped_retained = [(0, 1), (1, 4)];
@@ -1211,7 +1255,7 @@ mod context_impl_tests {
#[test]
fn excluding_keys_ignore_own_source_bumps() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let initial = [(7, 1), (9, 5)];
let own_bumped = [(7, 2), (9, 5)];
let other_bumped = [(7, 1), (9, 6)];
@@ -1226,7 +1270,7 @@ mod context_impl_tests {
#[test]
fn unretained_scope_sees_every_bump() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let initial = [(0, 1)];
let bumped = [(0, 2)];
let hash_with = |generations: &[(SourceId, u64)]| {
@@ -1238,7 +1282,7 @@ mod context_impl_tests {
#[test]
fn set_index_is_visible_and_keeps_outer_levels() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1251,7 +1295,7 @@ mod context_impl_tests {
#[test]
fn vararg_chain_concatenates_innermost_first() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1282,7 +1326,7 @@ mod context_impl_tests {
#[test]
fn snapshot_captures_vararg_levels() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1325,9 +1369,35 @@ mod context_impl_tests {
assert!(matches!(empty.vararg(0), Err(VarArgsResult::NoVarArgs)));
}
#[test]
fn sources_are_normalized_regardless_of_insertion_order() {
let mut dependencies = ContextDependencies::default();
dependencies.add_sources(&[9, 3, 9]);
dependencies.add_sources(&[5, 1]);
assert_eq!(dependencies.sources(), &[1, 3, 5, 9]);
let modification = ContextModification::from_sources(ContextFeatures::empty(), &[7, 2, 7]);
assert_eq!(modification.sources(), &[2, 7]);
}
#[test]
fn a_snapshot_preserves_an_absent_position_axis() {
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let absent = CtxSnapshot::capture(&root);
assert!(absent.try_position().is_none(), "capturing an unpositioned context must not invent a position stack");
let position = DVec2::new(1., 2.);
let positioned = CtxSnapshot::capture(&root.with_position(&PositionLink { position, outer: None }));
assert_eq!(positioned.try_position().map(|p| p.collect::<Vec<_>>()), Some(vec![position]));
}
#[test]
fn scope_arena_reaches_kernels_through_extract_arena() {
let arena = Arena::new(1024);
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -1,6 +1,6 @@
use crate::gpoll::Finality;
use std::cell::UnsafeCell;
use std::mem::MaybeUninit;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
const SLOT_EMPTY: u8 = 0;
@@ -17,6 +17,13 @@ struct FrameSlot<T> {
value: UnsafeCell<MaybeUninit<T>>,
}
// SAFETY: the key CAS reserves a slot for one writer, and the Release store of its
// state publishes the value to every Acquire load in `lookup`, so concurrent access
// is ordered. Sharing the table hands out `&T` and drops `T` on whichever thread
// drops the table, which is what the `Send + Sync` bounds cover.
unsafe impl<T: Send + Sync, const CAP: usize> Sync for FrameTable<T, CAP> {}
unsafe impl<T: Send, const CAP: usize> Send for FrameTable<T, CAP> {}
pub enum Lookup<'t, T> {
Hit(Finality, &'t T),
Vacant(VacantSlot<'t, T>),
@@ -45,8 +52,8 @@ impl<T, const CAP: usize> FrameTable<T, CAP> {
}
pub fn lookup(&self, hash: u64) -> Lookup<'_, T> {
// Keys are forced odd so the empty sentinel (0) can never collide.
let key = hash | 1;
// Only hash 0 is remapped, so distinct hashes stay distinct keys.
let key = if hash == 0 { 1 } else { hash };
for probe in 0..CAP {
let slot = &self.slots[(key as usize).wrapping_add(probe) % CAP];
let stored = slot.key.load(Ordering::Acquire);
@@ -81,18 +88,27 @@ impl<T, const CAP: usize> Drop for FrameTable<T, CAP> {
impl<'t, T> VacantSlot<'t, T> {
pub fn publish(self, value: T, finality: Finality) -> &'t T {
let slot = ManuallyDrop::new(self).slot;
// SAFETY: the CAS in `lookup` reserved this slot exclusively for us and
// its state is still SLOT_EMPTY, so nobody reads the value yet.
let lent = unsafe { &*(*self.slot.value.get()).write(value) };
let lent = unsafe { &*(*slot.value.get()).write(value) };
let state = match finality {
Finality::AllFinal => SLOT_FINAL,
Finality::Partial => SLOT_PARTIAL,
};
self.slot.state.store(state, Ordering::Release);
slot.state.store(state, Ordering::Release);
lent
}
pub fn release(self) {
drop(self);
}
}
/// Frees the reservation, so an early return or panic between `lookup` and
/// `publish` cannot retire the slot for the rest of the table's life.
impl<T> Drop for VacantSlot<'_, T> {
fn drop(&mut self) {
self.slot.key.store(0, Ordering::Release);
}
}
@@ -123,6 +139,33 @@ mod tests {
assert!(matches!(table.lookup(7), Lookup::Vacant(_)));
}
#[test]
fn a_dropped_reservation_frees_the_slot() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
drop(slot);
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an abandoned reservation must not retire the slot");
}
#[test]
fn neighboring_hashes_do_not_share_an_entry() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(6) else { unreachable!() };
slot.publish(600, Finality::AllFinal);
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an even hash must not answer for its odd neighbor");
}
#[test]
fn the_zero_hash_round_trips() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(0) else { unreachable!() };
slot.publish(11, Finality::AllFinal);
let Lookup::Hit(_, value) = table.lookup(0) else {
panic!("the remapped sentinel hash must still hit");
};
assert_eq!(*value, 11);
}
#[test]
fn distinct_keys_probe_past_collisions_until_full() {
let table = FrameTable::<u32, 4>::new();
+79 -27
View File
@@ -7,13 +7,48 @@ use std::ops::Range;
#[derive(Debug)]
pub enum BatchStatus<'a, T> {
Lent(&'a [T], Finality),
Filled(&'a mut [T], Finality),
Filled(FilledBatch<'a, T>, Finality),
Pending,
Error(GraphError),
NeedBuffer,
InvalidRange,
}
/// Owns the initialized prefix of a caller-supplied scratch buffer, dropping every
/// lane unless [`FilledBatch::into_values`] hands the obligation back to the caller.
#[derive(Debug)]
pub struct FilledBatch<'a, T> {
values: &'a mut [T],
}
impl<'a, T> FilledBatch<'a, T> {
/// # Safety
///
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
pub unsafe fn new(scratch: &'a mut [MaybeUninit<T>], len: usize) -> Self {
Self {
values: unsafe { assume_init_prefix_mut(scratch, len) },
}
}
pub fn values(&self) -> &[T] {
self.values
}
pub fn into_values(self) -> &'a mut [T] {
let mut guard = std::mem::ManuallyDrop::new(self);
std::mem::take(&mut guard.values)
}
}
impl<T> Drop for FilledBatch<'_, T> {
fn drop(&mut self) {
// SAFETY: every lane was initialized when the guard was built and none has
// been moved out, since `into_values` consumes the guard instead.
unsafe { std::ptr::drop_in_place(self.values as *mut [T]) }
}
}
/// # Safety
///
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
@@ -43,7 +78,7 @@ pub trait Node<Input> {
let Some(scratch) = scratch else {
return BatchStatus::NeedBuffer;
};
let Some(len) = range.end.checked_sub(range.start).map(|len| len as usize) else {
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
if scratch.len() < len {
@@ -76,7 +111,7 @@ pub trait Node<Input> {
}
}
// SAFETY: all `len` lanes were written by the loop above.
BatchStatus::Filled(unsafe { assume_init_prefix_mut(scratch, len) }, finality)
BatchStatus::Filled(unsafe { FilledBatch::new(scratch, len) }, finality)
}
}
@@ -94,6 +129,10 @@ where
(**self).extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
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,
@@ -116,6 +155,10 @@ where
(**self).extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
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,
@@ -138,6 +181,10 @@ where
(**self).extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
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,
@@ -239,28 +286,6 @@ impl<'a, N> LazyInput<'a, N> {
}
}
impl<'a, Input, N> Node<Input> for LazyInput<'a, N>
where
N: Node<Input>,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
self.node.eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
self.node.extent(input)
}
fn eval_batch<'b>(&self, input: &'b Input, range: Range<u64>, scratch: Option<&'b mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'b, Self::Output>
where
Input: InjectIndex + Copy,
{
self.node.eval_batch(input, range, scratch)
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -295,10 +320,37 @@ mod tests {
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes, &[4, 6, 8, 10]);
assert_eq!(lanes.values(), &[4, 6, 8, 10]);
assert_eq!(finality, Finality::AllFinal);
}
#[test]
fn a_dropped_filled_batch_reclaims_every_lane() {
static DROPS: AtomicU32 = AtomicU32::new(0);
#[derive(Clone)]
struct Probe;
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
struct Probes;
impl Node<TestInput> for Probes {
type Output = Probe;
fn eval(&self, _input: &TestInput) -> GPoll<Probe> {
GPoll::Final(Probe)
}
}
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 3];
let status = Probes.eval_batch(&input, 0..3, Some(&mut scratch));
assert!(matches!(status, BatchStatus::Filled(..)));
drop(status);
assert_eq!(DROPS.load(Ordering::Relaxed), 3, "an unconsumed batch must not leak its lanes");
}
#[test]
fn probe_without_scratch_requests_a_buffer() {
let input = TestInput { index: 0 };
@@ -330,7 +382,7 @@ mod tests {
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes, &[0, 1, 2, 3]);
assert_eq!(lanes.values(), &[0, 1, 2, 3]);
assert_eq!(finality, Finality::Partial);
}
@@ -20,6 +20,8 @@ pub struct NodeMetadata {
pub context_features: Vec<ContextFeature>,
pub memoize: bool,
pub inject_scope: bool,
/// The macro appended its hidden `_runtime` and `_source` fields as the last two entries of `fields`.
pub async_source_fields: bool,
}
// Translation struct between macro and definition
@@ -333,7 +335,7 @@ mod tests {
type ErasedSplitEdge = dyn for<'c> Node<ContextImpl<'c>, Output = SplitBorrow<'c>> + Send + Sync;
let arena = Arena::new(4096);
let arena = Arena::new(4096).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -391,7 +393,7 @@ mod tests {
}
}
let arena = Arena::new(1024);
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -443,7 +445,7 @@ mod tests {
}
}
let arena = Arena::new(1024);
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -493,7 +495,7 @@ mod tests {
#[test]
fn duplicated_edges_share_one_instance_and_outlive_each_other() {
let arena = Arena::new(1024);
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
+14 -11
View File
@@ -59,12 +59,15 @@ impl<S: Spawner + ?Sized> Spawner for Box<S> {
}
}
/// Dropped tasks never complete.
/// Polls each task once inline. Tasks that are not immediately ready never complete.
pub struct NoopSpawner;
impl Spawner for NoopSpawner {
fn spawn(&self, _task: SourceFuture) {
log::warn!("async source spawned before a host spawner is wired; the task is dropped");
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");
}
}
}
@@ -281,7 +284,7 @@ mod tests {
#[test]
fn async_source_spawns_once_and_lands_via_the_slot() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -301,7 +304,7 @@ mod tests {
#[test]
fn async_source_reports_the_placeholder_while_in_flight() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -316,7 +319,7 @@ mod tests {
#[test]
fn no_partial_maps_the_placeholder_frame_to_pending() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -331,7 +334,7 @@ mod tests {
#[test]
fn prologue_runs_sync_and_spawns_once() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -350,7 +353,7 @@ mod tests {
#[test]
fn prologue_interrupt_defers_the_spawn() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -369,7 +372,7 @@ mod tests {
#[test]
fn async_kernels_read_captured_varargs() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -390,7 +393,7 @@ mod tests {
#[test]
fn async_kernels_read_the_captured_context_snapshot() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -484,7 +487,7 @@ mod tests {
#[test]
fn a_source_slot_lands_through_the_runtime_while_downstream_keys_invalidate() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[11]);
let graph = EpilogueDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(11u64));
+1 -1
View File
@@ -367,7 +367,7 @@ pub fn simplify_identifier_name(ty: &str) -> String {
/// Converts a Rust-internal type name to its user-facing form.
pub fn make_type_user_readable(ty: &str) -> String {
let ty = ty
.replace("Option<Arc<OwnedContextImpl>>", "Context")
.replace("ContextImpl", "Context")
.replace("Raster<CPU>", "Raster")
.replace("Raster<GPU>", "Raster")
.replace("DAffine2", "Transform")
@@ -5,7 +5,7 @@ use core_types::shaders::buffer_struct::BufferStruct;
use raster_types::{GPU, Raster};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::{Mutex, PoisonError};
use wgpu::util::{BufferInitDescriptor, DeviceExt};
use wgpu::{
BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType, Buffer, BufferBinding, BufferBindingType, BufferUsages, ColorTargetState, Face,
@@ -34,7 +34,7 @@ impl PerPixelAdjustShaderRuntime {
impl ShaderRuntime {
pub fn run_per_pixel_adjust<T: BufferStruct>(&self, shaders: &Shaders<'_>, textures: List<Raster<GPU>>, args: Option<&T>) -> List<Raster<GPU>> {
let mut cache = self.per_pixel_adjust.pipeline_cache.lock().unwrap();
let mut cache = self.per_pixel_adjust.pipeline_cache.lock().unwrap_or_else(PoisonError::into_inner);
let pipeline = cache
.entry(shaders.fragment_shader_name.to_owned())
.or_insert_with(|| PerPixelAdjustGraphicsPipeline::new(&self.context, shaders));
+2 -15
View File
@@ -18,7 +18,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
fn_generics,
input,
output_type,
is_async,
fields,
description,
..
@@ -113,7 +112,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
quote! { pub(super) #name: #r#gen }
});
let async_source = *is_async || is_source_kernel(output_type);
let async_source = parsed.injects_async_source_fields();
let slot_value_type = slot_value_type(output_type);
let slot_field = async_source
.then(|| quote! { pub(super) slot: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<u64, Option<gcore::gpoll::GPoll<#slot_value_type>>>>> })
@@ -356,6 +355,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
context_features: vec![#(ContextFeature::#context_features,)*],
memoize: #memoize_flag,
inject_scope: #inject_scope_flag,
async_source_fields: #async_source,
fields: vec![
#(
FieldMetadata {
@@ -994,21 +994,8 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let entries = entries_tokens(parsed, &struct_name, &data_field_generic_idents, &regular_fields);
let cfg = crate::shader_nodes::modify_cfg(&parsed.attributes);
let entries_reexport = match entries.is_empty() {
true => quote!(),
false => {
let entries_name = format_ident!("{}_entries", fn_name);
quote! {
#cfg
#[doc(hidden)]
pub use #mod_name::#entries_name;
}
}
};
let top_level = quote! {
#entries_reexport
#cfg
#[automatically_derived]
impl<#(#generics,)* #(#node_generics,)*> #core_types::node::Node<#ctx_ident> for #mod_name::#struct_name<#(#struct_type_params,)*>
+5 -1
View File
@@ -998,7 +998,7 @@ pub fn new_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<TokenS
let crate_ident = CrateIdent::default();
let mut parsed_node = parse_node_fn(attr, item.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse node function:\n{e}")))?;
parsed_node.replace_impl_trait_in_input();
if parsed_node.is_async || crate::codegen::is_source_kernel(&parsed_node.output_type) {
if parsed_node.injects_async_source_fields() {
let core_types = crate_ident.gcore()?.clone();
parsed_node.inject_async_source_fields(&core_types);
}
@@ -1030,6 +1030,10 @@ impl ParsedNodeFn {
}
}
pub fn injects_async_source_fields(&self) -> bool {
self.is_async || crate::codegen::is_source_kernel(&self.output_type)
}
pub fn inject_async_source_fields(&mut self, core_types: &TokenStream2) {
let hidden_field = |name: &str, ty: Type, value_source: ParsedValueSource| ParsedField {
pat_ident: PatIdent {
@@ -231,9 +231,9 @@ impl PerPixelAdjustCodegen<'_> {
description: "".to_string(),
widget_override: Default::default(),
ty: ParsedFieldType::Regular(RegularParsedField {
ty: parse_quote!(std::sync::Arc<WgpuExecutor>),
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
exposed: true,
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorArcNode"))),
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))),
number_soft_min: None,
number_soft_max: None,
number_hard_min: None,
+9
View File
@@ -24,6 +24,15 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
fn validate_async_source(parsed: &ParsedNodeFn) {
let snapshot_ctx = matches!(&parsed.input.ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "CtxSnapshot"));
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
if let Some(placeholder) = &parsed.attributes.placeholder
&& !parsed.is_async
&& !future_kernel
{
emit_error!(
placeholder.span(),
"`placeholder` applies only to async and source kernels; a synchronous node never reports `Partial`, so the stand-in is unused"
);
}
if parsed.is_async && future_kernel {
emit_error!(
parsed.output_type.span(),
@@ -46,6 +46,6 @@ fn context_modification<T>(
/// The parts of the context to keep when evaluating the input value. All other parts are nullified.
modification: ContextModification,
) -> GPoll<T> {
let scope = ctx.scope().nullified(modification.features, Some(&modification.sources));
let scope = ctx.scope().nullified(modification.features, Some(modification.sources()));
value.eval(&ctx.nullified(modification.features, &scope))
}
+13 -11
View File
@@ -41,7 +41,11 @@ where
}
#[node_macro::node(category(""), path(graphene_core::memo), skip_impl, extent(frame_memo_extent))]
fn frame_memo<'e, T: Clone + 'static>(ctx: impl Ctx + CacheHash + ExtractArena<'e>, #[data] cell: ArenaCell<FrameTable<T, 32>>, content: impl Node<Context<'_>, Output = T>) -> GPoll<&'e T> {
fn frame_memo<'e, T: Clone + 'static + Send + Sync>(
ctx: impl Ctx + CacheHash + ExtractArena<'e>,
#[data] cell: ArenaCell<FrameTable<T, 32>>,
content: impl Node<Context<'_>, Output = T>,
) -> GPoll<&'e T> {
let arena = ctx.arena();
let table = match cell.load(arena) {
Some(table) => table,
@@ -70,13 +74,13 @@ fn frame_memo<'e, T: Clone + 'static>(ctx: impl Ctx + CacheHash + ExtractArena<'
fn frame_memo_extent<C, T, NodeContent>(node: &FrameMemoNode<T, NodeContent>, ctx: &C) -> GPoll<Extent>
where
T: Clone + 'static,
T: Clone + 'static + Send + Sync,
NodeContent: Node<C, Output = T>,
{
node.content.extent(ctx)
}
pub fn park<T>(arena: &Arena, result: GPoll<T>) -> GPoll<&T> {
pub fn park<T: Send + Sync>(arena: &Arena, result: GPoll<T>) -> GPoll<&T> {
match result {
GPoll::Final(value) => match arena.alloc(value) {
Some((parked, _)) => GPoll::Final(parked),
@@ -126,8 +130,6 @@ fn serialize_monitor<T: Clone + 'static + Send + Sync>(io: &MonitorValue<T>) ->
mod tests {
use super::*;
use core_types::SourceId;
use core_types::Type;
use core_types::concrete;
use core_types::context::{ContextImpl, EvalScope};
use core_types::registry::{EdgeHandle, ErasedLendNode, ErasedNode};
use std::sync::atomic::{AtomicU32, Ordering};
@@ -168,7 +170,7 @@ mod tests {
#[test]
fn monitor_serialize_exposes_the_io_record_through_the_edge() {
let arena = Arena::new(1024);
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -186,7 +188,7 @@ mod tests {
#[test]
fn memoize_caches_across_evals() {
let arena = Arena::new(1024);
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -199,7 +201,7 @@ mod tests {
#[test]
fn memo_invalidates_on_generation_bump() {
let arena = Arena::new(1024);
let arena = Arena::new(1024).unwrap();
let source: SourceId = 7;
let before = [(source, 1)];
let after = [(source, 2)];
@@ -215,7 +217,7 @@ mod tests {
#[test]
fn memo_replays_partiality_on_hit() {
let arena = Arena::new(1024);
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -228,7 +230,7 @@ mod tests {
#[test]
fn memoized_edges_stack_and_rewire() {
let arena = Arena::new(1024);
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -243,7 +245,7 @@ mod tests {
#[test]
fn frame_memo_turns_an_owned_edge_into_a_lending_edge() {
let arena = Arena::new(4096);
let arena = Arena::new(4096).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
+1 -1
View File
@@ -221,7 +221,7 @@ mod tests {
#[test]
fn create_context_builds_the_render_context_from_the_root_vararg() {
let arena = Arena::new(256);
let arena = Arena::new(256).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let root = ContextImpl::root(&scope);
+11 -19
View File
@@ -989,8 +989,6 @@ fn normalize(_: impl Ctx, vector: DVec2) -> DVec2 {
#[cfg(test)]
mod test {
use super::*;
use core_types::Node;
use core_types::generic::FnNode;
#[test]
pub fn dot_product_function() {
@@ -1029,12 +1027,6 @@ mod test {
assert_eq!(result, 0.);
}
#[test]
pub fn foo() {
let fnn = FnNode::new(|(a, b)| (b, a));
assert_eq!(fnn.eval((1u32, 2u32)), (2, 1));
}
#[test]
pub fn add_vectors() {
assert_eq!(super::add(&(), DVec2::ONE, DVec2::ONE), DVec2::ONE * 2.);
@@ -1098,7 +1090,7 @@ mod graphene_test {
#[test]
fn generated_add_evaluates_through_the_node_path() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
@@ -1108,7 +1100,7 @@ mod graphene_test {
#[test]
fn generated_add_batches_through_the_erased_edge() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
@@ -1118,13 +1110,13 @@ mod graphene_test {
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes, &[12.0, 13.0, 14.0, 15.0]);
assert_eq!(lanes.values(), &[12.0, 13.0, 14.0, 15.0]);
assert_eq!(finality, Finality::AllFinal);
}
#[test]
fn generated_wire_constructor_resolves_and_wires() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
@@ -1148,16 +1140,16 @@ mod graphene_test {
#[test]
fn generic_add_registers_one_entry_per_implementation() {
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let entries = add_entries();
assert_eq!(entries.len(), 6);
assert_eq!(entries[0].io.inputs, vec![core_types::concrete!(f64), core_types::concrete!(f64)]);
assert_eq!(entries[0].io.output, core_types::concrete!(f64));
assert_eq!(entries[0].io.return_value, core_types::concrete!(f64));
assert_eq!(entries[3].io.inputs, vec![core_types::concrete!(DVec2), core_types::concrete!(DVec2)]);
assert_eq!(entries[3].io.output, core_types::concrete!(DVec2));
assert_eq!(entries[3].io.return_value, core_types::concrete!(DVec2));
let augend = EdgeHandle::new(Arc::new(SourceNode(1.5f64)) as Arc<ErasedNode<f64>>);
let addend = EdgeHandle::new(Arc::new(SourceNode(2.5f64)) as Arc<ErasedNode<f64>>);
@@ -1182,7 +1174,7 @@ mod graphene_test {
}
}
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
@@ -1217,7 +1209,7 @@ mod graphene_test {
}
}
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
@@ -1240,7 +1232,7 @@ mod graphene_test {
}
}
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
@@ -1260,7 +1252,7 @@ mod graphene_test {
}
}
let arena = Arena::new(64);
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
@@ -201,8 +201,8 @@ mod test {
use raster_types::Image;
use raster_types::Raster;
#[tokio::test]
async fn color_overlay_multiply() {
#[test]
fn color_overlay_multiply() {
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
let image = Image::new(1, 1, image_color);
@@ -212,7 +212,7 @@ mod test {
// 100% of the output should come from the multiplied value
let opacity = 100.;
let result = super::color_overlay((), List::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
let result = super::color_overlay(&(), List::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
let result = result.element(0).unwrap().clone();
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
@@ -68,7 +68,7 @@ mod test {
#[test]
fn test_image_color_palette() {
let result = image_color_palette(
(),
&(),
List::new_from_element(Raster::new_cpu(Image {
width: 100,
height: 100,
@@ -77,6 +77,6 @@ mod test {
})),
1,
);
assert_eq!(futures::executor::block_on(result), List::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
assert_eq!(result, List::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
}
}
-6
View File
@@ -24,9 +24,3 @@ log = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
[dev-dependencies]
graphene-core = { workspace = true }
vector-nodes = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }
kurbo = { workspace = true }
+142
View File
@@ -179,3 +179,145 @@ fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
Ok(result_list)
}
#[cfg(test)]
mod test {
use super::*;
use core_types::arena::Arena;
use core_types::context::{ContextImpl, EvalScope, ExtractIndex, ExtractPosition};
use core_types::gpoll::GPoll;
use core_types::list::Item;
use core_types::node::{LazyInput, Node, StatusCell};
use vector_types::subpath::Subpath;
const TEST_POSITION: &str = "test-position";
struct ValueNode<T>(T);
impl<T: Clone, Input> Node<Input> for ValueNode<T> {
type Output = T;
fn eval(&self, _input: &Input) -> GPoll<T> {
GPoll::Final(self.0.clone())
}
}
/// Returns one default `Vector` whose transform records the innermost context index in its x translation.
struct IndexProbe;
impl<Input: ExtractIndex> Node<Input> for IndexProbe {
type Output = List<Vector>;
fn eval(&self, input: &Input) -> GPoll<List<Vector>> {
let index = input.try_index().and_then(|mut levels| levels.next()).expect("repeat must push an index level");
let mut list = List::new();
list.push(Item::new_from_element(Vector::default()).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(index as f64, 0.))));
GPoll::Final(list)
}
}
/// Returns one default `Vector` recording the innermost context position under `TEST_POSITION`.
struct PositionProbe;
impl<Input: ExtractPosition> Node<Input> for PositionProbe {
type Output = List<Vector>;
fn eval(&self, input: &Input) -> GPoll<List<Vector>> {
let position = input.try_position().and_then(|mut positions| positions.next()).expect("repeat_on_points must push a position level");
let mut list = List::new();
list.push(Item::new_from_element(Vector::default()).with_attribute(TEST_POSITION, DAffine2::from_translation(position)));
GPoll::Final(list)
}
}
fn single_default_vector() -> List<Vector> {
List::new_from_element(Vector::default())
}
fn row_translations(list: &List<Vector>, key: &str) -> Vec<DVec2> {
(0..list.len()).map(|index| list.attribute_cloned_or_default::<DAffine2>(key, index).translation).collect()
}
macro_rules! test_ctx {
($ctx:ident, $cell:ident) => {
let arena = Arena::new(4096).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let $ctx = ContextImpl::root(&scope);
let $cell = StatusCell::default();
};
}
#[test]
fn repeat_pushes_the_iteration_index_in_order() {
test_ctx!(ctx, cell);
let x_translations = |values: [f64; 3]| values.map(|x| DVec2::new(x, 0.)).to_vec();
let forward = super::repeat(&ctx, LazyInput::new(&IndexProbe, &cell, 0), 3, false).unwrap();
assert_eq!(row_translations(&forward, ATTR_TRANSFORM), x_translations([0., 1., 2.]));
let reversed = super::repeat(&ctx, LazyInput::new(&IndexProbe, &cell, 0), 3, true).unwrap();
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), x_translations([2., 1., 0.]));
}
#[test]
fn repeat_array_spaces_copies_along_the_direction() {
test_ctx!(ctx, cell);
let direction = DVec2::new(1.5, 0.);
let count = 3;
let content = ValueNode(single_default_vector());
let repeated = super::repeat_array(&ctx, LazyInput::new(&content, &cell, 0), direction, 0., count).unwrap();
assert_eq!(repeated.len(), count as usize);
for (index, translation) in row_translations(&repeated, ATTR_TRANSFORM).into_iter().enumerate() {
let expected = index as f64 * direction / (count - 1) as f64;
assert!(translation.abs_diff_eq(expected, 1e-10), "copy {index}: {translation:?} != {expected:?}");
}
}
#[test]
fn repeat_array_single_copy_stays_finite() {
test_ctx!(ctx, cell);
let content = ValueNode(single_default_vector());
let repeated = super::repeat_array(&ctx, LazyInput::new(&content, &cell, 0), DVec2::new(12., 10.), 45., 1).unwrap();
assert_eq!(repeated.len(), 1);
let transform: DAffine2 = repeated.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
assert!(transform.abs_diff_eq(DAffine2::IDENTITY, 1e-10), "single copy must not divide by zero: {transform:?}");
}
#[test]
fn repeat_radial_rotates_copies_around_the_center() {
test_ctx!(ctx, cell);
let (radius, count) = (5., 4);
let content = ValueNode(single_default_vector());
let repeated = super::repeat_radial(&ctx, LazyInput::new(&content, &cell, 0), 0., radius, count).unwrap();
assert_eq!(repeated.len(), count as usize);
for index in 0..count as usize {
let transform: DAffine2 = repeated.attribute_cloned_or_default(ATTR_TRANSFORM, index);
let expected = DAffine2::from_angle((TAU / count as f64) * index as f64) * DAffine2::from_translation(radius * DVec2::Y);
assert!(transform.abs_diff_eq(expected, 1e-10), "copy {index}: {transform:?} != {expected:?}");
}
}
#[test]
fn repeat_on_points_pushes_each_point_as_the_position() {
test_ctx!(ctx, cell);
let positions = [DVec2::new(40., 20.), DVec2::ONE, DVec2::new(-42., 9.), DVec2::new(10., 345.)];
let points = List::new_from_element(Vector::from_subpath(Subpath::from_anchors(positions, false)));
let generated = super::repeat_on_points(&ctx, points.clone(), LazyInput::new(&PositionProbe, &cell, 0), false).unwrap();
assert_eq!(row_translations(&generated, ATTR_TRANSFORM), positions.to_vec());
assert_eq!(row_translations(&generated, TEST_POSITION), positions.to_vec());
let reversed = super::repeat_on_points(&ctx, points, LazyInput::new(&PositionProbe, &cell, 0), true).unwrap();
let mut expected = positions.to_vec();
expected.reverse();
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), expected);
}
}
@@ -411,11 +411,11 @@ mod tests {
#[test]
fn isometric_grid_test() {
// Doesn't crash with weird angles
grid((), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
grid((), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
grid(&(), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
grid(&(), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
// Works properly
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
let grid = grid(&(), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
@@ -430,7 +430,7 @@ mod tests {
#[test]
fn skew_isometric_grid_test() {
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
let grid = grid(&(), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
@@ -443,7 +443,7 @@ mod tests {
#[test]
fn qr_code_test() {
let qr = qr_code((), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
let qr = qr_code(&(), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
assert!(qr.element(0).unwrap().point_domain.ids().len() > 0);
assert!(qr.element(0).unwrap().segment_domain.ids().len() > 0);
}
+45 -60
View File
@@ -3261,24 +3261,10 @@ fn centroid(ctx: impl Ctx + DeriveCtx, content: impl Node<Context<'_>, Output =
#[cfg(test)]
mod test {
use super::*;
use core_types::Node;
use kurbo::{CubicBez, Ellipse, Point, Rect};
use std::future::Future;
use std::pin::Pin;
use vector_types::vector::algorithms::bezpath_algorithms::{TValue, trim_pathseg};
use vector_types::vector::misc::pathseg_abs_diff_eq;
#[derive(Clone)]
pub struct FutureWrapperNode<T: Clone>(T);
impl<'i, T: 'i + Clone + Send> Node<'i, Footprint> for FutureWrapperNode<T> {
type Output = Pin<Box<dyn Future<Output = T> + 'i + Send>>;
fn eval(&'i self, _input: Footprint) -> Self::Output {
let value = self.0.clone();
Box::pin(async move { value })
}
}
fn vector_node_from_bezpath(bezpath: BezPath) -> List<Vector> {
List::new_from_element(Vector::from_bezpath(bezpath))
}
@@ -3289,9 +3275,9 @@ mod test {
Item::new_from_element(row).with_attribute(ATTR_TRANSFORM, transform)
}
#[tokio::test]
async fn bounding_box() {
let bounding_box = super::bounding_box((), vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))).await;
#[test]
fn bounding_box() {
let bounding_box = super::bounding_box(&(), vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)));
let bounding_box = bounding_box.element(0).unwrap();
assert_eq!(bounding_box.region_manipulator_groups().count(), 1);
let manipulator_groups_anchors = bounding_box
@@ -3309,7 +3295,7 @@ mod test {
let square = Vector::from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY));
let mut square = List::new_from_element(square);
square.with_attribute_mut_or_default(ATTR_TRANSFORM, 0, |t: &mut DAffine2| *t *= DAffine2::from_angle(std::f64::consts::FRAC_PI_4));
let bounding_box = BoundingBoxNode { content: FutureWrapperNode(square) }.eval(Footprint::default()).await;
let bounding_box = super::bounding_box(&(), square);
let bounding_box = bounding_box.element(0).unwrap();
assert_eq!(bounding_box.region_manipulator_groups().count(), 1);
let manipulator_groups_anchors = bounding_box
@@ -3326,15 +3312,15 @@ mod test {
assert_eq!(manipulator_groups_anchors[i], expected_bounding_box[i]);
}
}
#[tokio::test]
async fn copy_to_points() {
#[test]
fn copy_to_points() {
let points = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY);
let element = Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY);
let expected_points = Vector::from_bezpath(points.clone()).point_domain.positions().to_vec();
let copy_to_points = super::copy_to_points(Footprint::default(), vector_node_from_bezpath(points), vector_node_from_bezpath(element), 1., 1., 0., 0, 0., 0).await;
let flatten_path = super::flatten_path(Footprint::default(), copy_to_points).await;
let copy_to_points = super::copy_to_points(&Footprint::default(), vector_node_from_bezpath(points), vector_node_from_bezpath(element), 1., 1., 0., 0, 0., 0);
let flatten_path = super::flatten_path(&Footprint::default(), copy_to_points);
let flattened_copy_to_points = flatten_path.element(0).unwrap();
assert_eq!(flattened_copy_to_points.region_manipulator_groups().count(), expected_points.len());
@@ -3349,35 +3335,34 @@ mod test {
}
}
#[tokio::test]
async fn sample_polyline() {
#[test]
fn sample_polyline() {
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
let sample_polyline = super::sample_polyline(Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 30., 0, 0., 0., false).await;
let sample_polyline = super::sample_polyline(&Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 30., 0, 0., 0., false);
let sample_polyline = sample_polyline.element(0).unwrap();
assert_eq!(sample_polyline.point_domain.positions().len(), 4);
for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 0., DVec2::X * 30., DVec2::X * 60., DVec2::X * 90.]) {
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
}
}
#[tokio::test]
async fn sample_polyline_adaptive_spacing() {
#[test]
fn sample_polyline_adaptive_spacing() {
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
let sample_polyline = super::sample_polyline(Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 18., 0, 45., 10., true).await;
let sample_polyline = super::sample_polyline(&Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 18., 0, 45., 10., true);
let sample_polyline = sample_polyline.element(0).unwrap();
assert_eq!(sample_polyline.point_domain.positions().len(), 4);
for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 45., DVec2::X * 60., DVec2::X * 75., DVec2::X * 90.]) {
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
}
}
#[tokio::test]
async fn poisson() {
#[test]
fn poisson() {
let poisson_points = super::scatter_points(
Footprint::default(),
&Footprint::default(),
vector_node_from_bezpath(Ellipse::from_rect(Rect::new(-50., -50., 50., 50.)).to_path(DEFAULT_ACCURACY)),
10. * std::f64::consts::SQRT_2,
0,
)
.await;
);
let poisson_points = poisson_points.element(0).unwrap();
assert!(
(20..=40).contains(&poisson_points.point_domain.positions().len()),
@@ -3388,33 +3373,33 @@ mod test {
assert!(point.length() < 50. + 1., "Expected point in circle {point}")
}
}
#[tokio::test]
async fn path_length() {
#[test]
fn path_length() {
let bezpath = Rect::new(100., 100., 201., 201.).to_path(DEFAULT_ACCURACY);
let transform = DAffine2::from_scale(DVec2::new(2., 2.));
let row = create_vector_item(bezpath, transform);
let list = (0..5).map(|_| row.clone()).collect::<List<Vector>>();
let length = super::path_length(Footprint::default(), list).await;
let length = super::path_length(&Footprint::default(), list);
// 101 (each rectangle edge length) * 4 (rectangle perimeter) * 2 (scale) * 5 (number of rows)
assert_eq!(length, 101. * 4. * 2. * 5.);
}
#[tokio::test]
async fn spline() {
let spline = super::spline(Footprint::default(), vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY))).await;
#[test]
fn spline() {
let spline = super::spline(&Footprint::default(), vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)));
let spline = spline.element(0).unwrap();
assert_eq!(spline.stroke_bezpath_iter().count(), 1);
assert_eq!(spline.point_domain.positions(), &[DVec2::ZERO, DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]);
}
#[tokio::test]
async fn morph() {
#[test]
fn morph() {
let mut rectangles = vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
let mut second_rectangle = rectangles.clone_item(0).unwrap();
*second_rectangle.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM) *= DAffine2::from_translation((-100., -100.).into());
rectangles.push(second_rectangle);
let morphed = super::morph(Footprint::default(), rectangles, 0.5, false, InterpolationDistribution::default(), List::default()).await;
let morphed = super::morph(&Footprint::default(), rectangles, 0.5, false, InterpolationDistribution::default(), List::default());
let morphed_element = morphed.element(0).unwrap();
// Geometry stays in local space (original rectangle coordinates)
assert_eq!(
@@ -3425,8 +3410,8 @@ mod test {
assert!((morphed.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0).translation - DVec2::new(-50., -50.)).length() < 1e-3);
}
#[tokio::test]
async fn morph_interpolates_fill() {
#[test]
fn morph_interpolates_fill() {
let rect = || {
let mut v = Vector::default();
v.append_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
@@ -3443,7 +3428,7 @@ mod test {
let mut content = List::new_from_item(item_a);
content.push(item_b);
let morphed = super::morph(Footprint::default(), content, 0.5, false, InterpolationDistribution::default(), List::default()).await;
let morphed = super::morph(&Footprint::default(), content, 0.5, false, InterpolationDistribution::default(), List::default());
let fill = graphic_list_at(&morphed, 0, ATTR_FILL).expect("Morph should keep the fill paint at the midpoint");
@@ -3470,10 +3455,10 @@ mod test {
);
}
#[tokio::test]
async fn bevel_rect() {
#[test]
fn bevel_rect() {
let source = Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY);
let beveled = super::bevel(Footprint::default(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
let beveled = super::bevel(&Footprint::default(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
let beveled = beveled.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 8);
@@ -3492,8 +3477,8 @@ mod test {
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(0., 90.))));
}
#[tokio::test]
async fn bevel_open_curve() {
#[test]
fn bevel_open_curve() {
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
let mut source = BezPath::new();
@@ -3501,7 +3486,7 @@ mod test {
source.line_to(Point::ZERO);
source.push(curve.as_path_el());
let beveled = super::bevel((), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
let beveled = super::bevel(&(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
let beveled = beveled.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 4);
@@ -3516,8 +3501,8 @@ mod test {
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
}
#[tokio::test]
async fn bevel_with_transform() {
#[test]
fn bevel_with_transform() {
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
let mut source = BezPath::new();
@@ -3530,7 +3515,7 @@ mod test {
vector_list.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_scale_angle_translation(DVec2::splat(10.), 1., DVec2::new(99., 77.)));
let beveled = super::bevel((), List::new_from_element(vector), 2_f64.sqrt() * 10.);
let beveled = super::bevel(&(), List::new_from_element(vector), 2_f64.sqrt() * 10.);
let beveled = beveled.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 4);
@@ -3545,15 +3530,15 @@ mod test {
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
}
#[tokio::test]
async fn bevel_too_high() {
#[test]
fn bevel_too_high() {
let mut source = BezPath::new();
source.move_to(Point::ZERO);
source.line_to(Point::new(100., 0.));
source.line_to(Point::new(100., 100.));
source.line_to(Point::new(0., 100.));
let beveled = super::bevel(Footprint::default(), vector_node_from_bezpath(source), 999.);
let beveled = super::bevel(&Footprint::default(), vector_node_from_bezpath(source), 999.);
let beveled = beveled.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 6);
@@ -3569,15 +3554,15 @@ mod test {
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.))));
}
#[tokio::test]
async fn bevel_repeated_point() {
#[test]
fn bevel_repeated_point() {
let line = PathSeg::Line(Line::new(Point::ZERO, Point::new(100., 0.)));
let point = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::ZERO, Point::ZERO, Point::new(100., 0.)));
let curve = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::new(110., 0.), Point::new(110., 200.), Point::new(200., 0.)));
let subpath = BezPath::from_path_segments([line, point, curve].into_iter());
let beveled_list = super::bevel(Footprint::default(), vector_node_from_bezpath(subpath), 5.);
let beveled_list = super::bevel(&Footprint::default(), vector_node_from_bezpath(subpath), 5.);
let beveled = beveled_list.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 6);
+21 -10
View File
@@ -116,7 +116,13 @@ impl Preprocessor {
for (id, metadata) in core_types::registry::NODE_METADATA.lock().unwrap().iter() {
let id = id.clone();
let NodeMetadata { fields, memoize, inject_scope, .. } = metadata;
let NodeMetadata {
fields,
memoize,
inject_scope,
async_source_fields,
..
} = metadata;
let Some(implementations) = node_registry.get(&id) else { continue };
let valid_call_args: HashSet<_> = implementations.iter().map(|entry| entry.io.call_argument.clone()).collect();
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
@@ -131,16 +137,20 @@ impl Preprocessor {
input_type = &const { generic!(D) };
}
let inputs: Vec<_> = node_inputs(fields, first_node_io);
let input_count = inputs.len();
let network_inputs = (0..input_count).map(|i| NodeInput::node(NodeId(i as u64), 0)).collect();
let mut inputs: Vec<_> = node_inputs(fields, first_node_io);
let wrapper_input_count = inputs.len() - if *async_source_fields { 2 } else { 0 };
// The injected fields must not surface as wrapper inputs, and the `_source` reflection must sit on
// the kernel itself so the source id lands on a node that survives flattening.
let injected_inputs = inputs.split_off(wrapper_input_count);
let network_inputs = (0..wrapper_input_count).map(|i| NodeInput::node(NodeId(i as u64), 0)).chain(injected_inputs).collect();
let passthrough_node = ops::passthrough::IDENTIFIER;
let mut generated_nodes = 0;
let mut nodes: HashMap<_, _, _> = node_io_types
.iter()
.take(input_count)
.take(wrapper_input_count)
.enumerate()
.map(|(i, inputs)| {
(
@@ -185,7 +195,7 @@ impl Preprocessor {
})
.collect();
if generated_nodes == 0 && !memoize && !inject_scope {
if generated_nodes == 0 && !memoize && !inject_scope && !async_source_fields {
continue;
}
@@ -199,13 +209,14 @@ impl Preprocessor {
..Default::default()
};
nodes.insert(NodeId(input_count as u64), document_node);
let main_node_id = NodeId(wrapper_input_count as u64);
nodes.insert(main_node_id, document_node);
// If memoize is requested, append a Memoize node after the main node and redirect the export through it
let export_node_id = if *memoize {
let memoize_node_id = NodeId(input_count as u64 + 1);
let memoize_node_id = NodeId(wrapper_input_count as u64 + 1);
let memoize_node = DocumentNode {
inputs: vec![NodeInput::node(NodeId(input_count as u64), 0)],
inputs: vec![NodeInput::node(main_node_id, 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::memo::memoize::IDENTIFIER.clone()),
visible: true,
..Default::default()
@@ -213,7 +224,7 @@ impl Preprocessor {
nodes.insert(memoize_node_id, memoize_node);
memoize_node_id
} else {
NodeId(input_count as u64)
main_node_id
};
let node = DocumentNode {
+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.