Compare commits

..
7 changed files with 106 additions and 30 deletions

No files matched your search

@@ -31,6 +31,6 @@ pub use layout::{
pub use owned::{OwnedRecord, deepen_field_value, has_deep_element_glue, register_deep_element_clone, register_deep_field_value, replay_field_value};
pub use promote::{Promotion, assert_promoted, register_element_promote, register_field_promote, register_retained_heap};
pub use route::{RecordSource, SourcePlan};
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView};
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView, run_to_owned_list};
pub use serve::{FrameClaim, MaterializedSpan, Served, SlotRun, serve_input};
pub use testkit::{LiftedSource, ServedRecord, capture, test_frames};
@@ -480,6 +480,25 @@ impl<'e> GroupItem<'e> {
}
}
/// One typed run as an owned legacy list, elements cloned and every attribute
/// copied through its erased read. The owned result outlives the evaluation the
/// run was materialized in, so an async source can carry it across its await.
pub fn run_to_owned_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &GroupItem) -> Option<crate::list::List<T>> {
let lanes = item.typed_lanes::<T>()?;
let mut list = crate::list::List::new();
for lane in 0..lanes.len() {
list.push(crate::list::Item::new_from_element(lanes.element_ref(lane).clone()));
}
for field in &item.layout().fields {
for lane in 0..lanes.len() {
// SAFETY: the offset comes from the item's own layout.
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
list.set_attribute_value_dyn(field.name, lane, crate::list::AttributeValueDyn(value));
}
}
Some(list)
}
/// A run read at its element type. Record fields hold each marker's value
/// verbatim, so lane reads are plain typed reads at a hoisted offset.
pub struct RunView<'a, T> {
@@ -4,7 +4,7 @@ use super::walk::push_lane_paint_into_interiors;
use super::{Graphic, detable_items};
use crate::markers::{ATTR_FILL, ATTR_STROKE};
use core_types::Color;
use core_types::list::{AttributeValueDyn, Item, List};
use core_types::list::{Item, List};
use raster_types::{CPU, GPU, Raster};
use vector_types::{GradientStops, Vector};
@@ -12,19 +12,7 @@ use vector_types::{GradientStops, Vector};
/// through its erased read. Content keeps its native form; the legacy
/// conversions layer their mapping on top.
pub fn run_to_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
let lanes = item.typed_lanes::<T>()?;
let mut list = List::new();
for lane in 0..lanes.len() {
list.push(Item::new_from_element(lanes.element_ref(lane).clone()));
}
for field in &item.layout().fields {
for lane in 0..lanes.len() {
// SAFETY: the offset comes from the item's own layout.
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
list.set_attribute_value_dyn(field.name, lane, AttributeValueDyn(value));
}
}
Some(list)
core_types::record::run_to_owned_list(item)
}
/// Converts the group content of the list's paint attribute values to legacy
+36 -7
View File
@@ -1717,7 +1717,10 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let fn_where = &parsed.where_clause;
let body = if level_delta > 0 { rewrite_emit(&parsed.body) } else { parsed.body.clone() };
let vis = &parsed.vis;
let kernel_fields: Vec<&&ParsedField> = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).collect();
// The input index rides along: an async kernel's param type depends on the
// field's value binding, which is indexed off the node's inputs.
let kernel_indexed: Vec<(usize, &&ParsedField)> = regular_fields.iter().enumerate().filter(|(_, field)| !injected_name(&field.pat_ident.ident)).collect();
let kernel_fields: Vec<&&ParsedField> = kernel_indexed.iter().map(|(_, field)| *field).collect();
// A bare `Attr<M>` in the return type cannot elide its lifetime, so the
// kernel gets a fresh one; reference-valued writes name their real
// lifetime explicitly and pass through untouched. An async source's value
@@ -1757,12 +1760,18 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
};
quote!(#pat: #ty)
});
let value_kernel_params = kernel_fields.iter().map(|field| {
let value_kernel_params = kernel_indexed.iter().map(|(index, field)| {
let pat = &field.pat_ident;
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
unreachable!("async source fields are eager values");
};
quote!(#pat: #ty)
// A materialized level is a borrowed arena view, which cannot cross
// into a `'static` future; the prologue snapshots it to the owned
// legacy list and the kernel takes that instead.
match ir::materialized_levels(&node, *index) > 0 {
true => quote!(#pat: #core_types::list::List<#ty>),
false => quote!(#pat: #ty),
}
});
let params = snapshot_param.chain(data_kernel_params).chain(value_kernel_params);
quote! {
@@ -2137,12 +2146,32 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
Tail::Record => record_tail.clone().expect("a record-io node has a record tail"),
Tail::Flip => flip_tail.clone().expect("a flip node has a flip tail"),
Tail::SpawnAsyncFn => {
let kernel_value_names: Vec<&Ident> = kernel_fields.iter().map(|field| &field.pat_ident.ident).collect();
// The level is still live here (the prologue materialized it into the
// evaluation's arena), so the owned copy is taken before the future
// is built, as the owned-attr crossing does.
let kernel_value_args: Vec<TokenStream2> = kernel_indexed
.iter()
.map(|(index, field)| {
let name = &field.pat_ident.ident;
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
return quote!(#name.clone());
};
match ir::materialized_levels(&node, *index) > 0 {
true => quote! {
match #core_types::record::run_to_owned_list::<#ty>(&#name.as_group_item()) {
::core::option::Option::Some(__owned) => __owned,
::core::option::Option::None => return #core_types::gpoll::GPoll::Error(::std::boxed::Box::new(
#core_types::gpoll::GraphError::new(::std::concat!("the materialized level of ", ::std::stringify!(#name), " holds another element type")),
)),
}
},
false => quote!(#name.clone()),
}
})
.collect();
let snapshot_binding = snapshot_ctx.then(|| quote!(let __snapshot = #core_types::context::CtxSnapshot::capture(__input);)).into_iter();
let snapshot_arg = snapshot_ctx.then(|| quote!(__snapshot)).into_iter();
let future_args = snapshot_arg
.chain(data_names.iter().map(|name| quote!(self.#name.clone())))
.chain(kernel_value_names.iter().map(|name| quote!(#name.clone())));
let future_args = snapshot_arg.chain(data_names.iter().map(|name| quote!(self.#name.clone()))).chain(kernel_value_args);
let completion = future_completion(&parsed.output_type);
let tail = spawn_tail(completion, inflight.clone());
let prelude = carried_prelude.iter();
@@ -618,4 +618,36 @@ mod tests {
assert!(entries.contains("fn count_entries"), "a ranked record-io node still emits: {entries}");
assert_eq!(entries.matches("constructor :").count(), 2, "one row per ranked implementation");
}
/// An async source's materialized input crosses the future boundary as an
/// owned snapshot: the prologue materializes the level while the evaluation
/// is live, bridges it to the legacy list, and the kernel takes that.
#[test]
fn async_source_takes_a_materialized_input_as_an_owned_list() {
let generated = crate::parsing::new_node_fn(
quote!(category("")),
quote!(
async fn rasterize<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(
_: impl Ctx,
_: (),
#[implementations(Vector, Raster<CPU>, Graphic)] data: IList<T>,
footprint: Footprint,
) -> (Raster<CPU>, Attr<Transform>) {
todo!()
}
),
)
.expect("the async materialized shape generates")
.to_string();
assert!(generated.contains("data : :: core_types :: list :: List < T >"), "the kernel takes the owned legacy list: {generated}");
assert!(generated.contains("run_to_owned_list"), "the prologue snapshots the materialized level: {generated}");
assert!(
generated.contains("record :: materialize_batch"),
"the level still materializes in the prologue: {generated}"
);
for element in ["Vector", "Raster < CPU >", "Graphic"] {
let row = format!("record_source_type :: < {element} > ()");
assert!(generated.contains(&row), "the row carries the leveled element {element}: {generated}");
}
}
}
+8
View File
@@ -264,6 +264,14 @@ fn validate_async_source(parsed: &ParsedNodeFn) {
"`async fn` source nodes cannot take `impl Node` inputs: the spawned future outlives any borrow of the graph, so it cannot evaluate other nodes; use the sync-prologue form (return `SourceFuture`) to evaluate lazy inputs before spawning"
);
}
// One level snapshots to one owned legacy list; a deeper input has no
// owned form to cross the future boundary with.
if matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 1) {
emit_error!(
field.pat_ident.span(),
"`async fn` source nodes take a materialized input as an owned snapshot of one level, so nested `IList` is unsupported; flatten to a single `IList` or use the sync-prologue form (return `SourceFuture`)"
);
}
}
}
}
@@ -15,7 +15,7 @@ use core_types::runtime::SourceFuture;
#[cfg(target_family = "wasm")]
use core_types::transform::Footprint;
#[cfg(target_family = "wasm")]
use core_types::{ATTR_TRANSFORM, WasmNotSend};
use core_types::ATTR_TRANSFORM;
use core_types::{Color, Ctx};
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
pub use graph_craft::application_io::*;
@@ -204,17 +204,17 @@ fn create_canvas(_: impl Ctx) -> CanvasHandle {
/// Renders a view of the input graphic within an area defined by the *Footprint*.
#[cfg(target_family = "wasm")]
#[node_macro::node(category(""))]
async fn rasterize<T: WasmNotSend + Clone>(
async fn rasterize<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(
_: impl Ctx,
_: (),
#[implementations(
List<Vector>,
List<Raster<CPU>>,
List<Graphic>,
List<Color>,
List<GradientStops>,
Vector,
Raster<CPU>,
Graphic,
Color,
GradientStops,
)]
mut data: List<T>,
mut data: IList<T>,
footprint: Footprint,
mut canvas: CanvasHandle,
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>)