use super::*; use crate::resource_budget::{ResourceReason, RuntimeLimits}; use crate::typed_storage::tests::fixture_registry; use crate::value_contract::{ ValueError as E, can_unpack_dynamic as can_unpack, pack_dynamic as pack, unpack_dynamic as unpack, }; use prometeu_bytecode::load_limits::LoadBudget; use prometeu_bytecode::registry::ImplementationDecl; const I32: TypeId = TypeId(0); const I64: TypeId = TypeId(1); const COLOR: TypeId = TypeId(4); const VEC: TypeId = TypeId(5); const PIXEL: TypeId = TypeId(6); const STRING: TypeId = TypeId(7); const DYNAMIC: TypeId = TypeId(8); const ENEMY: TypeId = TypeId(9); const OTHER: TypeId = TypeId(10); const MIXED: TypeId = TypeId(11); const TRAIT: TypeId = TypeId(12); const INTS: TypeId = TypeId(13); const DYNAMICS: TypeId = TypeId(18); fn payload_handle(values: &[Value]) -> HeapRef { let [Value::Int64(_), Value::HeapRef(r)] = values else { panic!("boxed Dynamic pair") }; *r } fn forge_box(heap: &mut Heap, registry: Arc, ty: TypeId, values: &[Value]) -> HeapRef { let dynamic_box = DynamicBox::new(registry, ty, values, &heap.budget).unwrap(); heap.insert_object(StoredObject { header: ObjectHeader::new(ObjectKind::DynamicBox, values.len() as u32), payload: BudgetVec::new(&heap.budget, Q::GuestBytes), array_elems: None, closure_env: None, coroutine: None, typed: None, dynamic_box: Some(dynamic_box), }) .unwrap() } #[test] fn multi_slot_pack_has_one_exact_charged_box_and_immutable_copied_values() { let registry = fixture_registry(); let budget = RuntimeBudget::default(); let mut heap = Heap::with_budget(&budget); for (ty, mut input) in [ (VEC, vec![Value::Float(1.25), Value::Float(-2.5)]), ( PIXEL, vec![Value::Int64(i64::MIN), Value::Int64(i64::MAX), Value::Int64(u32::MAX.into())], ), ] { let before = budget.used(Q::GuestBytes); let original = input.clone(); let dynamic = pack(®istry, &mut heap, ty, &input).unwrap(); assert_eq!( budget.used(Q::GuestBytes) - before, (size_of::() + input.len() * size_of::()) as u64 ); let r = payload_handle(dynamic.as_slice()); assert_eq!(heap.header(r).unwrap().kind, ObjectKind::DynamicBox); assert_eq!(heap.dynamic_box_values(®istry, r, ty).unwrap().len(), input.len()); input.fill(Value::Null); assert_eq!(unpack(®istry, &heap, ty, dynamic.as_slice()).unwrap().as_slice(), original); assert!(can_unpack(®istry, &heap, ty, dynamic.as_slice()).unwrap()); assert!( !can_unpack(®istry, &heap, if ty == VEC { PIXEL } else { VEC }, dynamic.as_slice()) .unwrap() ); } assert_eq!(heap.len(), 2); assert_eq!(budget.used(Q::GuestBytes), heap.used_bytes.load(Ordering::Relaxed) as u64); heap.sweep(); assert_eq!(budget.used(Q::GuestBytes), 0); } #[test] fn repack_and_dynamic_extraction_preserve_the_pair_without_another_box() { let registry = fixture_registry(); let mut heap = Heap::new(); let first = pack(®istry, &mut heap, VEC, &[Value::Float(3.0), Value::Float(4.0)]).unwrap(); for _ in 0..100 { let again = pack(®istry, &mut heap, DYNAMIC, first.as_slice()).unwrap(); let extracted = unpack(®istry, &heap, DYNAMIC, again.as_slice()).unwrap(); assert_eq!(extracted.as_slice(), first.as_slice()); assert!(can_unpack(®istry, &heap, DYNAMIC, again.as_slice()).unwrap()); } assert_eq!(heap.allocation_count(), 1); assert_eq!(heap.len(), 1); } #[test] fn scalar_string_and_reference_payloads_are_direct_and_exact() { let registry = fixture_registry(); let mut heap = Heap::new(); let enemy = heap.allocate_typed_struct(registry.clone(), ENEMY).unwrap(); let text: Arc = Arc::from("shared"); let before = heap.allocation_count(); for (ty, input) in [ (I32, Value::Int32(7)), (I64, Value::Int64(7)), (COLOR, Value::Int64(7)), (STRING, Value::String(text.clone())), (ENEMY, Value::HeapRef(enemy)), ] { let dynamic = pack(®istry, &mut heap, ty, std::slice::from_ref(&input)).unwrap(); let result = unpack(®istry, &heap, ty, dynamic.as_slice()).unwrap(); assert_eq!(result.as_slice(), [input]); if let [Value::String(alias)] = result.as_slice() { assert!(Arc::ptr_eq(alias, &text)); } if ty == I64 { assert!(!can_unpack(®istry, &heap, COLOR, dynamic.as_slice()).unwrap()); } if ty == COLOR { assert!(!can_unpack(®istry, &heap, I64, dynamic.as_slice()).unwrap()); } if ty == ENEMY { assert!(!can_unpack(®istry, &heap, TRAIT, dynamic.as_slice()).unwrap()); } } assert_eq!(heap.allocation_count(), before); assert_eq!(Arc::strong_count(&text), 1); } #[test] fn null_compatibility_preserves_typed_identity_and_rebuilds_absent_trait() { let registry = fixture_registry(); let mut heap = Heap::new(); let untyped = [Value::Null, Value::Null]; for ty in [STRING, ENEMY, OTHER, TRAIT, INTS] { assert!(can_unpack(®istry, &heap, ty, &untyped).unwrap()); let absent = registry.type_layout(ty).unwrap().storage.default_values(); assert_eq!(unpack(®istry, &heap, ty, &untyped).unwrap().as_slice(), absent); let typed = pack(®istry, &mut heap, ty, absent).unwrap(); assert_eq!(typed.as_slice(), [Value::Int64(ty.0.into()), Value::Null]); assert_eq!(unpack(®istry, &heap, ty, typed.as_slice()).unwrap().as_slice(), absent); let other = if ty == STRING { ENEMY } else { STRING }; assert!(!can_unpack(®istry, &heap, other, typed.as_slice()).unwrap()); assert_eq!(unpack(®istry, &heap, other, typed.as_slice()).unwrap_err(), E::Type); } for ty in [I32, VEC, PIXEL] { assert!(!can_unpack(®istry, &heap, ty, &untyped).unwrap()); assert_eq!(unpack(®istry, &heap, ty, &untyped).unwrap_err(), E::Type); } assert_eq!(pack(®istry, &mut heap, DYNAMIC, &untyped).unwrap().as_slice(), untyped); assert_eq!(heap.allocation_count(), 0); } #[test] fn trait_box_keeps_receiver_identity_and_gc_reaches_through_typed_dynamic_storage() { let registry = fixture_registry(); let mut heap = Heap::new(); let receiver = heap.allocate_typed_struct(registry.clone(), ENEMY).unwrap(); let source = [Value::HeapRef(receiver), Value::Int64(0)]; // A safepoint before pack sees the original source reference. heap.mark_from_roots([receiver]).unwrap(); heap.sweep(); let dynamic = pack(®istry, &mut heap, TRAIT, &source).unwrap(); let r = payload_handle(dynamic.as_slice()); let holder = heap.allocate_typed_array(registry.clone(), DYNAMICS, 2).unwrap(); heap.store_typed(®istry, holder, 0, dynamic.as_slice()).unwrap(); heap.store_typed(®istry, holder, 1, dynamic.as_slice()).unwrap(); assert_eq!(heap.len(), 3); // Receiver, one shared box, holder. heap.mark_from_roots([holder]).unwrap(); heap.sweep(); assert!(heap.is_valid(receiver)); assert!(heap.is_valid(r)); assert_eq!(unpack(®istry, &heap, TRAIT, dynamic.as_slice()).unwrap().as_slice(), source); heap.store_typed(®istry, holder, 0, &[Value::Null, Value::Null]).unwrap(); heap.mark_from_roots([holder]).unwrap(); heap.sweep(); assert!(heap.is_valid(r)); // Second alias still owns reachability. heap.store_typed(®istry, holder, 1, &[Value::Null, Value::Null]).unwrap(); heap.mark_from_roots([holder]).unwrap(); heap.sweep(); assert!(!heap.is_valid(r)); assert!(!heap.is_valid(receiver)); } #[test] fn box_is_not_a_guest_instance_or_collection_and_cannot_be_a_trait_receiver() { let registry = fixture_registry(); let mut heap = Heap::new(); let dynamic = pack(®istry, &mut heap, VEC, &[Value::Float(0.0), Value::Float(0.0)]).unwrap(); let r = payload_handle(dynamic.as_slice()); assert_eq!(heap.load_typed(®istry, r, 0).unwrap_err(), E::Type); assert_eq!(heap.store_typed(®istry, r, 0, &[Value::Float(1.0)]).unwrap_err(), E::Type); assert_eq!( value_contract::validate(®istry, &heap, ENEMY, &[Value::HeapRef(r)]).unwrap_err(), E::Type ); assert_eq!( value_contract::validate(®istry, &heap, TRAIT, &[Value::HeapRef(r), Value::Int64(0)]) .unwrap_err(), E::Type ); assert_eq!(heap.concrete_type(r, ®istry).unwrap_err(), E::Type); } #[test] fn malformed_dynamic_queries_fault_before_reporting_ordinary_mismatch() { let registry = fixture_registry(); let mut heap = Heap::new(); let receiver = heap.allocate_typed_struct(registry.clone(), ENEMY).unwrap(); for bad in [ vec![], vec![Value::Null], vec![Value::Null, Value::Int64(0)], vec![Value::Int64(DYNAMIC.0.into()), Value::Null], vec![Value::Int64(VEC.0.into()), Value::HeapRef(receiver)], vec![Value::Int64(VEC.0.into()), Value::HeapRef(HeapRef::NULL)], vec![Value::Int64(u32::MAX as i64 + 1), Value::Null], vec![Value::Int64(999), Value::Null], vec![Value::Int64(I32.0.into()), Value::Int64(0)], ] { assert_eq!(can_unpack(®istry, &heap, STRING, &bad).unwrap_err(), E::Type); assert_eq!(unpack(®istry, &heap, STRING, &bad).unwrap_err(), E::Type); } let stale = heap .allocate_dynamic_box(registry.clone(), VEC, &[Value::Float(1.0), Value::Float(2.0)]) .unwrap(); heap.sweep(); let live = heap .allocate_dynamic_box(registry.clone(), VEC, &[Value::Float(3.0), Value::Float(4.0)]) .unwrap(); assert_eq!(stale.index, live.index); assert_ne!(stale.generation, live.generation); for handle in [ stale, HeapRef { index: live.index, generation: 0 }, HeapRef { index: u32::MAX, generation: 1 }, ] { let bad = [Value::Int64(VEC.0.into()), Value::HeapRef(handle)]; assert_eq!(can_unpack(®istry, &heap, STRING, &bad).unwrap_err(), E::InvalidHandle); } } #[test] fn forged_box_category_type_width_group_and_registry_are_rejected() { let registry = fixture_registry(); let mut heap = Heap::new(); let receiver = heap.allocate_typed_struct(registry.clone(), ENEMY).unwrap(); let wrong_boxes = [ forge_box(&mut heap, registry.clone(), VEC, &[Value::Float(1.0)]), forge_box(&mut heap, registry.clone(), VEC, &[Value::Float(1.0), Value::Int64(2)]), forge_box(&mut heap, registry.clone(), TRAIT, &[Value::HeapRef(receiver), Value::Int64(0)]), forge_box(&mut heap, fixture_registry(), VEC, &[Value::Float(1.0), Value::Float(2.0)]), heap.allocate_object(ObjectKind::DynamicBox, &[]).unwrap(), ]; for r in wrong_boxes { assert_eq!( can_unpack(®istry, &heap, STRING, &[Value::Int64(VEC.0.into()), Value::HeapRef(r)]) .unwrap_err(), E::Type ); } for contents in [vec![Value::Null, Value::Null], vec![Value::HeapRef(receiver), Value::Int64(1)]] { let r = forge_box(&mut heap, registry.clone(), TRAIT, &contents); assert_eq!( can_unpack(®istry, &heap, TRAIT, &[Value::Int64(TRAIT.0.into()), Value::HeapRef(r)]) .unwrap_err(), E::Type ); } let r = forge_box(&mut heap, registry.clone(), VEC, &[Value::Float(1.0), Value::Float(2.0)]); heap.objects[r.index as usize].as_mut().unwrap().header.payload_len = 3; assert_eq!(heap.dynamic_box_values(®istry, r, VEC).unwrap_err(), E::Type); } #[test] fn invalid_pack_never_allocates_or_consumes_source_values() { let registry = fixture_registry(); let budget = RuntimeBudget::default(); let mut heap = Heap::with_budget(&budget); for (ty, input) in [ (VEC, vec![Value::Float(1.0)]), (PIXEL, vec![Value::Int64(0), Value::Int64(0), Value::Int64(-1)]), (TRAIT, vec![Value::Null, Value::Int64(0)]), (DYNAMIC, vec![Value::Null, Value::Int64(0)]), ] { let copy = input.clone(); assert_eq!(pack(®istry, &mut heap, ty, &input).unwrap_err(), E::Type); assert_eq!(input, copy); assert_eq!(heap.len(), 0); assert_eq!(budget.used(Q::GuestBytes), 0); } // The lower-level allocator also rejects categories that must never box. for (ty, input) in [ (I32, vec![Value::Int32(0)]), (TRAIT, vec![Value::Null, Value::Null]), (DYNAMIC, vec![Value::Null, Value::Null]), (DYNAMIC, vec![Value::Int64(I32.0.into()), Value::Int32(1)]), ] { assert_eq!(heap.allocate_dynamic_box(registry.clone(), ty, &input).unwrap_err(), E::Type); } assert_eq!(heap.allocation_count(), 0); } #[test] fn box_guest_quota_boundary_and_late_table_failure_refund_all_reservations() { let registry = fixture_registry(); let bytes = (size_of::() + 2 * size_of::()) as u64; for limit in [bytes - 1, bytes] { let budget = RuntimeBudget::new(RuntimeLimits::default().lowered(Q::GuestBytes, limit).unwrap()); let mut heap = Heap::with_budget(&budget); let source = [Value::Float(1.0), Value::Float(2.0)]; let result = pack(®istry, &mut heap, VEC, &source); if limit == bytes { assert!(result.is_ok()); assert_eq!(budget.used(Q::GuestBytes), bytes); } else { assert!( matches!(result, Err(E::Resource(e)) if e.resource == Q::GuestBytes && e.reason == ResourceReason::Limit) ); assert_eq!(heap.allocation_count(), 0); for q in [Q::GuestBytes, Q::HandleSlots, Q::AuxiliaryBytes, Q::TemporaryBytes] { assert_eq!(budget.used(q), 0); } } assert_eq!(source, [Value::Float(1.0), Value::Float(2.0)]); } let budget = RuntimeBudget::new(RuntimeLimits::default().lowered(Q::AuxiliaryBytes, 0).unwrap()); let mut heap = Heap::with_budget(&budget); assert!( matches!(pack(®istry, &mut heap, VEC, &[Value::Float(1.0), Value::Float(2.0)]), Err(E::Resource(e)) if e.resource == Q::AuxiliaryBytes) ); assert_eq!(heap.len(), 0); for q in [Q::GuestBytes, Q::HandleSlots, Q::AuxiliaryBytes, Q::TemporaryBytes] { assert_eq!(budget.used(q), 0); } } #[test] fn query_and_unpack_succeed_at_full_heap_quota_without_allocating() { let registry = fixture_registry(); let bytes = (size_of::() + 2 * size_of::()) as u64; let budget = RuntimeBudget::new(RuntimeLimits::default().lowered(Q::GuestBytes, bytes).unwrap()); let mut heap = Heap::with_budget(&budget); let dynamic = pack(®istry, &mut heap, VEC, &[Value::Float(1.0), Value::Float(2.0)]).unwrap(); for _ in 0..100 { assert!(can_unpack(®istry, &heap, VEC, dynamic.as_slice()).unwrap()); assert_eq!( unpack(®istry, &heap, VEC, dynamic.as_slice()).unwrap().as_slice(), [Value::Float(1.0), Value::Float(2.0)] ); assert_eq!( pack(®istry, &mut heap, DYNAMIC, dynamic.as_slice()).unwrap().as_slice(), dynamic.as_slice() ); } assert_eq!(heap.allocation_count(), 1); assert_eq!(budget.used(Q::GuestBytes), bytes); assert_eq!(budget.used(Q::TemporaryBytes), 0); } #[test] fn collecting_a_trait_box_drops_transitive_native_owners_once() { let mut declarations = fixture_registry().declarations().clone(); declarations.implementations.push(ImplementationDecl { owner: MIXED, trait_id: TRAIT, methods: vec![], }); let registry = Arc::new( Registry::resolve(declarations, 0, &mut LoadBudget::new(Default::default())).unwrap(), ); let mut heap = Heap::new(); let text: Arc = Arc::from("retained through boxed trait"); let receiver = heap.allocate_typed_struct(registry.clone(), MIXED).unwrap(); heap.store_typed(®istry, receiver, 3, &[Value::String(text.clone())]).unwrap(); let dynamic = pack(®istry, &mut heap, TRAIT, &[Value::HeapRef(receiver), Value::Int64(2)]).unwrap(); // Receiver -> Dynamic box -> receiver is a real typed heap cycle. heap.store_typed(®istry, receiver, 4, dynamic.as_slice()).unwrap(); let r = payload_handle(dynamic.as_slice()); heap.mark_from_roots([r]).unwrap(); heap.sweep(); assert_eq!(Arc::strong_count(&text), 2); heap.sweep(); assert_eq!(Arc::strong_count(&text), 1); assert_eq!(heap.len(), 0); } #[test] fn raw_box_storage_drops_native_owners_even_for_rejected_groups() { let registry = fixture_registry(); let budget = RuntimeBudget::default(); let mut heap = Heap::with_budget(&budget); let text: Arc = Arc::from("malformed box fixture"); let r = forge_box( &mut heap, registry.clone(), VEC, &[Value::String(text.clone()), Value::Float(1.0)], ); assert_eq!(Arc::strong_count(&text), 2); assert_eq!(heap.dynamic_box_values(®istry, r, VEC).unwrap_err(), E::Type); heap.sweep(); assert_eq!(Arc::strong_count(&text), 1); assert_eq!(budget.used(Q::GuestBytes), 0); } #[test] fn failed_trait_box_publication_preserves_source_roots_and_existing_table_capacities() { let registry = fixture_registry(); let one_slot_aux = (size_of::>() + size_of::() + size_of::()) as u64; let budget = RuntimeBudget::new( RuntimeLimits::default().lowered(Q::AuxiliaryBytes, one_slot_aux).unwrap(), ); let mut heap = Heap::with_budget(&budget); let receiver = heap.allocate_typed_struct(registry.clone(), ENEMY).unwrap(); let before = budget.used(Q::GuestBytes); let source = [Value::HeapRef(receiver), Value::Int64(0)]; assert!( matches!(pack(®istry, &mut heap, TRAIT, &source), Err(E::Resource(e)) if e.resource == Q::AuxiliaryBytes) ); assert_eq!(heap.len(), 1); assert_eq!(heap.allocation_count(), 1); assert_eq!(budget.used(Q::GuestBytes), before); assert_eq!(budget.used(Q::AuxiliaryBytes), one_slot_aux); assert_eq!(budget.used(Q::HandleSlots), 1); assert_eq!(budget.used(Q::TemporaryBytes), 0); assert_eq!(source, [Value::HeapRef(receiver), Value::Int64(0)]); heap.mark_from_roots(source.iter().filter_map(crate::roots::value_heap_ref)).unwrap(); heap.sweep(); assert!(heap.is_valid(receiver)); }