diff --git a/node-graph/libraries/core-types/src/context.rs b/node-graph/libraries/core-types/src/context.rs index 20d625cf2a..fbd5497df9 100644 --- a/node-graph/libraries/core-types/src/context.rs +++ b/node-graph/libraries/core-types/src/context.rs @@ -323,6 +323,12 @@ impl core::ops::BitOrAssign for IndexLevels { } } +impl core::ops::BitAndAssign for IndexLevels { + fn bitand_assign(&mut self, other: Self) { + self.0 &= other.0; + } +} + impl graphene_hash::CacheHash for IndexLevels { fn cache_hash(&self, state: &mut H) { core::hash::Hash::hash(self, state); @@ -707,7 +713,7 @@ impl ExtractFootprint for () { // ============== pub type Context<'a> = ContextImpl<'a>; -type DynRef<'a> = &'a (dyn Any + Send + Sync); +pub type DynRef<'a> = &'a (dyn Any + Send + Sync); pub trait DynHash { fn dyn_hash(&self, state: &mut dyn Hasher); @@ -937,6 +943,23 @@ impl<'a> EvalScope<'a> { self.generations.iter().find(|(candidate, _)| *candidate == source).map(|(_, generation)| *generation) } + /// The scope's own contribution to a cache key. + pub fn hash(&self) -> u64 { + self.hash + } + + pub fn real_time(&self) -> Option { + self.real_time + } + + pub fn animation_time(&self) -> Option { + self.animation_time + } + + pub fn pointer_position(&self) -> Option { + self.pointer_position + } + pub fn generations(&self) -> &'a [(SourceId, u64)] { self.generations } @@ -969,7 +992,7 @@ impl BorrowArena for ContextImpl<'_> { } pub trait CtxFamily { - type Ctx<'s>: Ctx + DeriveCtx + InjectIndex + Copy; + type Ctx<'s>: Ctx + DeriveCtx + InjectIndex + Copy + crate::dispatch::AsDispatch<'s>; } pub type Derived<'s, C> = <::Family as CtxFamily>::Ctx<'s>; @@ -1243,6 +1266,15 @@ impl<'a> ContextImpl<'a> { pub fn index_head(&self) -> IndexLink<'a> { self.index } + pub fn footprint_ref(&self) -> Option<&'a Footprint> { + self.footprint + } + pub fn varargs_ref(&self) -> Option<&'a VarArgLink<'a>> { + self.varargs + } + pub fn position_ref(&self) -> Option<&'a PositionLink<'a>> { + self.position + } pub fn with_footprint<'s>(&self, footprint: &'s Footprint) -> ContextImpl<'s> where @@ -1364,37 +1396,52 @@ impl ExtractPosition for ContextImpl<'_> { self.position.map(|head| std::iter::successors(Some(head), |link| link.outer).map(|link| link.position)) } } -impl ExtractVarArgs for ContextImpl<'_> { - fn vararg(&self, index: usize) -> Result, VarArgsResult> { - let mut link = self.varargs.ok_or(VarArgsResult::NoVarArgs)?; - let mut remaining = index; - loop { - match link.args.get(remaining) { - Some(arg) => return Ok(arg as DynRef<'_>), - None => { - remaining -= link.args.len(); - link = link.outer.ok_or(VarArgsResult::IndexOutOfBounds)?; - } +/// The vararg at `index` along a chain of links. +pub fn vararg_at<'a>(head: Option<&'a VarArgLink<'a>>, index: usize) -> Result, VarArgsResult> { + let mut link = head.ok_or(VarArgsResult::NoVarArgs)?; + let mut remaining = index; + loop { + match link.args.get(remaining) { + Some(arg) => return Ok(arg as DynRef<'a>), + None => { + remaining -= link.args.len(); + link = link.outer.ok_or(VarArgsResult::IndexOutOfBounds)?; } } } +} + +/// The number of varargs along a chain of links. +pub fn varargs_len(head: Option<&VarArgLink<'_>>) -> Result { + let head = head.ok_or(VarArgsResult::NoVarArgs)?; + Ok(std::iter::successors(Some(head), |link| link.outer).map(|link| link.args.len()).sum()) +} + +/// Hashes every vararg along a chain of links, then their count. +pub fn hash_vararg_chain(head: Option<&VarArgLink<'_>>, hasher: &mut dyn Hasher) { + let mut count = 0u64; + let mut link = head; + while let Some(current) = link { + for arg in current.args.iter() { + arg.dyn_hash(&mut *hasher); + count += 1; + } + link = current.outer; + } + count.hash(&mut &mut *hasher); +} + +impl ExtractVarArgs for ContextImpl<'_> { + fn vararg(&self, index: usize) -> Result, VarArgsResult> { + vararg_at(self.varargs, index) + } fn varargs_len(&self) -> Result { - let head = self.varargs.ok_or(VarArgsResult::NoVarArgs)?; - Ok(std::iter::successors(Some(head), |link| link.outer).map(|link| link.args.len()).sum()) + varargs_len(self.varargs) } fn hash_varargs(&self, hasher: &mut dyn Hasher) { - let mut count = 0u64; - let mut link = self.varargs; - while let Some(current) = link { - for arg in current.args.iter() { - arg.dyn_hash(&mut *hasher); - count += 1; - } - link = current.outer; - } - count.hash(&mut &mut *hasher); + hash_vararg_chain(self.varargs, hasher) } } impl<'a> ExtractArena for ContextImpl<'a> { diff --git a/node-graph/libraries/core-types/src/dispatch.rs b/node-graph/libraries/core-types/src/dispatch.rs new file mode 100644 index 0000000000..d6431a0738 --- /dev/null +++ b/node-graph/libraries/core-types/src/dispatch.rs @@ -0,0 +1,488 @@ +//! Batch evaluation over a flat lane range without building a context per +//! lane: a [`LaneMap`] decomposes a global lane into index levels, and a +//! [`Lane`] answers the context traits from the map and the batch's fixed +//! part on demand. + +use crate::arena::Arena; +use crate::context::{ + ContextFeatures, ContextImpl, Ctx, EvalScope, ExtractAnimationTime, ExtractArena, ExtractFootprint, ExtractIndices, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs, + IndexLevels, IndexLink, InjectIndex, PositionLink, VarArgLink, VarArgsResult, +}; +use crate::transform::Footprint; +use glam::DVec2; +use std::hash::{Hash, Hasher}; + +/// The levels a map can split a lane into; deeper nesting stays on the outer chain. +pub const MAX_LEVELS: usize = 8; + +/// How a global lane decomposes into index levels, innermost first: level +/// `i` runs over `extents[i]` values with the product of the levels below +/// it as its stride. A reversed level counts down, as Repeat's `reverse`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct LaneMap { + extents: [u64; MAX_LEVELS], + depth: u8, + reversed: u8, +} + +impl LaneMap { + /// One level of `extent` lanes: the flat view of a level. + pub fn flat(extent: u64) -> Self { + let mut extents = [1; MAX_LEVELS]; + extents[0] = extent; + Self { extents, depth: 1, reversed: 0 } + } + + /// A flat view whose extent is unknown: a range over it is what the caller + /// asked for, and refinement leaves the copy count open too. + pub fn open() -> Self { + Self::flat(u64::MAX) + } + + pub fn depth(&self) -> usize { + self.depth as usize + } + + /// The number of lanes the map spans. + pub fn total(&self) -> u64 { + self.extents[..self.depth()].iter().product() + } + + /// Splits level 0 into `inner` lanes per copy: the map reads `[inner, copies, ..]` + /// afterwards. `None` where level 0 is not a whole number of copies or the + /// map is full. + pub fn refined(&self, inner: u64, reverse: bool) -> Option { + // A reversed flat level has no well-defined split, so it refuses. + let open = self.extents[0] == u64::MAX; + if inner == 0 || self.depth() == MAX_LEVELS || (!open && self.extents[0] % inner != 0) || self.reversed & 1 == 1 { + return None; + } + let mut map = *self; + map.extents.copy_within(1..self.depth(), 2); + map.extents[0] = inner; + map.extents[1] = match open { + true => u64::MAX, + false => self.extents[0] / inner, + }; + map.depth += 1; + // The copies take the flag; the new inner level counts up. + map.reversed = (self.reversed << 1) | (u8::from(reverse) << 1); + Some(map) + } + + /// Level `level`'s index at `lane`. + pub fn level(&self, lane: u64, level: usize) -> u64 { + let mut rest = lane; + for extent in &self.extents[..level] { + rest /= extent; + } + let index = rest % self.extents[level]; + match self.reversed >> level & 1 { + 1 => self.extents[level] - 1 - index, + _ => index, + } + } +} + +/// What every lane of a batch shares: the evaluation scope, the features a +/// context carries by reference, and the index chain above the map. +#[derive(Clone, Copy)] +pub struct Fixed<'a> { + scope: &'a EvalScope<'a>, + footprint: Option<&'a Footprint>, + varargs: Option<&'a VarArgLink<'a>>, + position: Option<&'a PositionLink<'a>>, + outer: Option<&'a IndexLink<'a>>, +} + +/// A batch: the fixed part, the map, the lanes asked for, and which levels +/// survive nullification. Structure nodes refine the map; boundaries narrow +/// the retained levels; kernels loop [`Lane`]s over the range. +#[derive(Clone)] +pub struct Dispatch<'a> { + fixed: Fixed<'a>, + map: LaneMap, + retained: IndexLevels, + range: std::ops::Range, +} + +impl<'a> Dispatch<'a> { + /// A dispatch over `range` of the level `ctx` addresses at its lane: the + /// context's own lane becomes the map's level 0. + pub fn new(ctx: &ContextImpl<'a>, map: LaneMap, range: std::ops::Range) -> Self { + let head = ctx.index_head(); + Self { + fixed: Fixed { + scope: ctx.scope(), + footprint: ctx.footprint_ref(), + varargs: ctx.varargs_ref(), + position: ctx.position_ref(), + outer: head.outer, + }, + map, + retained: IndexLevels::all(), + range, + } + } + + pub fn map(&self) -> &LaneMap { + &self.map + } + + pub fn range(&self) -> std::ops::Range { + self.range.clone() + } + + pub fn retained(&self) -> IndexLevels { + self.retained + } + + /// The same lanes with level 0 split into `inner` lanes per copy. + pub fn refined(&self, inner: u64, reverse: bool) -> Option { + Some(Self { + map: self.map.refined(inner, reverse)?, + ..self.clone() + }) + } + + /// The same lanes with only `keep`'s levels readable. + pub fn nullified(&self, keep: IndexLevels) -> Self { + let mut retained = self.retained; + retained &= keep; + Self { retained, ..self.clone() } + } + + pub fn lane(&self, lane: u64) -> Lane<'_> { + Lane { dispatch: self, lane } + } +} + +/// The bridge between a kernel's context type and the batch: a context +/// yields the dispatch over a range of the level it addresses, and rebuilds +/// itself at any lane of a dispatch. +pub trait AsDispatch<'e>: Sized { + fn dispatch(&self, map: LaneMap, range: std::ops::Range) -> Dispatch<'e>; + /// The context at `lane`, or `None` when the arena cannot hold its chain. + fn at_lane(dispatch: &Dispatch<'e>, lane: u64) -> Option; +} + +impl<'e> AsDispatch<'e> for ContextImpl<'e> { + fn dispatch(&self, map: LaneMap, range: std::ops::Range) -> Dispatch<'e> { + Dispatch::new(self, map, range) + } + + fn at_lane(dispatch: &Dispatch<'e>, lane: u64) -> Option { + dispatch.serve_at(lane) + } +} + +impl<'e> Dispatch<'e> { + pub fn scope(&self) -> &'e EvalScope<'e> { + self.fixed.scope + } + + /// The same lanes under another scope, as a boundary narrows the scope. + pub fn with_scope<'s>(&self, scope: &'s EvalScope<'s>) -> Dispatch<'s> + where + 'e: 's, + { + Dispatch { + fixed: Fixed { + scope, + footprint: self.fixed.footprint, + varargs: self.fixed.varargs, + position: self.fixed.position, + outer: self.fixed.outer, + }, + map: self.map, + retained: self.retained, + range: self.range.clone(), + } + } + + /// The same lanes carrying only the features in `keep`. + pub fn keeping(&self, keep: ContextFeatures) -> Self { + Dispatch { + fixed: Fixed { + footprint: self.fixed.footprint.filter(|_| keep.contains(ContextFeatures::FOOTPRINT)), + varargs: self.fixed.varargs.filter(|_| keep.contains(ContextFeatures::VARARGS)), + position: self.fixed.position.filter(|_| keep.contains(ContextFeatures::POSITION)), + ..self.fixed + }, + ..self.clone() + } + } + + /// The key every lane of the dispatch shares: the context with the map's + /// levels zeroed, which is what a memo keys a published level on. + pub fn key(&self) -> u64 { + let mut outer_only = IndexLevels::empty(); + for level in self.map.depth()..32 { + outer_only = outer_only.with_level(level as u8); + } + crate::registry::cache_key(&self.nullified(outer_only).lane(0)) + } + + /// The serve-side context at `lane`, its canonical chain built in the + /// scope's arena so it lives as long as the dispatch does. + pub fn serve_at(&self, lane: u64) -> Option> { + let view = self.lane(lane); + // A chain is a handful of levels, so it lands in a stack buffer; deeper + // chains spill to a heap buffer rather than to a limit. + let mut buffer = [0u64; 16]; + let mut spill = Vec::new(); + let mut count = 0; + for level in view.canonical() { + match count < buffer.len() { + true => buffer[count] = level, + false => spill.push(level), + } + count += 1; + } + let levels = |index: usize| match index < buffer.len() { + true => buffer[index], + false => spill[index - buffer.len()], + }; + let arena = self.fixed.scope.arena(); + let mut outer: Option<&'e IndexLink<'e>> = None; + for index in (1..count).rev() { + outer = Some(arena.alloc(IndexLink { index: levels(index), outer })?.0); + } + let mut base = ContextImpl::root(self.fixed.scope); + if let Some(footprint) = self.fixed.footprint { + base = base.with_footprint(footprint); + } + if let Some(varargs) = self.fixed.varargs { + base = base.with_varargs(varargs); + } + if let Some(position) = self.fixed.position { + base = base.with_position(position); + } + Some(match outer { + Some(outer) => base.promoted(outer, levels(0)), + None => base.replaced(levels(0)), + }) + } +} +/// One lane of a dispatch, answering the context traits from the map. +#[derive(Clone, Copy)] +pub struct Lane<'a> { + dispatch: &'a Dispatch<'a>, + lane: u64, +} + +impl<'a> Lane<'a> { + fn depth(&self) -> usize { + self.dispatch.map.depth() + } + + /// The chain value at `level`, zero where nullification cleared it. + pub fn level(&self, level: usize) -> u64 { + if !self.dispatch.retained.contains_level(level) { + return 0; + } + let depth = self.depth(); + match level < depth { + true => self.dispatch.map.level(self.lane, level), + false => std::iter::successors(self.dispatch.fixed.outer, |link| link.outer).nth(level - depth).map_or(0, |link| link.index), + } + } + + fn chain_len(&self) -> usize { + self.depth() + std::iter::successors(self.dispatch.fixed.outer, |link| link.outer).count() + } + + /// The chain as nullification canonicalizes it: trailing zeroed levels + /// carry no information and are dropped, keeping at least one level. + fn canonical(&self) -> impl Iterator + '_ { + let len = (0..self.chain_len()).rev().find(|&level| self.level(level) != 0).map_or(1, |level| level + 1); + (0..len).map(move |level| self.level(level)) + } + + /// Runs `body` with the serve-side context this lane stands for, its chain + /// built on the stack for the call. + pub fn with_serve(&self, body: impl FnOnce(&ContextImpl<'_>) -> R) -> R { + let mut levels: Vec = self.canonical().collect(); + levels.reverse(); + let fixed = &self.dispatch.fixed; + let mut base = ContextImpl::root(fixed.scope); + if let Some(footprint) = fixed.footprint { + base = base.with_footprint(footprint); + } + if let Some(varargs) = fixed.varargs { + base = base.with_varargs(varargs); + } + if let Some(position) = fixed.position { + base = base.with_position(position); + } + // The canonical chain replaces the whole chain, outer part included. + descend(&levels, None, &base, body) + } +} + +/// Builds `levels` (outermost first) as stack-linked chain links and hands +/// the innermost to `body` through the base context. +fn descend(levels: &[u64], outer: Option<&IndexLink<'_>>, base: &ContextImpl<'_>, body: impl FnOnce(&ContextImpl<'_>) -> R) -> R { + match levels.split_last() { + None => body(base), + Some((&innermost, rest)) if rest.is_empty() => match outer { + Some(outer) => body(&base.promoted(outer, innermost)), + None => body(&base.replaced(innermost)), + }, + Some((_, _)) => { + let (&outermost, inner) = levels.split_first().expect("non-empty"); + let link = IndexLink { index: outermost, outer }; + descend(inner, Some(&link), base, body) + } + } +} + +impl Ctx for Lane<'_> {} + +impl InjectIndex for Lane<'_> { + fn set_index(&mut self, index: u64) { + self.lane = index; + } +} + +impl ExtractIndices for Lane<'_> { + fn try_index(&self) -> Option> { + Some(self.canonical().map(|level| level as usize)) + } +} + +impl ExtractFootprint for Lane<'_> { + fn try_footprint(&self) -> Option<&Footprint> { + self.dispatch.fixed.footprint + } +} + +impl ExtractRealTime for Lane<'_> { + fn try_real_time(&self) -> Option { + self.dispatch.fixed.scope.real_time() + } +} + +impl ExtractAnimationTime for Lane<'_> { + fn try_animation_time(&self) -> Option { + self.dispatch.fixed.scope.animation_time() + } +} + +impl ExtractPointerPosition for Lane<'_> { + fn try_pointer_position(&self) -> Option { + self.dispatch.fixed.scope.pointer_position() + } +} + +impl ExtractPosition for Lane<'_> { + fn try_position(&self) -> Option> { + self.dispatch.fixed.position.map(|head| std::iter::successors(Some(head), |link| link.outer).map(|link| link.position)) + } +} + +impl ExtractVarArgs for Lane<'_> { + fn vararg(&self, index: usize) -> Result, VarArgsResult> { + crate::context::vararg_at(self.dispatch.fixed.varargs, index) + } + + fn varargs_len(&self) -> Result { + crate::context::varargs_len(self.dispatch.fixed.varargs) + } + + fn hash_varargs(&self, hasher: &mut dyn Hasher) { + crate::context::hash_vararg_chain(self.dispatch.fixed.varargs, hasher) + } +} + +impl<'a> ExtractArena for Lane<'a> { + type ArenaRef = &'a Arena; + fn arena(&self) -> &'a Arena { + self.dispatch.fixed.scope.arena() + } +} + +/// The same hash as the serve-side context this lane stands for. +impl graphene_hash::CacheHash for Lane<'_> { + fn cache_hash(&self, state: &mut H) { + match self.dispatch.fixed.footprint { + Some(footprint) => { + 1u8.hash(state); + footprint.cache_hash(state); + } + None => 0u8.hash(state), + } + let mut count = 0u64; + for level in self.canonical() { + level.hash(state); + count += 1; + } + count.hash(state); + count = 0; + let mut position = self.dispatch.fixed.position; + while let Some(link) = position { + link.position.x.to_bits().hash(state); + link.position.y.to_bits().hash(state); + count += 1; + position = link.outer; + } + count.hash(state); + self.hash_varargs(state); + self.dispatch.fixed.scope.hash().hash(state); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::context::{ContextImpl, nullify_index_levels}; + use crate::registry::cache_key; + + fn keep(levels: &[u8]) -> IndexLevels { + levels.iter().fold(IndexLevels::empty(), |mask, &level| mask.with_level(level)) + } + + /// The serve side: the chain a Repeat of `copies` over a body of `inner` + /// lanes builds for one lane, nullified to `keep`. + fn served_key(root: &ContextImpl<'_>, scope: &EvalScope<'_>, arena: &Arena, inner: u64, lane: u64, reverse: bool, copies: u64, keep: IndexLevels) -> u64 { + let (copy, within) = (lane / inner, lane % inner); + let copy = match reverse { + true => copies - 1 - copy, + false => copy, + }; + let mut frame = IndexLink { index: 0, outer: None }; + let served = root.push_level(&mut frame, copy, within); + let chain = nullify_index_levels(served.index_head(), keep, arena).unwrap(); + cache_key(&served.nullified(ContextFeatures::all(), chain, scope)) + } + + #[test] + fn a_lane_keys_like_the_serve_chain_it_stands_for() { + let arena = Arena::new(1 << 12).unwrap(); + let generations = []; + let scope = EvalScope::new(Some(0.5), None, None, &generations, &arena); + let root = ContextImpl::root(&scope); + let (inner, copies) = (4u64, 3u64); + for reverse in [false, true] { + for keep in [keep(&[0, 1]), keep(&[1]), keep(&[0])] { + let dispatch = Dispatch::new(&root, LaneMap::flat(inner * copies).refined(inner, reverse).unwrap(), 0..inner * copies).nullified(keep); + for lane in 0..inner * copies { + let expected = served_key(&root, &scope, &arena, inner, lane, reverse, copies, keep); + assert_eq!(cache_key(&dispatch.lane(lane)), expected, "lane {lane} reverse {reverse} keep {keep:?}"); + let via_serve = dispatch.lane(lane).with_serve(|ctx| cache_key(ctx)); + assert_eq!(via_serve, expected, "with_serve for lane {lane} reverse {reverse} keep {keep:?}"); + } + } + } + } + + #[test] + fn a_map_decomposes_and_reverses() { + let map = LaneMap::flat(12).refined(4, true).unwrap(); + assert_eq!(map.depth(), 2); + assert_eq!(map.total(), 12); + assert_eq!((map.level(5, 0), map.level(5, 1)), (1, 1), "lane 5 is inner 1 of copy 1, reversed among 3 copies"); + assert_eq!(map.level(11, 1), 0, "the last lane is the last copy, which reversal makes copy 0"); + assert!(LaneMap::flat(10).refined(4, false).is_none(), "a level is a whole number of copies"); + } +} diff --git a/node-graph/libraries/core-types/src/lib.rs b/node-graph/libraries/core-types/src/lib.rs index ee2776b1ef..5e18ea6684 100644 --- a/node-graph/libraries/core-types/src/lib.rs +++ b/node-graph/libraries/core-types/src/lib.rs @@ -5,6 +5,7 @@ pub mod attribute; pub mod bounds; pub mod consts; pub mod context; +pub mod dispatch; pub mod extent; pub mod gpoll; pub mod lane; diff --git a/node-graph/libraries/core-types/src/node.rs b/node-graph/libraries/core-types/src/node.rs index 05f619aacd..c7ee56efba 100644 --- a/node-graph/libraries/core-types/src/node.rs +++ b/node-graph/libraries/core-types/src/node.rs @@ -3,7 +3,7 @@ use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt, Level}; use std::cell::Cell; use std::marker::PhantomData; use std::mem::MaybeUninit; -use std::ops::{Deref, Range}; +use std::ops::Deref; #[derive(Debug)] pub enum BatchStatus<'a> { @@ -386,7 +386,7 @@ pub trait Node { /// takes exactly its own frame out of the caller's free space. fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll> where - Input: crate::context::ExtractArena; + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena; /// The count of items at one absolute nesting level (innermost `0`). The /// leveled primitive a structure node overrides to report a pushed level's @@ -394,7 +394,7 @@ pub trait Node { /// `GPoll` status axis. fn extent_at<'e>(&self, _input: &Input, _level: u8, _frames: &crate::record::Frames<'e>) -> GPoll where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { GPoll::Final(Extent::Exactly(1)) } @@ -404,7 +404,7 @@ pub trait Node { /// domain's flat count. Consumers query this; nodes only write `extent_at`. fn extent<'e>(&self, input: &Input, at: Level, frames: &crate::record::Frames<'e>) -> GPoll where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { let product = |range: core::ops::Range, frames: &crate::record::Frames<'e>| range.fold(GPoll::Final(Extent::Exactly(1)), |acc, level| Extent::mul(acc, self.extent_at(input, level, frames))); @@ -438,17 +438,19 @@ pub trait Node { /// Installs this node's resolved record layout; a no-op unless it produces records. fn set_layout(&mut self, _layout: crate::record::RecordLayout) {} - /// Batched evaluation of `range` into caller-provided frame storage of + /// Batched evaluation of the dispatch's range into caller-provided frame storage of /// `range.len() * layout.lane_stride()` bytes; see [`BatchStatus`]. The /// default advertises no support and drivers fall back to per-lane serves /// with copy-out ([`crate::record::fill_frames`]); overrides exist to beat /// that loop (resident lanes, direct fills, fewer erased calls), never for /// correctness. - fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range, scratch: Option<&'a mut [MaybeUninit]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a> + fn eval_batch<'a, 'e, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'e>, scratch: Option<&'r mut [MaybeUninit]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'r> where - Input: InjectIndex + Copy + crate::context::ExtractArena, + 'a: 'r, + 'e: 'r, + Input: crate::dispatch::AsDispatch<'e> + InjectIndex + Copy + crate::context::ExtractArena, { - let _ = (input, range, scratch, frames); + let _ = (dispatch, scratch, frames); BatchStatus::Unbatched } } @@ -459,14 +461,14 @@ where { fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll> where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { (**self).serve(input, slot) } fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { (**self).extent_at(input, level, frames) } @@ -479,11 +481,13 @@ where (**self).layout() } - fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range, scratch: Option<&'a mut [MaybeUninit]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a> + fn eval_batch<'a, 'e, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'e>, scratch: Option<&'r mut [MaybeUninit]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'r> where - Input: InjectIndex + Copy + crate::context::ExtractArena, + 'a: 'r, + 'e: 'r, + Input: crate::dispatch::AsDispatch<'e> + InjectIndex + Copy + crate::context::ExtractArena, { - (**self).eval_batch(input, range, scratch, frames) + (**self).eval_batch(dispatch, scratch, frames) } } @@ -493,14 +497,14 @@ where { fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll> where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { (**self).serve(input, slot) } fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { (**self).extent_at(input, level, frames) } @@ -513,11 +517,13 @@ where (**self).layout() } - fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range, scratch: Option<&'a mut [MaybeUninit]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a> + fn eval_batch<'a, 'e, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'e>, scratch: Option<&'r mut [MaybeUninit]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'r> where - Input: InjectIndex + Copy + crate::context::ExtractArena, + 'a: 'r, + 'e: 'r, + Input: crate::dispatch::AsDispatch<'e> + InjectIndex + Copy + crate::context::ExtractArena, { - (**self).eval_batch(input, range, scratch, frames) + (**self).eval_batch(dispatch, scratch, frames) } } @@ -527,14 +533,14 @@ where { fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll> where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { (**self).serve(input, slot) } fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { (**self).extent_at(input, level, frames) } @@ -547,11 +553,13 @@ where (**self).layout() } - fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range, scratch: Option<&'a mut [MaybeUninit]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a> + fn eval_batch<'a, 'e, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'e>, scratch: Option<&'r mut [MaybeUninit]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'r> where - Input: InjectIndex + Copy + crate::context::ExtractArena, + 'a: 'r, + 'e: 'r, + Input: crate::dispatch::AsDispatch<'e> + InjectIndex + Copy + crate::context::ExtractArena, { - (**self).eval_batch(input, range, scratch, frames) + (**self).eval_batch(dispatch, scratch, frames) } } @@ -587,7 +595,7 @@ impl StatusCell { #[inline(always)] pub fn eval_input<'e, Input, N: Node + ?Sized>(&self, input_index: usize, node: &N, input: &Input, frames: &crate::record::Frames<'e>) -> Result, Interrupt> where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { let slot = frames.claim(node.layout()); match node.serve(input, slot) { @@ -683,7 +691,7 @@ impl<'a, 'f, N> LazyInput<'a, 'f, N> { pub fn extent<'e, Input>(&self, ctx: &Input, at: Level) -> GPoll where N: Node, - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, 'f: 'e, { self.node.extent(ctx, at, self.frames) @@ -693,59 +701,43 @@ impl<'a, 'f, N> LazyInput<'a, 'f, N> { #[cfg(test)] mod tests { use super::*; - use crate::arena::Arena; - use crate::context::ExtractArena; + use crate::context::{ContextImpl, EvalScope, ExtractIndices}; + use crate::dispatch::{AsDispatch, LaneMap}; use crate::record::{LiftedSource, serve_input}; - #[derive(Clone, Copy)] - struct TestInput<'a> { - index: u64, - arena: &'a Arena, - } - - impl InjectIndex for TestInput<'_> { - fn set_index(&mut self, index: u64) { - self.index = index; - } - } - - impl<'a> ExtractArena for TestInput<'a> { - type ArenaRef = &'a Arena; - - fn arena(&self) -> &'a Arena { - self.arena - } - } - - fn double<'a>() -> LiftedSource) -> GPoll> { - LiftedSource::new(|input: &TestInput<'a>| GPoll::Final(input.index * 2)) + fn double() -> LiftedSource Fn(&ContextImpl<'c>) -> GPoll> { + LiftedSource::new(|input: &ContextImpl<'_>| GPoll::Final(input.innermost_index() * 2)) } #[test] fn the_default_advertises_no_batch_support() { let frames = crate::record::test_frames(1 << 16); let arena = Arena::new(1024).unwrap(); - let input = TestInput { index: 0, arena: &arena }; + let generations = []; + let scope = EvalScope::new(None, None, None, &generations, &arena); + let input = ContextImpl::root(&scope); let mut scratch = [const { MaybeUninit::uninit() }; 4]; let node = double(); - assert!(matches!(node.eval_batch(&input, 2..6, Some(&mut scratch), &frames), BatchStatus::Unbatched)); - assert!(matches!(node.eval_batch(&input, 2..6, None, &frames), BatchStatus::Unbatched)); + assert!(matches!(node.eval_batch(input.dispatch(LaneMap::open(), 2..6), Some(&mut scratch), &frames), BatchStatus::Unbatched)); + assert!(matches!(node.eval_batch(input.dispatch(LaneMap::open(), 2..6), None, &frames), BatchStatus::Unbatched)); } #[test] fn trait_is_object_safe_across_erased_edges() { let arena = Arena::new(1024).unwrap(); - let input = TestInput { index: 21, arena: &arena }; + let generations = []; + let scope = EvalScope::new(None, None, None, &generations, &arena); + let input = ContextImpl::root(&scope).replaced(21); let node = double(); - let layout = Node::::layout(&node).clone(); - let erased: Box> = Box::new(node); + let layout = Node::>::layout(&node).clone(); + let erased: Box Node>> = Box::new(node); let frames = crate::record::test_frames(1 << 12); let GPoll::Final(value) = serve_input(&*erased, &input, &frames) else { panic!("the erased edge must serve a final record"); }; // SAFETY: the record was served at `layout`, whose element is the output. assert_eq!(unsafe { crate::record::read_element::(layout.rec(&value)) }, 42); - assert!(matches!(erased.eval_batch(&input, 0..2, None, &frames), BatchStatus::Unbatched)); + assert!(matches!(erased.eval_batch(input.dispatch(LaneMap::open(), 0..2), None, &frames), BatchStatus::Unbatched)); } } diff --git a/node-graph/libraries/core-types/src/record/input.rs b/node-graph/libraries/core-types/src/record/input.rs index 6075f45136..ff61520de4 100644 --- a/node-graph/libraries/core-types/src/record/input.rs +++ b/node-graph/libraries/core-types/src/record/input.rs @@ -4,6 +4,7 @@ use super::access::{Rec, RecordValue, read_element}; use super::frames::Frames; use super::layout::Layout; use super::serve::{FrameClaim, Served, serve_input}; +use crate::dispatch::{AsDispatch, Dispatch, LaneMap}; use crate::gpoll::GPoll; use crate::node::Node; @@ -15,29 +16,32 @@ use crate::node::Node; pub trait DerivedRecordInput<'derived, C> { fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result, crate::gpoll::Interrupt>; fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll; - fn eval_batch_derived<'a>(&'a self, ctx: &'a C, range: std::ops::Range, scratch: Option<&'a mut [std::mem::MaybeUninit]>, frames: &Frames<'derived>) -> crate::node::BatchStatus<'a> + fn eval_batch_derived<'a, 'r>(&'a self, dispatch: Dispatch<'derived>, scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &Frames<'derived>) -> crate::node::BatchStatus<'r> where - C: crate::context::InjectIndex + Copy; + 'a: 'r, + 'derived: 'r, + C: AsDispatch<'derived> + crate::context::InjectIndex + Copy; fn serve_derived<'l>(&self, ctx: &C, slot: crate::record::FrameClaim<'derived, 'l>) -> GPoll>; } impl<'derived, C, N> DerivedRecordInput<'derived, C> for N where N: Node, - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'derived> + crate::context::ExtractArena, { fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result, crate::gpoll::Interrupt> { cell.eval_input(input_index, self, ctx, frames) } - fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll { self.extent_at(ctx, level, frames) } - fn eval_batch_derived<'a>(&'a self, ctx: &'a C, range: std::ops::Range, scratch: Option<&'a mut [std::mem::MaybeUninit]>, frames: &Frames<'derived>) -> crate::node::BatchStatus<'a> + fn eval_batch_derived<'a, 'r>(&'a self, dispatch: Dispatch<'derived>, scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &Frames<'derived>) -> crate::node::BatchStatus<'r> where - C: crate::context::InjectIndex + Copy, + 'a: 'r, + 'derived: 'r, + C: AsDispatch<'derived> + crate::context::InjectIndex + Copy, { - self.eval_batch(ctx, range, scratch, frames) + self.eval_batch(dispatch, scratch, frames) } fn serve_derived<'l>(&self, ctx: &C, slot: crate::record::FrameClaim<'derived, 'l>) -> GPoll> { self.serve(ctx, slot) @@ -61,14 +65,31 @@ pub fn forward_batch<'a, 'derived, C, N>( ) -> crate::node::BatchStatus<'a> where N: DerivedRecordInput<'derived, C>, - C: crate::context::InjectIndex + Copy, + C: AsDispatch<'derived> + crate::context::InjectIndex + Copy, +{ + forward_dispatch(node, &ctx.dispatch(LaneMap::open(), range), scratch, frames, layout, unbatched) +} + +/// [`forward_batch`] over a dispatch the caller already derived. +pub fn forward_dispatch<'a, 'derived, C, N>( + node: &N, + dispatch: &Dispatch<'derived>, + scratch: Option<&'a mut [std::mem::MaybeUninit]>, + frames: &Frames<'derived>, + layout: &'a Layout, + unbatched: impl FnOnce(&'a mut [std::mem::MaybeUninit]) -> crate::node::BatchStatus<'a>, +) -> crate::node::BatchStatus<'a> +where + N: DerivedRecordInput<'derived, C>, + C: AsDispatch<'derived> + crate::context::InjectIndex + Copy, { use crate::node::BatchStatus; + let range = dispatch.range(); let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else { return BatchStatus::InvalidRange; }; let stride = layout.lane_stride(); - let wants_fill = match node.eval_batch_derived(ctx, range.clone(), None, frames) { + let wants_fill = match node.eval_batch_derived(dispatch.clone(), None, frames) { BatchStatus::Lent(batch, finality, hint) => { let Some(scratch) = scratch else { return BatchStatus::NeedBuffer; @@ -106,7 +127,7 @@ where if scratch.len() * 8 < len * stride { return BatchStatus::InvalidRange; } - let filled = match node.eval_batch_derived(ctx, range, Some(&mut *scratch), frames) { + let filled = match node.eval_batch_derived(dispatch.clone(), Some(&mut *scratch), frames) { BatchStatus::Filled(filled, finality, hint) => Ok((filled.len(), finality, hint)), // A node that lends only once given scratch is served lane by lane instead. BatchStatus::Lent(..) | BatchStatus::Unbatched | BatchStatus::NeedBuffer => Err(BatchStatus::Unbatched), @@ -124,13 +145,25 @@ where /// Fills caller scratch with one frame per lane of `range`: the input serves /// into the lane's own region of the slab, and the lane's own frame space is /// free again at the next lane, so the frame peak stays at one lane's need and -/// every lane's bytes are distinct. -pub fn fill_frames<'a, 'e, C, N>(node: &'a N, input: &C, range: std::ops::Range, scratch: Option<&'a mut [std::mem::MaybeUninit]>, frames: &Frames<'e>) -> crate::node::BatchStatus<'a> +/// the scratch grows only with the lanes. +pub fn fill_frames<'a, 'e, 'r, C, N>(node: &'a N, input: &C, range: std::ops::Range, scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &Frames<'e>) -> crate::node::BatchStatus<'r> where - C: crate::context::InjectIndex + Copy + crate::context::ExtractArena, + 'a: 'r, + C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena, + N: Node, +{ + fill_dispatch::(node, &input.dispatch(LaneMap::open(), range), scratch, frames) +} + +/// [`fill_frames`] over a dispatch: each lane's context is rebuilt from it. +pub fn fill_dispatch<'a, 'e, 'r, C, N>(node: &'a N, dispatch: &Dispatch<'e>, scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &Frames<'e>) -> crate::node::BatchStatus<'r> +where + 'a: 'r, + C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena, N: Node, { use crate::node::BatchStatus; + let range = dispatch.range(); let Some(scratch) = scratch else { return BatchStatus::NeedBuffer; }; @@ -140,11 +173,15 @@ where let Some(mut run) = frames.run(scratch, len, node.layout()) else { return BatchStatus::InvalidRange; }; - let mut local = *input; let mut finality = crate::gpoll::Finality::AllFinal; let mut hint = crate::gpoll::Extent::AtLeast(range.end as usize); for lane in 0..len { - local.set_index(range.start + lane as u64); + let Some(local) = C::at_lane(dispatch, range.start + lane as u64) else { + return BatchStatus::Error(crate::gpoll::GraphError { + kind: crate::gpoll::ErrorKind::ArenaExhausted, + trace: Vec::new(), + }); + }; let lane_frames = frames.scope(); let slot = run.slot(lane, &lane_frames); let served = match node.serve(&local, slot) { @@ -171,12 +208,37 @@ where /// The driver a consumer runs on a record input: a resident batch returns with /// no allocation, a node's own batch impl gets `n * frame_bytes` of arena /// scratch, and an unbatched input falls back to the [`fill_frames`] loop. -pub fn materialize_batch<'a, 'e, C, N>(node: &'a N, input: &'a C, range: std::ops::Range, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'a> +pub fn materialize_batch<'a, 'e, 'r, C, N>(node: &'a N, input: &'a C, range: std::ops::Range, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'r> where - C: crate::context::InjectIndex + Copy + crate::context::ExtractArena, + 'a: 'r, + 'e: 'r, + C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena, + N: Node, +{ + let dispatch = input.dispatch(LaneMap::open(), range); + materialize_owned::(node, dispatch, arena, frames) +} + +/// [`materialize_batch`] over a dispatch the caller already derived. +pub fn materialize_dispatch<'a, 'e, 'r, C, N>(node: &'a N, dispatch: &Dispatch<'e>, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'r> +where + 'a: 'r, + 'e: 'r, + C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena, + N: Node, +{ + materialize_owned::(node, dispatch.clone(), arena, frames) +} + +fn materialize_owned<'a, 'e, 'r, C, N>(node: &'a N, dispatch: Dispatch<'e>, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'r> +where + 'a: 'r, + 'e: 'r, + C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena, N: Node, { use crate::node::BatchStatus; + let range = dispatch.range(); let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else { return BatchStatus::InvalidRange; }; @@ -190,7 +252,7 @@ where trace: Vec::new(), }) }; - let status = node.eval_batch(input, range.clone(), None, frames); + let status = node.eval_batch(dispatch.clone(), None, frames); #[cfg(debug_assertions)] { let consumer = BATCH_CONSUMER.with(|consumer| consumer.get()); @@ -203,11 +265,11 @@ where } match status { BatchStatus::Unbatched => match arena.alloc_scratch::(words) { - Some(scratch) => fill_frames(node, input, range, Some(scratch), frames), + Some(scratch) => fill_dispatch::(node, &dispatch, Some(scratch), frames), None => exhausted(), }, BatchStatus::NeedBuffer => match arena.alloc_scratch::(words) { - Some(scratch) => node.eval_batch(input, range, Some(scratch), frames), + Some(scratch) => node.eval_batch(dispatch, Some(scratch), frames), None => exhausted(), }, status => status, @@ -225,9 +287,11 @@ pub enum LevelStatus<'a> { /// fills once, a lower bound drains by guess-and-double until a short fill, /// each reply's hint seeding the next guess. The boundary consumers' driver; /// reducers inline the same protocol with their span offsets. -pub fn materialize_level<'a, 'e, C, N>(node: &'a N, input: &'a C, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> LevelStatus<'a> +pub fn materialize_level<'a, 'e, 'r, C, N>(node: &'a N, input: &'a C, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> LevelStatus<'r> where - C: crate::context::InjectIndex + Copy + crate::context::ExtractArena, + 'a: 'r, + 'e: 'r, + C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena, N: Node, { use crate::gpoll::{Extent, GraphError, Level}; @@ -295,7 +359,7 @@ impl<'a, 'e, N> RecordInput<'a, 'e, N> { pub fn serve<'l, C>(&self, ctx: &C, slot: FrameClaim<'e, 'l>) -> GPoll> where N: Node, - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { self.node.serve(ctx, slot) } @@ -305,7 +369,7 @@ impl<'a, 'e, N> RecordInput<'a, 'e, N> { pub fn materialize_level<'b, C>(&'b self, ctx: &'b C, arena: &'b crate::arena::Arena) -> LevelStatus<'b> where N: Node, - C: crate::context::InjectIndex + Copy + crate::context::ExtractArena, + C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena, { materialize_level(self.node, ctx, arena, self.frames) } @@ -613,7 +677,7 @@ impl RecordExtract { pub fn eval<'e, C>(&self, input: &C, frames: &Frames<'e>) -> GPoll where N: Node, - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { // The element copies out by value, so the input's claim dies with // the scope. diff --git a/node-graph/libraries/core-types/src/record/mod.rs b/node-graph/libraries/core-types/src/record/mod.rs index a3dd22b857..b8d47b2633 100644 --- a/node-graph/libraries/core-types/src/record/mod.rs +++ b/node-graph/libraries/core-types/src/record/mod.rs @@ -24,7 +24,8 @@ mod testkit; pub use access::{Rec, RecordValue, apply_plan, borrow_element, erase_static, read_at, read_at_defaulting, read_element, token_only, write_element, write_element_sized, write_field}; pub use frames::{FrameArena, FrameScope, Frames}; pub use input::{ - DerivedLazyInput, DerivedRecordInput, ElementInput, ElementLazyInput, LevelStatus, RecordExtract, RecordInput, RecordLazyInput, fill_frames, forward_batch, materialize_batch, materialize_level, + DerivedLazyInput, DerivedRecordInput, ElementInput, ElementLazyInput, LevelStatus, RecordExtract, RecordInput, RecordLazyInput, fill_dispatch, fill_frames, forward_batch, forward_dispatch, + materialize_batch, materialize_dispatch, materialize_level, }; #[cfg(debug_assertions)] pub use input::{note_batch_consumer, note_kernel_batch, take_batch_tally, take_kernel_tally}; diff --git a/node-graph/libraries/core-types/src/record/route.rs b/node-graph/libraries/core-types/src/record/route.rs index 68d27fba45..50d08df86b 100644 --- a/node-graph/libraries/core-types/src/record/route.rs +++ b/node-graph/libraries/core-types/src/record/route.rs @@ -92,7 +92,7 @@ where { fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll> where - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { // The source's frame is claimed beyond this one and dies with the // claim; the translated union record stays. @@ -127,7 +127,7 @@ where fn extent_at<'x>(&self, input: &C, level: u8, frames: &Frames<'x>) -> GPoll where - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'x> + crate::context::ExtractArena, { self.edge.extent_at(input, level, frames) } @@ -136,13 +136,16 @@ where /// untouched, and a translating route materializes the source's lanes at /// the source layout and translates each into the caller's scratch, so a /// batch survives the layout seam instead of restarting lane by lane. - fn eval_batch<'a, 'x>(&'a self, input: &'a C, range: std::ops::Range, scratch: Option<&'a mut [std::mem::MaybeUninit]>, frames: &Frames<'x>) -> crate::node::BatchStatus<'a> + fn eval_batch<'a, 'x, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'x>, scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &Frames<'x>) -> crate::node::BatchStatus<'r> where - C: crate::context::InjectIndex + Copy + crate::context::ExtractArena, + 'a: 'r, + 'x: 'r, + C: crate::dispatch::AsDispatch<'x> + crate::context::InjectIndex + Copy + crate::context::ExtractArena, { use crate::node::BatchStatus; + let range = dispatch.range(); let Some(plan) = &self.plan else { - return self.edge.eval_batch(input, range, scratch, frames); + return self.edge.eval_batch(dispatch, scratch, frames); }; let Some(scratch) = scratch else { return BatchStatus::NeedBuffer; @@ -154,8 +157,7 @@ where if scratch.len() * 8 < len * stride { return BatchStatus::InvalidRange; } - let arena = crate::context::ExtractArena::arena(input); - let (source, finality, hint) = match super::input::materialize_batch(&self.edge, input, range, arena, frames) { + let (source, finality, hint) = match super::input::materialize_dispatch::(&self.edge, &dispatch, dispatch.scope().arena(), frames) { BatchStatus::Lent(batch, finality, hint) => (batch, finality, hint), BatchStatus::Filled(batch, finality, hint) => (batch.into_shared(), finality, hint), BatchStatus::Pending => return BatchStatus::Pending, diff --git a/node-graph/libraries/core-types/src/record/serve.rs b/node-graph/libraries/core-types/src/record/serve.rs index fdbdef4950..6de7b3eb97 100644 --- a/node-graph/libraries/core-types/src/record/serve.rs +++ b/node-graph/libraries/core-types/src/record/serve.rs @@ -488,7 +488,7 @@ impl<'e> Served<'e> { pub fn serve_input<'e, C, N>(node: &N, input: &C, frames: &Frames<'e>) -> GPoll> where N: Node + ?Sized, - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { let slot = frames.claim(node.layout()); node.serve(input, slot).map(Served::value) diff --git a/node-graph/libraries/core-types/src/record/testkit.rs b/node-graph/libraries/core-types/src/record/testkit.rs index 8eeba90637..a8de908dd6 100644 --- a/node-graph/libraries/core-types/src/record/testkit.rs +++ b/node-graph/libraries/core-types/src/record/testkit.rs @@ -77,7 +77,7 @@ impl ServedRecord { pub fn capture<'e, C, N>(node: &N, ctx: &C, frames: &Frames<'e>) -> GPoll where N: Node + ?Sized, - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { let scope = frames.scope(); let layout = node.layout().clone(); @@ -119,7 +119,7 @@ where { fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll> where - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { slot.lift_served((self.kernel)(input), input.arena()) } @@ -146,7 +146,7 @@ mod tests { impl Node for Fixture { fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll> where - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { let offset = self.layout.offset_of(Transform::NAME, 0).expect("the fixture's layout carries the transform"); if slot.element(String::from("parked"), crate::context::ExtractArena::arena(input)).is_none() { diff --git a/node-graph/libraries/core-types/src/registry.rs b/node-graph/libraries/core-types/src/registry.rs index 0a93187d95..da74903b8d 100644 --- a/node-graph/libraries/core-types/src/registry.rs +++ b/node-graph/libraries/core-types/src/registry.rs @@ -167,7 +167,7 @@ where { fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll> where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { // SAFETY: `own` keeps the payload alive for `self`'s lifetime and Arc // payloads are address stable. @@ -176,7 +176,7 @@ where fn extent_at<'x>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'x>) -> crate::gpoll::GPoll where - Input: crate::context::ExtractArena, + Input: crate::dispatch::AsDispatch<'x> + crate::context::ExtractArena, { // SAFETY: as in serve. unsafe { self.ptr.as_ref() }.extent_at(input, level, frames) @@ -192,18 +192,19 @@ where unsafe { self.ptr.as_ref() }.layout() } - fn eval_batch<'a, 'x>( + fn eval_batch<'a, 'x, 'r>( &'a self, - input: &'a Input, - range: std::ops::Range, - scratch: Option<&'a mut [std::mem::MaybeUninit]>, + dispatch: crate::dispatch::Dispatch<'x>, + scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &crate::record::Frames<'x>, - ) -> crate::node::BatchStatus<'a> + ) -> crate::node::BatchStatus<'r> where - Input: crate::context::InjectIndex + Copy + crate::context::ExtractArena, + 'a: 'r, + 'x: 'r, + Input: crate::dispatch::AsDispatch<'x> + crate::context::InjectIndex + Copy + crate::context::ExtractArena, { // SAFETY: as in serve. - unsafe { self.ptr.as_ref() }.eval_batch(input, range, scratch, frames) + unsafe { self.ptr.as_ref() }.eval_batch(dispatch, scratch, frames) } } diff --git a/node-graph/libraries/core-types/src/value.rs b/node-graph/libraries/core-types/src/value.rs index 280cee333a..a2fdc35586 100644 --- a/node-graph/libraries/core-types/src/value.rs +++ b/node-graph/libraries/core-types/src/value.rs @@ -28,7 +28,7 @@ where { fn serve<'e, 'l>(&self, input: &C, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll> where - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { let arena = input.arena(); // An element the arena does not park has no pointer to share, so it takes the plain write @@ -86,7 +86,7 @@ where { fn serve<'e, 'l>(&self, input: &C, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll> where - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena, { let Some(value) = self.values.get(input.innermost_index() as usize) else { return crate::gpoll::GPoll::error("value level addressed past its items"); @@ -96,7 +96,7 @@ where fn extent_at<'x>(&self, _input: &C, level: u8, _frames: &crate::record::Frames<'x>) -> crate::gpoll::GPoll where - C: crate::context::ExtractArena, + C: crate::dispatch::AsDispatch<'x> + crate::context::ExtractArena, { match level { 0 => crate::gpoll::GPoll::Final(crate::gpoll::Extent::Exactly(self.values.len())), diff --git a/node-graph/libraries/graphic-types/src/boundary.rs b/node-graph/libraries/graphic-types/src/boundary.rs index 990e530904..e383313051 100644 --- a/node-graph/libraries/graphic-types/src/boundary.rs +++ b/node-graph/libraries/graphic-types/src/boundary.rs @@ -26,9 +26,11 @@ pub enum LevelGroup<'e> { /// The renderer's flip form: the wire's whole extent materialized into a /// group over the level's records, ready for the group render bridge. -pub fn materialize_group<'a, 'e, C, N>(node: &'a N, input: &'a C, arena: &'a Arena, frames: &core_types::record::Frames<'e>) -> LevelGroup<'a> +pub fn materialize_group<'a, 'e, 'r, C, N>(node: &'a N, input: &'a C, arena: &'a Arena, frames: &core_types::record::Frames<'e>) -> LevelGroup<'r> where - C: InjectIndex + Copy + core_types::context::ExtractArena, + 'a: 'r, + 'e: 'r, + C: core_types::dispatch::AsDispatch<'e> + InjectIndex + Copy + core_types::context::ExtractArena, N: Node, { match materialize_level(node, input, arena, frames) { diff --git a/node-graph/node-macro/src/codegen.rs b/node-graph/node-macro/src/codegen.rs index b8a621fbed..f9325ed2ee 100644 --- a/node-graph/node-macro/src/codegen.rs +++ b/node-graph/node-macro/src/codegen.rs @@ -955,7 +955,11 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn (None, false) => quote!('_), }; if bind_record_arena { - ctx_bounds.push(quote!(#core_types::context::ExtractArena)); + ctx_bounds.push(quote!(#core_types::dispatch::AsDispatch<'__record> + #core_types::context::ExtractArena)); + } + // A kernel naming its own arena lifetime batches at that lifetime. + if let Some(lifetime) = &declared_arena_lifetime { + ctx_bounds.push(quote!(#core_types::dispatch::AsDispatch<#lifetime>)); } let ctx_generic = match ctx_bounds.is_empty() { @@ -1697,7 +1701,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn quote! { fn extent_at<'__serve>(&self, __input: &#ctx_ident, __level: u8, __frames: &#core_types::record::Frames<'__serve>) -> #core_types::gpoll::GPoll<#core_types::gpoll::Extent> where - #ctx_ident: #core_types::context::ExtractArena, + #ctx_ident: #core_types::dispatch::AsDispatch<'__serve> + #core_types::context::ExtractArena, { #(#arg_decls)* let __level_in = #core_types::extent::LevelIn::new(__level, >::layout(self).depth); @@ -1710,7 +1714,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn quote! { fn extent_at<'__serve>(&self, __input: &#ctx_ident, __level: u8, __frames: &#core_types::record::Frames<'__serve>) -> #core_types::gpoll::GPoll<#core_types::gpoll::Extent> where - #ctx_ident: #core_types::context::ExtractArena, + #ctx_ident: #core_types::dispatch::AsDispatch<'__serve> + #core_types::context::ExtractArena, { #path(self, __input, __level, __frames) } @@ -1740,7 +1744,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn quote! { fn extent_at<'__serve>(&self, __input: &#ctx_ident, __level: u8, __frames: &#core_types::record::Frames<'__serve>) -> #core_types::gpoll::GPoll<#core_types::gpoll::Extent> where - #ctx_ident: #core_types::context::ExtractArena, + #ctx_ident: #core_types::dispatch::AsDispatch<'__serve> + #core_types::context::ExtractArena, { #query let __arg = #core_types::extent::ExtentIn::new(&__query); @@ -1754,7 +1758,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn quote! { fn extent_at<'__serve>(&self, _: &#ctx_ident, _: u8, _: &#core_types::record::Frames<'__serve>) -> #core_types::gpoll::GPoll<#core_types::gpoll::Extent> where - #ctx_ident: #core_types::context::ExtractArena, + #ctx_ident: #core_types::dispatch::AsDispatch<'__serve> + #core_types::context::ExtractArena, { #core_types::gpoll::GPoll::Final(#core_types::gpoll::Extent::AtLeast(0)) } @@ -1776,15 +1780,16 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }; let batch_signature = quote! { - fn eval_batch<'__batch, '__serve>( + fn eval_batch<'__batch, '__serve, '__out>( &'__batch self, - __input: &'__batch #ctx_ident, - __range: ::std::ops::Range, - __scratch: Option<&'__batch mut [::std::mem::MaybeUninit]>, + __dispatch: #core_types::dispatch::Dispatch<'__serve>, + __scratch: Option<&'__out mut [::std::mem::MaybeUninit]>, __frames: &#core_types::record::Frames<'__serve>, - ) -> #core_types::node::BatchStatus<'__batch> + ) -> #core_types::node::BatchStatus<'__out> where - #ctx_ident: #core_types::context::InjectIndex + Copy + #core_types::context::ExtractArena, + '__batch: '__out, + '__serve: '__out, + #ctx_ident: #core_types::dispatch::AsDispatch<'__serve> + #core_types::context::InjectIndex + Copy + #core_types::context::ExtractArena, }; let produces_records = record_io || routing_generic.is_some() || flip; @@ -2378,9 +2383,10 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn (Some(path), ..) => quote! { #batch_signature { + let __range = __dispatch.range(); #[cfg(debug_assertions)] #core_types::record::note_kernel_batch(::std::stringify!(#fn_name), "hand", __range.end.saturating_sub(__range.start) as usize); - #path(self, __input, __range, __scratch, __frames) + #path(self, __dispatch, __scratch, __frames) } }, (None, true, Some(lane_poll)) => { @@ -2467,9 +2473,10 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn let mut __finality = #core_types::gpoll::Finality::AllFinal; let mut __hint = #core_types::gpoll::Extent::AtLeast(__range.end as usize); #subject_prologue - let mut __lane_ctx = __base_ctx; for __lane in 0..__len { - #core_types::context::InjectIndex::set_index(&mut __lane_ctx, __range.start + __lane as u64); + let ::core::option::Option::Some(__lane_ctx) = <#ctx_ident as #core_types::dispatch::AsDispatch<'__serve>>::at_lane(&__dispatch, __range.start + __lane as u64) else { + return #core_types::node::BatchStatus::Error(#core_types::gpoll::GraphError { kind: #core_types::gpoll::ErrorKind::ArenaExhausted, trace: ::std::vec::Vec::new() }); + }; let __input = &__lane_ctx; // The lane's inputs claim beyond its slab region, and their // space is free again at the next lane. @@ -2521,6 +2528,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn quote! { #batch_signature { + let __range = __dispatch.range(); let ::core::option::Option::Some(__scratch) = __scratch else { return #core_types::node::BatchStatus::NeedBuffer; }; @@ -2534,10 +2542,8 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn // the caller's free space comes back as it was lent. let __frames = __frames.scope(); let __cell = #cell_constructor; - let __base_ctx = { - let mut __ctx = *__input; - #core_types::context::InjectIndex::set_index(&mut __ctx, __range.start); - __ctx + let ::core::option::Option::Some(__base_ctx) = <#ctx_ident as #core_types::dispatch::AsDispatch<'__serve>>::at_lane(&__dispatch, __range.start) else { + return #core_types::node::BatchStatus::Error(#core_types::gpoll::GraphError { kind: #core_types::gpoll::ErrorKind::ArenaExhausted, trace: ::std::vec::Vec::new() }); }; let __input = &__base_ctx; #selected_fill @@ -2549,14 +2555,16 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn (None, true, None) => quote! { #batch_signature { + let __range = __dispatch.range(); #[cfg(debug_assertions)] #core_types::record::note_kernel_batch(::std::stringify!(#fn_name), "eager-forward", __range.end.saturating_sub(__range.start) as usize); - #core_types::record::fill_frames(self, __input, __range, __scratch, __frames) + #core_types::record::fill_dispatch::<#ctx_ident, _>(self, &__dispatch, __scratch, __frames) } }, (None, false, _) => quote! { #batch_signature { + let __range = __dispatch.range(); #[cfg(debug_assertions)] #core_types::record::note_kernel_batch(::std::stringify!(#fn_name), "unbatched", __range.end.saturating_sub(__range.start) as usize); #core_types::node::BatchStatus::Unbatched @@ -2978,7 +2986,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn { fn serve<'__serve, '__slot>(&self, __input: &#ctx_ident, __slot: #core_types::record::FrameClaim<'__serve, '__slot>) -> #core_types::gpoll::GPoll<#core_types::record::Served<'__serve>> where - #ctx_ident: #core_types::context::ExtractArena, + #ctx_ident: #core_types::dispatch::AsDispatch<'__serve> + #core_types::context::ExtractArena, { #frame_entry let __cell = #cell_constructor; diff --git a/node-graph/nodes/gcore/src/context_modification.rs b/node-graph/nodes/gcore/src/context_modification.rs index ee0b3a9d3e..1be79b6b75 100644 --- a/node-graph/nodes/gcore/src/context_modification.rs +++ b/node-graph/nodes/gcore/src/context_modification.rs @@ -27,49 +27,52 @@ fn context_modification( value.eval(&ctx.nullified(modification.features, index, &scope)) } -/// The boundary's batch: the scope and index chain derive once for the whole -/// range, and the value answers the range through the caller's scratch, so a -/// consumer reading a level below a boundary walks the boundary once rather -/// than once per lane. -fn context_modification_batch<'batch, 'serve, Input, Value, Modification>( +/// The boundary's batch: the scope, features and index levels narrow once for +/// the whole range, and the value answers the range through the caller's +/// scratch, so a consumer reading a level below a boundary walks the +/// boundary once rather than once per lane. +fn context_modification_batch<'batch, 'serve, 'r, Input, Value, Modification>( node: &'batch _context_modification_mod::ContextModificationNode, - input: &'batch Input, - range: std::ops::Range, - scratch: Option<&'batch mut [std::mem::MaybeUninit]>, + dispatch: core_types::dispatch::Dispatch<'serve>, + scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &core_types::record::Frames<'serve>, -) -> core_types::node::BatchStatus<'batch> +) -> core_types::node::BatchStatus<'r> where - Input: Ctx + DeriveCtx + InjectIndex + Copy + core_types::context::ExtractArena, + 'batch: 'r, + 'serve: 'r, + Input: Ctx + DeriveCtx + InjectIndex + Copy + core_types::dispatch::AsDispatch<'serve> + core_types::context::ExtractArena, Value: for<'derived> core_types::record::DerivedRecordInput<'derived, core_types::context::Derived<'derived, Input>>, Modification: core_types::node::Node, _context_modification_mod::ContextModificationNode: core_types::node::Node, { use core_types::node::BatchStatus; + let exhausted = || { + BatchStatus::Error(GraphError { + kind: ErrorKind::ArenaExhausted, + trace: Vec::new(), + }) + }; + let range = dispatch.range(); + let Some(base) = Input::at_lane(&dispatch, range.start) else { + return exhausted(); + }; let cell = core_types::node::StatusCell::new(); - let modification = match cell.eval_input(1, &node.modification, input, frames) { + let modification = match cell.eval_input(1, &node.modification, &base, frames) { // SAFETY: input 1 is the modification, read at the layout resolved for it. Ok(value) => unsafe { core_types::record::read_element::(node.__in_1.rec(&value)) }, Err(interrupt) => return interrupt.into(), }; - let scope = input.scope().nullified_through(modification.features, Some(modification.sources()), &node.remembered); - let index = match modification.features.contains(ContextFeatures::INDEX) { - true => match nullify_index_levels(input.index_head(), modification.index_levels, scope.arena()) { - Some(index) => index, - None => { - return BatchStatus::Error(GraphError { - kind: ErrorKind::ArenaExhausted, - trace: Vec::new(), - }); - } - }, - false => IndexLink { index: 0, outer: None }, + let scope = dispatch.scope().nullified_through(modification.features, Some(modification.sources()), &node.remembered); + let levels = match modification.features.contains(ContextFeatures::INDEX) { + true => modification.index_levels, + false => core_types::context::IndexLevels::empty(), }; - let derived = input.nullified(modification.features, index, &scope); + let derived = dispatch.keeping(modification.features).nullified(levels).with_scope(&scope); let layout = core_types::node::Node::::layout(node); - // Nothing below lends: the boundary serves the range itself, with the - // modification, scope and layout bound once rather than per lane. - let lanes = |scratch: &'batch mut [std::mem::MaybeUninit]| { + // Nothing below lends: the boundary serves the range itself from the + // narrowed dispatch, one context rebuilt per lane. + let lanes = |scratch: &'r mut [std::mem::MaybeUninit]| { use core_types::gpoll::{Extent, Finality}; #[cfg(debug_assertions)] core_types::record::note_kernel_batch("context_modification", "lane loop", range.end.saturating_sub(range.start) as usize); @@ -82,24 +85,12 @@ where let mut finality = Finality::AllFinal; let mut hint = Extent::AtLeast(range.end as usize); for lane in 0..len { - let mut local = *input; - local.set_index(range.start + lane as u64); - let index = match modification.features.contains(ContextFeatures::INDEX) { - true => match nullify_index_levels(local.index_head(), modification.index_levels, scope.arena()) { - Some(index) => index, - None => { - return BatchStatus::Error(GraphError { - kind: ErrorKind::ArenaExhausted, - trace: Vec::new(), - }); - } - }, - false => IndexLink { index: 0, outer: None }, + let Some(ctx) = as core_types::dispatch::AsDispatch<'_>>::at_lane(&derived, range.start + lane as u64) else { + return exhausted(); }; - let derived = local.nullified(modification.features, index, &scope); let lane_frames = frames.scope(); let slot = run.slot(lane, &lane_frames); - let served = match node.value.serve_derived(&derived, slot) { + let served = match node.value.serve_derived(&ctx, slot) { GPoll::Final(served) => served, GPoll::Partial(served) => { finality = Finality::Partial; @@ -118,5 +109,5 @@ where } BatchStatus::Filled(run.finish(), finality, hint) }; - core_types::record::forward_batch(&node.value, &derived, range.clone(), scratch, frames, layout, lanes) + core_types::record::forward_dispatch(&node.value, &derived, scratch, frames, layout, lanes) } diff --git a/node-graph/nodes/gcore/src/memo.rs b/node-graph/nodes/gcore/src/memo.rs index f484604584..3109c7d68b 100644 --- a/node-graph/nodes/gcore/src/memo.rs +++ b/node-graph/nodes/gcore/src/memo.rs @@ -179,15 +179,16 @@ impl MemoTable { /// span is exactly that: one flat buffer in the persistent region, so the run is a view of it /// and the caller reads the published bytes in place. A miss goes unbatched, which runs the /// per-lane path and leaves the level published for the next caller. -fn frame_memo_batch<'batch, 'serve, C, N>( +fn frame_memo_batch<'batch, 'serve, 'r, C, N>( node: &'batch _frame_memo_mod::FrameMemoNode, - input: &'batch C, - range: std::ops::Range, - scratch: Option<&'batch mut [std::mem::MaybeUninit]>, + dispatch: core_types::dispatch::Dispatch<'serve>, + scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &core_types::record::Frames<'serve>, -) -> core_types::node::BatchStatus<'batch> +) -> core_types::node::BatchStatus<'r> where - C: Ctx + CacheHash + DeriveCtx + core_types::context::ExtractArena + ModifyIndex + Copy, + 'batch: 'r, + 'serve: 'r, + C: Ctx + CacheHash + DeriveCtx + core_types::dispatch::AsDispatch<'serve> + core_types::context::ExtractArena + ModifyIndex + Copy, N: core_types::node::Node, { use core_types::gpoll::Extent; @@ -195,10 +196,16 @@ where let content = &node.content; let layout = content.layout(); - let mut keyed = *input; - keyed.set_index(0); - let key = cache_key(&keyed); - let persistent = input.scope().persistent(); + let range = dispatch.range(); + let key = dispatch.key(); + let persistent = dispatch.scope().persistent(); + let arena = dispatch.scope().arena(); + let exhausted = || { + BatchStatus::Error(core_types::gpoll::GraphError { + kind: core_types::gpoll::ErrorKind::ArenaExhausted, + trace: Vec::new(), + }) + }; let (Ok(start), Ok(end)) = (usize::try_from(range.start), usize::try_from(range.end)) else { return BatchStatus::InvalidRange; }; @@ -236,13 +243,13 @@ where } #[cfg(debug_assertions)] core_types::record::note_kernel_batch("frame_memo", "scalar fill", len); - let filled = core_types::record::forward_batch(content, input, range.clone(), Some(scratch), frames, layout, |scratch| { - core_types::record::fill_frames(content, input, range.clone(), Some(scratch), frames) + let filled = core_types::record::forward_dispatch(content, &dispatch, Some(scratch), frames, layout, |scratch| { + core_types::record::fill_dispatch::(content, &dispatch, Some(scratch), frames) }); let BatchStatus::Filled(batch, finality, hint) = filled else { return filled; }; - let promotion = Promotion::new(input.arena(), frames.bounds(), persistent); + let promotion = Promotion::new(arena, frames.bounds(), persistent); let mut table = node.cache.lock().unwrap(); let span = table.for_generation(persistent).lanes.entry(key).or_insert_with(|| LaneSpan::new(persistent)); for lane in 0..batch.len() { @@ -260,24 +267,25 @@ where // caller to walk this boundary lane by lane. let (span, finality) = match entry { Some(entry) => entry, - None => match { + None => { #[cfg(debug_assertions)] core_types::record::note_kernel_batch("frame_memo", "miss materialize", end.saturating_sub(start)); - core_types::record::materialize_level(content, input, input.arena(), frames) - } { - LevelStatus::Batch(batch, finality) => { - let promotion = Promotion::new(input.arena(), frames.bounds(), persistent); - // SAFETY: the batch came from this input, so it carries the input's layout. - let Some(span) = (unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }) else { - return BatchStatus::Unbatched; - }; - probe_memo_publish(&node.cache, true, batch.len(), layout.frame_bytes(), true); - node.cache.lock().unwrap().for_generation(persistent).levels.insert(key, SpanLevel { span, finality }); - (span, finality) + let Some(input) = C::at_lane(&dispatch, range.start) else { return exhausted() }; + match core_types::record::materialize_level(content, &input, arena, frames) { + LevelStatus::Batch(batch, finality) => { + let promotion = Promotion::new(arena, frames.bounds(), persistent); + // SAFETY: the batch came from this input, so it carries the input's layout. + let Some(span) = (unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }) else { + return BatchStatus::Unbatched; + }; + probe_memo_publish(&node.cache, true, batch.len(), layout.frame_bytes(), true); + node.cache.lock().unwrap().for_generation(persistent).levels.insert(key, SpanLevel { span, finality }); + (span, finality) + } + LevelStatus::Pending => return BatchStatus::Pending, + LevelStatus::Error(error) => return BatchStatus::Error(error), } - LevelStatus::Pending => return BatchStatus::Pending, - LevelStatus::Error(error) => return BatchStatus::Error(error), - }, + } }; let Some(published) = span.batch(persistent, layout) else { return BatchStatus::Unbatched; @@ -300,7 +308,7 @@ where /// through, since the span is flat across its levels and could not be read apart. fn frame_memo_extent<'e, C, N>(node: &_frame_memo_mod::FrameMemoNode, ctx: &C, level: u8, frames: &core_types::record::Frames<'e>) -> GPoll where - C: Ctx + CacheHash + DeriveCtx + core_types::context::ExtractArena + ModifyIndex + Copy, + C: Ctx + CacheHash + DeriveCtx + core_types::dispatch::AsDispatch<'e> + core_types::context::ExtractArena + ModifyIndex + Copy, N: core_types::node::Node, { use core_types::gpoll::Extent; @@ -961,23 +969,27 @@ fn extent_cache_enabled() -> bool { /// The monitor's batch: the snapshot is lane zero's, and the content answers /// the range through the caller's scratch. -fn monitor_batch<'batch, 'serve, C, N>( +fn monitor_batch<'batch, 'serve, 'r, C, N>( node: &'batch _monitor_mod::MonitorNode, - input: &'batch C, - range: std::ops::Range, - scratch: Option<&'batch mut [std::mem::MaybeUninit]>, + dispatch: core_types::dispatch::Dispatch<'serve>, + scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &core_types::record::Frames<'serve>, -) -> core_types::node::BatchStatus<'batch> +) -> core_types::node::BatchStatus<'r> where - C: Ctx + DeriveCtx + ExtractAll + core_types::context::ExtractArena + ModifyIndex + Copy, + 'batch: 'r, + 'serve: 'r, + C: Ctx + DeriveCtx + ExtractAll + core_types::dispatch::AsDispatch<'serve> + core_types::context::ExtractArena + ModifyIndex + Copy, N: core_types::node::Node, { - if range.start == 0 && input.index() == 0 { - *node.io.lock().unwrap() = Some(CtxSnapshot::capture(input)); + if dispatch.range().start == 0 + && let Some(first) = C::at_lane(&dispatch, 0) + && first.index() == 0 + { + *node.io.lock().unwrap() = Some(CtxSnapshot::capture(&first)); } let content = &node.content; let layout = content.layout(); - core_types::record::forward_batch(content, input, range.clone(), scratch, frames, layout, |scratch| { - core_types::record::fill_frames(content, input, range.clone(), Some(scratch), frames) + core_types::record::forward_dispatch(content, &dispatch, scratch, frames, layout, |scratch| { + core_types::record::fill_dispatch::(content, &dispatch, Some(scratch), frames) }) } diff --git a/node-graph/nodes/gcore/src/record.rs b/node-graph/nodes/gcore/src/record.rs index a497c16915..3d0e3f9a32 100644 --- a/node-graph/nodes/gcore/src/record.rs +++ b/node-graph/nodes/gcore/src/record.rs @@ -1288,9 +1288,22 @@ mod tests { let head = ctx.index_head(); let scoped = ctx.promoted(&head, 0); - assert!(matches!(node.eval_batch(&scoped, 0..6, None, &frames), core_types::node::BatchStatus::NeedBuffer)); + assert!(matches!( + core_types::node::Node::>::eval_batch( + &node, + core_types::dispatch::AsDispatch::dispatch(&scoped, core_types::dispatch::LaneMap::open(), 0..6), + None, + &frames + ), + core_types::node::BatchStatus::NeedBuffer + )); let mut scratch = vec![std::mem::MaybeUninit::::uninit(); 6 * out.lane_stride() / 8]; - let core_types::node::BatchStatus::Filled(batch, finality, _) = node.eval_batch(&scoped, 0..6, Some(&mut scratch), &frames) else { + let core_types::node::BatchStatus::Filled(batch, finality, _) = core_types::node::Node::>::eval_batch( + &node, + core_types::dispatch::AsDispatch::dispatch(&scoped, core_types::dispatch::LaneMap::open(), 0..6), + Some(&mut scratch), + &frames, + ) else { panic!("expected a filled batch"); }; assert_eq!(finality, core_types::gpoll::Finality::AllFinal); @@ -1349,7 +1362,12 @@ mod tests { let scoped = ctx.promoted(&head, 0); let mut scratch = vec![std::mem::MaybeUninit::::uninit(); 6 * out.lane_stride() / 8]; - let core_types::node::BatchStatus::Filled(batch, ..) = node.eval_batch(&scoped, 0..6, Some(&mut scratch), &frames) else { + let core_types::node::BatchStatus::Filled(batch, ..) = core_types::node::Node::>::eval_batch( + &node, + core_types::dispatch::AsDispatch::dispatch(&scoped, core_types::dispatch::LaneMap::open(), 0..6), + Some(&mut scratch), + &frames, + ) else { panic!("expected a filled batch"); }; assert_eq!(batch.len(), 6); @@ -1390,7 +1408,12 @@ mod tests { let scoped = ctx.promoted(&head, 0); let mut scratch = vec![std::mem::MaybeUninit::::uninit(); 6 * out.lane_stride() / 8]; - let core_types::node::BatchStatus::Filled(batch, ..) = node.eval_batch(&scoped, 0..6, Some(&mut scratch), &frames) else { + let core_types::node::BatchStatus::Filled(batch, ..) = core_types::node::Node::>::eval_batch( + &node, + core_types::dispatch::AsDispatch::dispatch(&scoped, core_types::dispatch::LaneMap::open(), 0..6), + Some(&mut scratch), + &frames, + ) else { panic!("expected a filled batch"); }; assert_eq!(batch.len(), 6); diff --git a/node-graph/nodes/graphic/src/record.rs b/node-graph/nodes/graphic/src/record.rs index 0cd4ae990a..ce437c089f 100644 --- a/node-graph/nodes/graphic/src/record.rs +++ b/node-graph/nodes/graphic/src/record.rs @@ -560,7 +560,7 @@ mod tests { let scoped = ctx.promoted(&head, 0); let mut scratch = vec![std::mem::MaybeUninit::::uninit(); 5 * out.lane_stride() / 8]; - let core_types::node::BatchStatus::Filled(batch, ..) = node.eval_batch(&scoped, 0..5, Some(&mut scratch), &frames) else { + let core_types::node::BatchStatus::Filled(batch, ..) = core_types::node::Node::>::eval_batch(&node, core_types::dispatch::AsDispatch::dispatch(&scoped, core_types::dispatch::LaneMap::open(), 0..5), Some(&mut scratch), &frames) else { panic!("expected a filled batch"); }; let batch = batch.into_shared(); @@ -1006,7 +1006,7 @@ mod tests { let scoped = ctx.promoted(&head, 0); let mut scratch = vec![std::mem::MaybeUninit::::uninit(); 3 * out.lane_stride() / 8]; - let core_types::node::BatchStatus::Filled(batch, ..) = node.eval_batch(&scoped, 0..3, Some(&mut scratch), &frames) else { + let core_types::node::BatchStatus::Filled(batch, ..) = core_types::node::Node::>::eval_batch(&node, core_types::dispatch::AsDispatch::dispatch(&scoped, core_types::dispatch::LaneMap::open(), 0..3), Some(&mut scratch), &frames) else { panic!("expected a filled batch"); }; let batch = batch.into_shared(); diff --git a/node-graph/nodes/math/src/lib.rs b/node-graph/nodes/math/src/lib.rs index 91b503f26d..ecd5bb810c 100644 --- a/node-graph/nodes/math/src/lib.rs +++ b/node-graph/nodes/math/src/lib.rs @@ -1753,7 +1753,7 @@ mod graphene_test { let erased: Box = Box::new(node); // One u64 word per lane at the element-only layout. let mut scratch = [const { MaybeUninit::uninit() }; 4]; - let status = erased.eval_batch(&ctx, 2..6, Some(&mut scratch), &frames); + let status = erased.eval_batch(core_types::dispatch::AsDispatch::dispatch(&ctx, core_types::dispatch::LaneMap::open(), 2..6), Some(&mut scratch), &frames); let BatchStatus::Filled(batch, finality, _) = status else { panic!("expected filled, got {status:?}"); }; diff --git a/node-graph/nodes/text/src/lib.rs b/node-graph/nodes/text/src/lib.rs index 8fa91778f4..4ced993eb7 100644 --- a/node-graph/nodes/text/src/lib.rs +++ b/node-graph/nodes/text/src/lib.rs @@ -857,15 +857,16 @@ fn string_split<'e>( /// Serves a whole range of lanes from one walk of the rows, instead of re-walking them for /// each lane. A split level is read lane by lane by its consumer, so the per-lane form costs /// a scan per lane and this costs one scan per range. -fn string_split_batch<'batch, 'serve, Input, Primary, Strings, Delimiter, Escaping>( +fn string_split_batch<'batch, 'serve, 'r, Input, Primary, Strings, Delimiter, Escaping>( node: &'batch _string_split_mod::StringSplitNode, - input: &'batch Input, - range: std::ops::Range, - scratch: Option<&'batch mut [std::mem::MaybeUninit]>, + dispatch: core_types::dispatch::Dispatch<'serve>, + scratch: Option<&'r mut [std::mem::MaybeUninit]>, frames: &core_types::record::Frames<'serve>, -) -> core_types::node::BatchStatus<'batch> +) -> core_types::node::BatchStatus<'r> where - Input: Ctx + ExtractIndex + InjectIndex + Copy + core_types::context::ExtractArena, + 'batch: 'r, + 'serve: 'r, + Input: Ctx + ExtractIndex + InjectIndex + Copy + core_types::dispatch::AsDispatch<'serve> + core_types::context::ExtractArena, Primary: core_types::node::Node, Strings: core_types::node::Node, Delimiter: core_types::node::Node, @@ -873,6 +874,11 @@ where { use core_types::node::BatchStatus; + let range = dispatch.range(); + let Some(input) = Input::at_lane(&dispatch, range.start) else { + return BatchStatus::Error(GraphError::new("string split could not rebuild its context")); + }; + let input = &input; let Some(scratch) = scratch else { return BatchStatus::NeedBuffer }; let Ok(len) = usize::try_from(range.end.saturating_sub(range.start)) else { return BatchStatus::InvalidRange;