Compare commits

...
Author SHA1 Message Date
Dennis Kobert df99ab3a72 Guard attribute writes against an uninstalled layout offset 2026-09-07 16:12:01 +00:00
Dennis Kobert 0fc4424a09 State the disjointness a plan's copies require 2026-09-07 16:11:56 +00:00
Dennis Kobert e9a3199456 State what contains the laundered arena borrow in the flatten test 2026-09-07 16:11:32 +00:00
Dennis Kobert ef8312806d Serve the probe record the forwarding test finishes 2026-09-07 16:11:32 +00:00
Dennis Kobert 548cbfbf4e Check the claim's layout when replaying an owned record 2026-09-07 16:11:32 +00:00
Dennis Kobert 313c591f70 State from_resident's borrow-window contract at its call sites 2026-09-07 16:11:32 +00:00
Dennis Kobert f07f708ee8 Back the owned-item tests' lanes with word storage 2026-09-07 16:03:10 +00:00
Dennis Kobert 5f73044b6b Back the repark test's element slot with word storage 2026-09-07 16:03:10 +00:00
Dennis Kobert 11aedd8196 Refuse record layouts wider than the frame tier's alignment 2026-09-07 16:03:10 +00:00
Dennis Kobert f4f266b1ba Refuse a lift that never filled its layout's fields 2026-09-07 15:56:28 +00:00
Dennis Kobert 77e4e8c894 Bound and order the lanes a serve run records as filled 2026-09-07 15:51:08 +00:00
Dennis Kobert c231bd0eb8 Check the serve run's lane capacity arithmetic 2026-09-07 15:50:32 +00:00
Dennis Kobert 095e0bb4ff Require content glue for a group's element 2026-09-07 15:39:00 +00:00
Dennis Kobert 369f7db992 Copy records out untyped instead of through a byte slice 2026-09-07 15:38:53 +00:00
Dennis Kobert 79750fb52d Stage attribute default bytes through zeroed storage 2026-09-07 15:38:11 +00:00
13 changed files with 243 additions and 56 deletions

No files matched your search

+12 -4
View File
@@ -502,7 +502,9 @@ impl NodeRuntime {
// Graphic run: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
if type_id == std::any::TypeId::of::<Graphic>() {
if update_thumbnails {
// SAFETY: the batch is resident for the read.
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let bounds = graphene_std::renderer::graphic_list_bounding_box(&RunView::<Graphic>::new(&item)?, DAffine2::IDENTITY);
let group = Graphic::Group(Group { row: None, content: item });
@@ -514,7 +516,9 @@ impl NodeRuntime {
// clips content to those rectangles so anything outside isn't visible
else if type_id == std::any::TypeId::of::<Artboard>() {
if update_thumbnails {
// SAFETY: the batch is resident for the read.
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<Artboard>::new(&item)?;
let bounds = artboard_clip_bounds(&run);
@@ -524,7 +528,9 @@ impl NodeRuntime {
}
// Vector run: vector modifications
else if type_id == std::any::TypeId::of::<Vector>() {
// SAFETY: the batch is resident for the read.
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<Vector>::new(&item)?;
use graphene_std::core_types::lane::LaneSource;
@@ -534,7 +540,9 @@ impl NodeRuntime {
// String run: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
else if type_id == std::any::TypeId::of::<String>() {
if update_thumbnails {
// SAFETY: the batch is resident for the read.
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<String>::new(&item)?;
let bounds = graphene_std::renderer::text_list_bounding_box(&run, DAffine2::IDENTITY);
@@ -154,10 +154,15 @@ pub struct AttributeInfo {
pub write_stored: unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>,
}
/// The default's object representation, staged through zeroed storage so a
/// value with padding or an unused payload (`Option<f64>`'s `None`) hands the
/// caller deterministic bytes rather than whatever the stack held.
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
assert_eq!(out.len(), size_of::<A::Value<'static>>());
let value: A::Value<'static> = A::default();
unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
let mut staged = std::mem::MaybeUninit::<A::Value<'static>>::zeroed();
staged.write(A::default());
// SAFETY: the staging holds a live value of the type `out` is sized for.
unsafe { std::ptr::copy_nonoverlapping(staged.as_ptr().cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
}
fn field_write_at<A: Attribute>(level: u8) -> crate::record::FieldWrite
+3 -2
View File
@@ -106,9 +106,10 @@ pub struct RecordBatchMut<'a> {
impl<'a> RecordBatchMut<'a> {
/// Minted only by a [`crate::record::SlotRun`] finishing its served lanes,
/// which is what makes the initialized prefix a fact rather than a contract.
/// which serve in ascending order with no gaps, so the initialized prefix is
/// a fact rather than a contract.
pub(crate) fn new(scratch: &'a mut [MaybeUninit<u64>], len: usize, layout: &'a crate::record::Layout) -> Self {
debug_assert!(len * layout.lane_stride() <= scratch.len() * 8);
debug_assert!(len.checked_mul(layout.lane_stride()).is_some_and(|need| need <= scratch.len() * 8));
Self { scratch, len, layout }
}
@@ -221,7 +221,9 @@ pub(in crate::record) unsafe fn lift_poll_into<'e, T: Send + Sync + dyn_any::Sta
/// # Safety
/// `src` must be a record of the plan's source layout and `dst` a buffer of
/// the plan's target layout; both are proven at wiring.
/// the plan's target layout; both are proven at wiring. The two records must
/// not overlap: a plan routinely carries identity moves, so each entry copies
/// non-overlapping and an aliasing pair is undefined on the first copy.
pub unsafe fn apply_plan(src: Rec<'_>, dst: *mut u8, plan: &[(usize, usize, usize)]) {
for &(from, to, size) in plan {
unsafe { std::ptr::copy_nonoverlapping(src.ptr().add(from), dst.add(to), size) };
@@ -111,6 +111,7 @@ impl<'e> Frames<'e> {
inline: RecordValue::zeroed(),
frame,
free: self.reborrow(),
filled_fields: false,
}
}
@@ -90,7 +90,10 @@ where
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
let words = len * node.layout().lane_stride() / 8;
// Checked: a wrapped product would size the scratch below the run.
let Some(words) = len.checked_mul(node.layout().lane_stride()).map(|bytes| bytes / 8) else {
return BatchStatus::InvalidRange;
};
let exhausted = || {
BatchStatus::Error(crate::gpoll::GraphError {
kind: crate::gpoll::ErrorKind::ArenaExhausted,
@@ -155,6 +155,11 @@ impl Default for ElementWrite {
}
}
/// The widest alignment a record may need. Frames are a `Vec<u64>`, lanes
/// stride at a multiple of 8, and run slabs come from `alloc_scratch::<u64>`,
/// so nothing below a record can promise more.
pub const MAX_ALIGN: usize = 8;
/// A record layout: the element at offset 0, then the written attributes in
/// canonical order (descending alignment, then size, then name, then level).
/// Layouts are derived data, a pure function of the upstream write set.
@@ -198,8 +203,9 @@ impl Layout {
/// The union of this layout's fields and `writes` over `element` at
/// `depth`, in canonical order. A (name, level) written at a different
/// size is a type conflict and panics; the census keeps declared names to
/// one type, so this only fires on wiring bugs.
/// size is a type conflict and panics, as does an element or attribute
/// wider than [`MAX_ALIGN`]; the census keeps declared names to one type,
/// so these only fire on wiring bugs.
pub fn with_writes(&self, depth: u8, element: ElementWrite, writes: &[FieldWrite]) -> Layout {
let mut merged: Vec<FieldWrite> = self.fields.iter().map(FieldDesc::as_write).collect();
for &write in writes {
@@ -208,6 +214,10 @@ impl Layout {
None => merged.push(write),
}
}
assert!(element.align <= MAX_ALIGN, "a record element aligns to at most {MAX_ALIGN} bytes, but this one needs {}", element.align);
for write in &merged {
assert!(write.align <= MAX_ALIGN, "attribute `{}` aligns to at most {MAX_ALIGN} bytes, but needs {}", write.name, write.align);
}
merged.sort_by(|a, b| b.align.cmp(&a.align).then(b.size.cmp(&a.size)).then(a.name.cmp(b.name)).then(a.level.cmp(&b.level)));
let mut offset = element.size;
let mut align = element.align.max(1);
@@ -619,6 +629,18 @@ mod tests {
assert_eq!(layout.align, 8);
}
#[test]
#[should_panic(expected = "a record element aligns to at most 8 bytes")]
fn an_over_aligned_element_is_refused_at_wiring() {
Layout::default().with_writes(0, element_write::<u128>(), &[]);
}
#[test]
#[should_panic(expected = "attribute `wide` aligns to at most 8 bytes")]
fn an_over_aligned_attribute_is_refused_at_wiring() {
Layout::default().with_writes(0, element_write::<f64>(), &[sized_field("wide", 16, 16)]);
}
#[test]
#[should_panic(expected = "two different types")]
fn type_conflicts_panic() {
@@ -87,7 +87,10 @@ pub fn replay_field_value(value: &dyn crate::list::AnyAttributeValue, arena: &cr
pub struct OwnedRecord {
pub(in crate::record) bytes: Box<[u8]>,
pub(in crate::record) element: Option<Box<dyn std::any::Any + Send + Sync>>,
fields: Vec<(usize, Box<dyn crate::list::AnyAttributeValue>)>,
/// Each copied field's index in the copy's layout, that field's declared
/// value type, and the owned value. The type rides along so a replay can
/// re-check the field it resolves rather than trusting the caller's claim.
fields: Vec<(usize, std::any::TypeId, Box<dyn crate::list::AnyAttributeValue>)>,
}
impl std::fmt::Debug for OwnedRecord {
@@ -100,23 +103,39 @@ impl OwnedRecord {
/// # Safety
/// `rec` must be a live record of `layout`.
pub unsafe fn copy_out(layout: &Layout, rec: Rec<'_>) -> OwnedRecord {
let bytes: Box<[u8]> = unsafe { std::slice::from_raw_parts(rec.ptr(), layout.size) }.into();
// The element-to-field seam is never written, so the copy stays untyped:
// a `&[u8]` over the frame would read those bytes.
let mut staged = Vec::<u8>::with_capacity(layout.size);
let bytes = unsafe {
std::ptr::copy_nonoverlapping(rec.ptr(), staged.as_mut_ptr(), layout.size);
staged.set_len(layout.size);
staged.into_boxed_slice()
};
let element = layout.element.parked.then(|| unsafe { (layout.element.clone_out)(rec.ptr()) });
let fields = layout
.fields
.iter()
.enumerate()
.filter(|(_, field)| field.repark.is_some())
.map(|(index, field)| (index, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
.map(|(index, field)| (index, field.type_id, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
.collect();
OwnedRecord { bytes, element, fields }
}
/// Replays the copy into a caller's claim, re-parking droppable payloads
/// against `arena`; the claim's layout is the one the copy was taken at,
/// and `None` reports arena exhaustion.
/// against `arena`; `None` reports arena exhaustion. The claim's layout must
/// be the one the copy was taken at, which the checks below establish rather
/// than assume: the copy carries no layout of its own, so a mismatched claim
/// would otherwise write past the frame or re-park a field through another
/// field's glue.
pub fn replay_into(&self, slot: &mut FrameClaim<'_, '_>, arena: &crate::arena::Arena) -> Option<()> {
let layout = slot.layout;
assert_eq!(self.bytes.len(), layout.size, "a replay lands in the layout the copy was taken at");
assert_eq!(self.element.is_some(), layout.element.parked, "a replay lands in the layout the copy was taken at");
for &(index, type_id, _) in &self.fields {
let field = layout.fields.get(index).expect("a replay lands in the layout the copy was taken at");
assert_eq!(field.type_id, type_id, "a replay lands in the layout the copy was taken at");
}
self.write_into(layout, slot.dst(), arena)
}
@@ -125,7 +144,7 @@ impl OwnedRecord {
if let Some(element) = &self.element {
unsafe { (layout.element.repark)(&**element, dst, arena) }?;
}
for (index, value) in &self.fields {
for (index, _, value) in &self.fields {
let field = &layout.fields[*index];
let repark = field.repark.expect("copied fields carry re-park glue");
let resident = replay_field_value(&**value, arena)?;
@@ -142,6 +161,34 @@ mod tests {
use crate::record::frames::FrameArena;
use crate::record::layout::{FieldWrite, element_write};
#[test]
fn a_padded_layout_copies_out_without_reading_its_seam() {
// A 4-byte element before an 8-aligned field leaves [4, 8) unwritten.
let layout = Layout::default().with_writes(0, element_write::<u32>(), &[FieldWrite::of::<crate::attribute::Opacity>(0)]);
let offset = layout.offset_of("opacity", 0).unwrap();
assert_eq!((layout.element.size, offset), (4, 8), "the fixture needs the element-to-field seam");
let arena = crate::arena::Arena::new(1024).unwrap();
let scratch = arena.alloc_scratch::<u64>(layout.frame_bytes().div_ceil(8)).unwrap();
let base: *mut u8 = scratch.as_mut_ptr().cast();
unsafe { write_element(base, 7u32, &arena) }.unwrap();
unsafe { write_field::<f64>(base, offset, 0.5) };
let copy = unsafe { OwnedRecord::copy_out(&layout, Rec::new(base.cast_const())) };
let replay_arena = crate::arena::Arena::new(1024).unwrap();
let mut frame_arena = FrameArena::new();
frame_arena.reserve(layout.frame_bytes());
let frames = frame_arena.frames();
let mut slot = frames.claim(&layout);
copy.replay_into(&mut slot, &replay_arena).unwrap();
// SAFETY: the replay completes the record in the claimed frame.
let value = unsafe { slot.finish() };
let rec = layout.rec(&value);
assert_eq!(unsafe { read_element::<u32>(rec) }, 7);
assert_eq!(unsafe { rec.read::<f64>(offset) }, 0.5);
}
#[test]
fn owned_records_replay_re_parked_payloads_after_the_source_dies() {
let layout = Layout::default().with_writes(0, element_write::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
@@ -48,8 +48,8 @@ impl SourcePlan {
/// # Safety
/// `src` must be a record of this plan's source layout and `dst` a
/// buffer of the plan's union layout. The returned view borrows `dst`, so
/// `'d` must not outlive it.
/// buffer of the plan's union layout that does not overlap `src`. The
/// returned view borrows `dst`, so `'d` must not outlive it.
pub unsafe fn translate<'d>(&self, src: Rec<'_>, dst: *mut u8) -> Rec<'d> {
unsafe {
apply_plan(src, dst, &self.moves);
@@ -5,6 +5,15 @@ use super::layout::{ElementWrite, FieldOffset, FieldWrite, Layout, element_write
use super::owned::deep_field_glue;
use super::promote::{Promotion, promote_record};
/// A group's element is compared and hashed by content, so it needs glue: the
/// byte fallback would read a padded element type's uninitialized padding.
fn assert_element_glue(layout: &Layout) {
assert!(
layout.element.size == 0 || layout.element.content_hash.is_some(),
"a run's element adopts only with content glue; declare it with `element_write_hashed`"
);
}
/// Builds a resident run lane by lane: fresh frames in the arena at a layout
/// derived from the element glue and field writes, elements pushed in order
/// and attributes written onto pushed lanes. The finished item's frames are
@@ -22,7 +31,7 @@ impl<'e> RunBuilder<'e> {
/// `None` reports arena exhaustion.
pub fn new(arena: &'e crate::arena::Arena, element: ElementWrite, fields: &[FieldWrite], len: usize) -> Option<Self> {
let layout = Layout::default().with_writes(0, element, fields);
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
assert_element_glue(&layout);
for field in &layout.fields {
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
}
@@ -163,7 +172,7 @@ impl<'e> GroupItem<'e> {
/// bytes.
pub fn adopt(batch: crate::node::RecordBatch<'_>, arena: &'e crate::arena::Arena) -> Option<Self> {
let layout = batch.layout().clone();
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
assert_element_glue(&layout);
for field in &layout.fields {
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
}
@@ -239,11 +248,14 @@ impl<'e> GroupItem<'e> {
/// A `GroupItem` over the batch's frames, without copying.
///
/// # Safety
/// The frames must stay valid for the evaluation. Arena-resident batches
/// qualify, caller stack scratch does not.
/// The item borrows the batch's frames at `'e`, so the frames must stay
/// valid for the whole of `'e` and nothing derived from the item may outlive
/// it. Arena-resident batches span the evaluation; a caller's serve scratch
/// spans only the window it lends the batch for, which is sound exactly when
/// `'e` is bounded to that window.
pub unsafe fn from_resident(batch: crate::node::RecordBatch<'e>) -> Self {
let layout = batch.layout().clone();
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
assert_element_glue(&layout);
for field in &layout.fields {
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
}
@@ -279,7 +291,14 @@ impl<'e> GroupItem<'e> {
let frames = self.frames();
// SAFETY: the constructors store `len` lanes of `layout` at the
// layout's stride, and the erased glue reads each lane's own region.
let bytes: Box<[u8]> = unsafe { std::slice::from_raw_parts(frames, self.len * stride) }.into();
// A lane's seam and stride tail are never written, so the copy stays
// untyped: a `&[u8]` over the frames would read those bytes.
let mut staged = Vec::<u8>::with_capacity(self.len * stride);
let bytes = unsafe {
std::ptr::copy_nonoverlapping(frames, staged.as_mut_ptr(), self.len * stride);
staged.set_len(self.len * stride);
staged.into_boxed_slice()
};
let elements = self
.layout
.element
@@ -522,7 +541,12 @@ impl<'e> Group<'e> {
}
/// Compares one record region of `layout` by content. Regions without glue
/// compare as bytes, which is the content for unparked values.
/// compare as bytes, which is the content for unparked values. Only written
/// spans are read: the element's own bytes and each field's own bytes, never
/// the element-to-field seam or the lane's stride tail, which no writer
/// touches. The element always carries glue (`assert_element_glue`) and
/// `FieldWrite::of` always installs field glue, so a padded value's own
/// padding never reaches the byte fallback either.
unsafe fn record_content_eq(layout: &Layout, a: *const u8, b: *const u8) -> bool {
let bytes_eq = |offset: usize, size: usize| unsafe { std::slice::from_raw_parts(a.add(offset), size) == std::slice::from_raw_parts(b.add(offset), size) };
let element = match layout.element.content_eq {
@@ -607,7 +631,6 @@ impl graphene_hash::CacheHash for Group<'_> {
mod tests {
use super::*;
use crate::record::access::{read_element, write_field};
use crate::record::layout::element_write;
use crate::record::test_support::f64_field;
#[test]
@@ -618,7 +641,7 @@ mod tests {
let arena = crate::arena::Arena::new(4096).unwrap();
let transform = DAffine2::from_translation((5., 6.).into());
let mut builder = RunBuilder::new(&arena, element_write::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)], 2).unwrap();
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)], 2).unwrap();
for lane in 0..2 {
let lane = builder.push(lane as f64).unwrap();
builder.attr::<Transform>(lane, transform);
@@ -648,7 +671,7 @@ mod tests {
use crate::lane::LaneSource;
let arena = crate::arena::Arena::new(1024).unwrap();
let mut builder = RunBuilder::new(&arena, element_write::<f64>(), &[], 1).unwrap();
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[], 1).unwrap();
builder.push(0f64).unwrap();
let item = builder.finish();
let run = RunView::<f64>::new(&item).expect("the run holds f64 elements");
@@ -660,7 +683,7 @@ mod tests {
fn an_interior_run_already_persistent_is_shared() {
let transient = crate::arena::Arena::new(4096).unwrap();
let persistent = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
let stride = layout.lane_stride();
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
@@ -682,7 +705,7 @@ mod tests {
#[test]
fn adopting_within_one_region_shares_the_run() {
let arena = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
let stride = layout.lane_stride();
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
@@ -702,7 +725,7 @@ mod tests {
#[test]
fn adopted_lanes_round_trip_through_the_group_item() {
let arena = crate::arena::Arena::new(1024).unwrap();
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
let stride = layout.lane_stride();
let offset = layout.offset_of("opacity", 0).unwrap();
@@ -768,20 +791,21 @@ mod tests {
fn owned_items_replay_re_parked_payloads_after_the_source_dies() {
let layout = Layout::default().with_writes(0, element_write_hashed::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
let stride = layout.lane_stride();
let mut bytes = vec![0u8; stride * 2];
// Word storage: the parked element and the `&str` field are 8-aligned.
let mut bytes = vec![0u64; (stride * 2).div_ceil(8)];
let owned = {
let arena = crate::arena::Arena::new(1024).unwrap();
for lane in 0..2 {
let base = unsafe { bytes.as_mut_ptr().add(lane * stride) };
let base = unsafe { bytes.as_mut_ptr().cast::<u8>().add(lane * stride) };
unsafe { write_element(base, format!("element {lane}"), &arena) }.unwrap();
let (name, _) = arena.alloc(format!("field {lane}")).unwrap();
unsafe { write_field::<&str>(base, layout.offset_of("name", 0).unwrap(), name.as_str()) };
}
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr(), 2, &layout)) };
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr().cast(), 2, &layout)) };
item.copy_out()
};
bytes.fill(u8::MAX);
bytes.fill(u64::MAX);
let arena = crate::arena::Arena::new(1024).unwrap();
let replayed = owned.replay(&arena).unwrap();
@@ -862,10 +886,11 @@ mod tests {
#[should_panic(expected = "an owned item replays")]
fn an_owned_item_refuses_reads() {
let layout = Layout::default().with_writes(0, element_write_hashed::<String>(), &[]);
let mut bytes = vec![0u8; layout.lane_stride()];
// Word storage: the parked element slot holds an 8-aligned reference.
let mut bytes = vec![0u64; layout.lane_stride().div_ceil(8)];
let arena = crate::arena::Arena::new(1024).unwrap();
unsafe { write_element(bytes.as_mut_ptr(), String::from("parked"), &arena) }.unwrap();
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr(), 1, &layout)) };
unsafe { write_element(bytes.as_mut_ptr().cast(), String::from("parked"), &arena) }.unwrap();
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr().cast(), 1, &layout)) };
item.copy_out().lanes();
}
}
@@ -20,8 +20,13 @@ pub struct SlotRun<'a> {
}
impl<'a> SlotRun<'a> {
/// `None` where the scratch cannot hold `len` lanes. The products are
/// checked: the stride is a multiple of 8, so a wrapped one would pass the
/// capacity test vacuously.
pub(in crate::record) fn new(scratch: &'a mut [std::mem::MaybeUninit<u64>], len: usize, layout: &'a Layout) -> Option<SlotRun<'a>> {
(scratch.len() * 8 >= len * layout.lane_stride()).then_some(SlotRun { scratch, layout, len, filled: 0 })
let need = len.checked_mul(layout.lane_stride())?;
let capacity = scratch.len().checked_mul(8)?;
(capacity >= need).then_some(SlotRun { scratch, layout, len, filled: 0 })
}
pub fn layout(&self) -> &'a Layout {
@@ -41,20 +46,24 @@ impl<'a> SlotRun<'a> {
inline: RecordValue::zeroed(),
frame: (self.layout.frame_bytes() != 0).then_some(frame),
free: frames.reborrow(),
filled_fields: false,
}
}
/// Records lane `lane` as served; the proof came from that lane's slot. An
/// inline record rides the value's own storage, so it takes the one copy
/// the run makes.
/// the run makes. Lanes serve in ascending order with no gaps, so the
/// filled count is an initialized prefix rather than a high-water mark.
pub fn served(&mut self, lane: usize, proof: &Served<'_>) {
assert!(lane < self.len, "lane {lane} out of bounds for a run of {}", self.len);
assert_eq!(lane, self.filled, "lane {lane} serves out of order after {} filled lanes", self.filled);
if self.layout.size == 0 {
let stride = self.layout.lane_stride();
// SAFETY: in-bounds by the capacity check `new` made, and the lane
// takes the whole inline record.
// SAFETY: in-bounds by the assert against the capacity check `new`
// made, and the lane takes the whole inline record.
unsafe { std::ptr::copy_nonoverlapping(self.layout.rec(proof.record()).ptr(), self.scratch.as_mut_ptr().cast::<u8>().add(lane * stride), stride) };
}
self.filled = self.filled.max(lane + 1);
self.filled = lane + 1;
}
/// The served lanes as the caller's exclusive batch.
@@ -74,6 +83,9 @@ pub struct FrameClaim<'e, 'l> {
pub(in crate::record) inline: RecordValue<'static>,
pub(in crate::record) frame: Option<*mut u8>,
pub(in crate::record) free: Frames<'e>,
/// Set by the writes that fill the declared fields, so the safe closers can
/// refuse a field-bearing frame that was never filled.
pub(in crate::record) filled_fields: bool,
}
impl<'e, 'l> FrameClaim<'e, 'l> {
@@ -107,17 +119,27 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
///
/// # Safety
/// `src` must be a live record of the plan's source layout, and the plan
/// must be the wiring-resolved plan of this frame's layout.
/// must be the wiring-resolved plan of this frame's layout. `src` must not
/// overlap this frame; an input's frame is split off beyond the claim, so
/// serving the source through [`Self::frames`] establishes it.
pub unsafe fn carry(&mut self, src: Rec<'_>, plan: &[(usize, usize, usize)]) {
unsafe { apply_plan(src, self.dst(), plan) };
self.filled_fields = true;
}
/// Writes a field at its wiring-resolved offset.
///
/// # Safety
/// `offset` must be this layout's resolved offset for a field of `T`.
/// `offset` must be this layout's resolved offset for a field of `T`. A
/// generated write offset defaults to 0 until `set_layout` installs it, so
/// the debug assertion catches a serve that ran before the install.
pub unsafe fn attr_at<T>(&mut self, offset: usize, value: T) {
debug_assert!(
self.layout.fields.iter().any(|field| field.offset == offset),
"attribute write at an offset this layout does not carry; the layout must install before serving"
);
unsafe { write_field(self.dst(), offset, value) };
self.filled_fields = true;
}
/// Writes the element; `None` reports arena exhaustion for a parked
@@ -132,9 +154,17 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
/// Lifts a kernel's poll into the frame and closes it: the element
/// writes on value polls, every poll keeps the frame claimed, and arena
/// exhaustion of a parked element reports as an error poll. Panics where
/// the element does not match the wired layout.
/// the element does not match the wired layout, or where a field-bearing
/// layout closes on a frame no carry or field write ever filled, since the
/// [`Served`] proof certifies the whole record and the fields would be the
/// prior frame's bytes.
pub fn lift<T: Send + Sync + dyn_any::StaticTypeSized>(mut self, poll: GPoll<T>, arena: &'e crate::arena::Arena) -> GPoll<RecordValue<'e>> {
self.check_element::<T>();
assert!(
self.layout.fields.is_empty() || self.filled_fields,
"a layout with {} fields must carry or write them before lifting",
self.layout.fields.len()
);
let frame_bytes = self.layout.frame_bytes();
let dst = self.dst();
// SAFETY: the frame is this layout's fresh claim, the element check
@@ -150,6 +180,7 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
/// references outlive the serving evaluation.
pub unsafe fn fill_copy(&mut self, src: *const u8) {
unsafe { std::ptr::copy_nonoverlapping(src, self.dst(), self.layout.size) };
self.filled_fields = true;
}
/// The served record. The frame stays claimed for the consumer; the drop
@@ -196,10 +227,12 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
/// Translates a source record into the frame through a wiring-resolved plan.
///
/// # Safety
/// `src` must be a live record of `plan`'s source layout, and `plan` must
/// translate into this frame's layout.
/// `src` must be a live record of `plan`'s source layout, `plan` must
/// translate into this frame's layout, and `src` must not overlap this
/// frame, as [`Self::carry`] requires.
pub unsafe fn translate(&mut self, src: Rec<'_>, plan: &SourcePlan) {
unsafe { plan.translate(src, self.dst()) };
self.filled_fields = true;
}
}
@@ -312,6 +345,35 @@ mod tests {
frames.claim(&layout).element(1u32, &arena);
}
#[test]
fn a_run_refuses_a_lane_count_whose_stride_product_overflows() {
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 4];
let mut frame_arena = FrameArena::new();
frame_arena.reserve(64);
let frames = frame_arena.frames();
let wrapping = usize::MAX / layout.lane_stride() + 1;
assert!(frames.run(&mut scratch, wrapping, &layout).is_none(), "a wrapped capacity product must not pass the check");
}
#[test]
#[should_panic(expected = "serves out of order")]
fn a_run_refuses_a_gapped_serve() {
let arena = crate::arena::Arena::new(1024).unwrap();
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 8];
let mut frame_arena = FrameArena::new();
frame_arena.reserve(1 << 10);
let frames = frame_arena.frames();
let mut run = frames.run(&mut scratch, 3, &layout).unwrap();
let lane_frames = frames.scope();
let slot = run.slot(2, &lane_frames);
let GPoll::Final(proof) = slot.lift_served(GPoll::Final(1.0f64), &arena) else {
panic!("expected a final record");
};
run.served(2, &proof);
}
#[test]
fn a_claim_shortens_onto_a_derived_lifetime() {
fn shorten<'long: 'short, 'short, 'l>(claim: FrameClaim<'long, 'l>) -> FrameClaim<'short, 'l> {
+8 -2
View File
@@ -2859,8 +2859,14 @@ mod tests {
let frames = frames_for(&[&layout]);
let base = {
let probe = frames.scope();
// SAFETY: nothing reads the probe's record; only its address is taken.
let value = unsafe { probe.claim(&layout).finish() };
let mut claim = probe.claim(&layout);
claim.element(0f64, &arena).expect("the arena holds the element");
for name in ["opacity", "length"] {
// SAFETY: the offset is this claim's own layout's, at the f64 the field was declared with.
unsafe { claim.attr_at(layout.offset_of(name, 0).expect("the fixture declares the field"), 0f64) };
}
// SAFETY: the element and both fields complete the record.
let value = unsafe { claim.finish() };
layout.rec(&value).ptr()
};
+9 -4
View File
@@ -750,10 +750,11 @@ mod tests {
let copy = unsafe { (out.element.clone_out)(out.rec(&value).ptr()) };
let replay_arena = Arena::new(1 << 16).unwrap();
let mut slot = [0u8; 8];
unsafe { (out.element.repark)(&*copy, slot.as_mut_ptr(), &replay_arena) }.expect("the arena holds the replay");
// Word storage: a parked element slot holds an 8-aligned reference.
let mut slot = [0u64; 1];
unsafe { (out.element.repark)(&*copy, slot.as_mut_ptr().cast(), &replay_arena) }.expect("the arena holds the replay");
// SAFETY: the re-park wrote a parked `Graphic` element into `slot`.
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(record::Rec::new(slot.as_ptr())) }) else {
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(record::Rec::new(slot.as_ptr().cast())) }) else {
panic!("the replay restores the group element");
};
let item = &group.content;
@@ -880,7 +881,11 @@ mod tests {
let head = ctx.index_head();
let group = {
// SAFETY: the element is cloned out inside the scope, so no borrow
// into the frame escapes it.
// into the frame escapes it. The clone is shallow, so the `'static`
// the `GraphicSource` rows infer launders a borrow of `arena`: it is
// contained because `arena` outlives every use below and this test
// never resets it, so the interior stays resident for the whole
// generation the group is read in.
let scope = frames.scope();
let GPoll::Final(value) = record::serve_input(&wrapped, &ctx.promoted(&head, 0), &scope) else {
panic!("expected a final record");