feat(registry): checkpoint PLN-0176 foundations and validated partial integrations

This commit is contained in:
2026-10-07 17:49:46 +01:00
parent 01fab56cc6
commit 126a9e50e7
63 changed files with 8499 additions and 1462 deletions
@@ -0,0 +1,147 @@
//! Exact-width immutable native storage for a present multi-slot Dynamic.
use crate::resource_budget::{
Reservation, ResourceFailure, ResourceReason, RuntimeBudget, RuntimeResource as Q,
};
use crate::value_contract::ValueError;
use prometeu_bytecode::Value;
use prometeu_bytecode::registry::{Registry, TypeId};
use std::alloc::{Layout, alloc, dealloc};
use std::ptr::NonNull;
use std::sync::Arc;
#[derive(Debug)]
pub(super) struct DynamicBox {
registry: Arc<Registry>,
type_id: TypeId,
values: Box<[Value]>,
charge: Reservation,
}
impl DynamicBox {
/// Heap validates the exact non-Dynamic multi-slot group before construction.
/// Source owners remain borrowed until publication; allocation never invokes GC.
pub fn new(
registry: Arc<Registry>,
type_id: TypeId,
values: &[Value],
budget: &RuntimeBudget,
) -> Result<Self, ResourceFailure> {
let bytes = budget.bytes::<Value>(values.len(), Q::GuestBytes)?;
let layout = Layout::array::<Value>(values.len())
.map_err(|_| budget.failure(Q::GuestBytes, ResourceReason::SizeOverflow, bytes))?;
let charge = budget.reserve(Q::GuestBytes, bytes)?;
let ptr = if values.is_empty() {
NonNull::dangling()
} else {
// SAFETY: checked nonzero array layout; a null allocator result is a
// recoverable resource failure and drops the provisional reservation.
NonNull::new(unsafe { alloc(layout) }.cast::<Value>()).ok_or_else(|| {
budget.failure(Q::GuestBytes, ResourceReason::AllocationFailed, bytes)
})?
};
let mut pending = PendingValues { ptr, layout, initialized: 0 };
for value in values {
let cloned = value.clone();
// SAFETY: initialized advances within the exactly allocated Value array;
// ptr::write moves each owner into an unused, aligned native slot.
unsafe {
ptr.as_ptr().add(pending.initialized).write(cloned);
}
pending.initialized += 1;
}
// SAFETY: allocation came from the global allocator with precisely the
// Box<[Value]> layout; all elements are initialized. Transfer ownership
// without Vec capacity/shrink reallocations or a second allocation.
let boxed = unsafe {
Box::from_raw(std::ptr::slice_from_raw_parts_mut(ptr.as_ptr(), values.len()))
};
std::mem::forget(pending);
Ok(Self { registry, type_id, values: boxed, charge })
}
pub fn bytes(&self) -> u64 {
self.charge.amount()
}
pub fn values(&self) -> &[Value] {
&self.values
}
pub fn typed_values(
&self,
registry: &Registry,
type_id: TypeId,
) -> Result<&[Value], ValueError> {
if !std::ptr::eq(self.registry.as_ref(), registry) || self.type_id != type_id {
return Err(ValueError::Type);
}
Ok(&self.values)
}
}
/// Owns the partially initialized allocation until Box takes over. A panic
/// while constructing an owner drops only the initialized prefix, then frees it.
struct PendingValues {
ptr: NonNull<Value>,
layout: Layout,
initialized: usize,
}
impl Drop for PendingValues {
fn drop(&mut self) {
// SAFETY: initialized counts constructed Values only, all uniquely owned.
unsafe {
std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(
self.ptr.as_ptr(),
self.initialized,
));
if self.layout.size() != 0 {
dealloc(self.ptr.as_ptr().cast(), self.layout);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interrupted_native_initialization_drops_the_constructed_prefix_and_refunds() {
let budget = RuntimeBudget::default();
let text: Arc<str> = Arc::from("partially initialized");
let result = std::panic::catch_unwind(|| {
let layout = Layout::array::<Value>(3).unwrap();
let _charge = budget.reserve(Q::GuestBytes, layout.size() as u64).unwrap();
// SAFETY: checked nonzero layout; only the first slot is initialized.
let ptr = NonNull::new(unsafe { alloc(layout) }.cast::<Value>()).unwrap();
let mut pending = PendingValues { ptr, layout, initialized: 0 };
unsafe {
ptr.as_ptr().write(Value::String(text.clone()));
}
pending.initialized = 1;
assert_eq!(Arc::strong_count(&text), 2);
panic!("simulate interrupted construction before the next native slot");
});
assert!(result.is_err());
assert_eq!(Arc::strong_count(&text), 1);
assert_eq!(budget.used(Q::GuestBytes), 0);
}
#[test]
fn zero_width_storage_owns_no_allocation_and_is_not_a_valid_guest_box() {
let registry = crate::typed_storage::tests::fixture_registry();
let budget = RuntimeBudget::default();
let empty = DynamicBox::new(registry, TypeId(5), &[], &budget).unwrap();
assert!(empty.values().is_empty());
assert_eq!(empty.bytes(), 0);
drop(empty);
assert_eq!(budget.used(Q::GuestBytes), 0);
// Heap's group validator rejects empty values before invoking this storage constructor.
let mut heap = crate::heap::Heap::with_budget(&budget);
assert_eq!(
heap.allocate_dynamic_box(
crate::typed_storage::tests::fixture_registry(),
TypeId(5),
&[]
)
.unwrap_err(),
ValueError::Type
);
}
}