diff --git a/CHANGELOG.md b/CHANGELOG.md index aa8153e..9243e3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable milestones for the nera project are documented in this file. +## Native sends preserve negative integers + +- Native sends no longer turn negative small integers into large positive + integers. This affected tuples built in the send expression, such as + `self() ! {id(-3)}`, and messages copied between processes. +- Retained ETS snapshots now count toward full garbage collection, so a process + that reads frequently replaced table entries can reclaim old data sooner. + ## Process startup deadlines - `proc_lib:start_link/5` now kills an unacknowledged child when its finite diff --git a/crates/nera-codegen/src/term_layout.rs b/crates/nera-codegen/src/term_layout.rs index a5b66ed..bacffa2 100644 --- a/crates/nera-codegen/src/term_layout.rs +++ b/crates/nera-codegen/src/term_layout.rs @@ -29,7 +29,8 @@ pub const BOXED_REFC_BINARY: u64 = 0x6; pub const BOXED_REFERENCE: u64 = 0x7; pub const BOXED_MATCH_CTX: u64 = 0x8; -/// Bit 63 marks a term as "external" (points into ETS storage). +/// Bit 63 marks a cons or boxed pointer into ETS storage. On a small integer +/// it is the sign bit. pub const EXTERNAL_BIT: u64 = 1u64 << 63; // Sizes (in bytes) diff --git a/crates/nera-runtime/src/ets.rs b/crates/nera-runtime/src/ets.rs index d36b435..9d52d37 100644 --- a/crates/nera-runtime/src/ets.rs +++ b/crates/nera-runtime/src/ets.rs @@ -185,20 +185,21 @@ unsafe impl Sync for CompactHeap {} /// references from the table and from processes holding zero-copy /// lookup results. pub struct StoredTupleInner { - _heap: CompactHeap, + heap: CompactHeap, + retained_bytes: usize, } /// Deep-copied tuple stored in ETS (independent of any process heap). /// All elements are stored in a compact word buffer. /// -/// The backing memory (`inner._heap`) is Arc-wrapped so that zero-copy +/// The backing memory (`inner.heap`) is Arc-wrapped so that zero-copy /// lookups can hold a reference to the storage without preventing /// the table from being modified. `elements` stays outside the Arc /// so that `update_counter` can mutate element slots in place. struct StoredTuple { /// Arc-wrapped backing storage for all boxed terms in this tuple. inner: Arc, - /// The element terms (immediates or pointers into `inner._heap.words`). + /// The element terms (immediates or pointers into the compact heap). elements: Vec, } @@ -561,8 +562,12 @@ unsafe fn deep_copy_tuple_to_stored(elements: &[ErlTerm], compact: CompactHeap) let copied_elems: Vec = elements.iter() .map(|&elem| deep_copy_into_compact(elem, &mut compact)) .collect(); + let retained_bytes = compact.refc_binaries.iter() + .fold(compact.words_len * std::mem::size_of::(), |bytes, binary| { + bytes.saturating_add(binary.len()) + }); StoredTuple { - inner: Arc::new(StoredTupleInner { _heap: compact }), + inner: Arc::new(StoredTupleInner { heap: compact, retained_bytes }), elements: copied_elems, } } @@ -1001,21 +1006,21 @@ unsafe fn store_tuple(table: &EtsTable, tuple_term: ErlTerm) -> Result /// Build a zero-copy result tuple from a stored tuple. fn stored_to_zero_copy(stored: &StoredTuple, heap: &mut ProcessHeap) -> ErlTerm { - let arc = stored.inner.clone(); + let mut borrows_storage = false; let elems: Vec = stored.elements.iter() .map(|&elem| { - if elem.is_atom() || elem.is_small_int() - || elem.is_pid() || elem.is_nil() - { - elem - } else { - elem.with_external_bit() - } + let term = elem.with_external_bit(); + borrows_storage |= term.is_external(); + term }) .collect(); - let result = heap.alloc_tuple(&elems); - heap.retain_borrowed_heap(arc); - result + if borrows_storage { + let compact = &stored.inner.heap; + let start = compact.allocation.as_ref().expect("boxed ETS storage").as_ptr() as usize; + let end = start + compact.words_len * std::mem::size_of::(); + heap.retain_borrowed_heap(stored.inner.clone(), start..end, stored.inner.retained_bytes); + } + heap.alloc_tuple(&elems) } /// Look up tuples by key using zero-copy: returns tagged pointers @@ -2948,6 +2953,127 @@ mod tests { }).join().unwrap(); } + #[test] + fn projected_ets_binary_keeps_backing_after_full_gc() { + let (id, _) = make_test_table("projected_binary_full_gc"); + let table = ErlTerm::small_int(id as i64); + let key = ErlTerm::small_int(7); + let mut source = ProcessHeap::new(); + let bytes = [42; 128]; + let binary = source.alloc_binary_auto(&bytes); + let nested = source.alloc_tuple(&[binary]); + let row = source.alloc_tuple(&[key, nested]); + // SAFETY: both heaps own the inputs used below; lookup retains the ETS storage. + unsafe { ets_insert(table, row) }.unwrap(); + let mut receiver = ProcessHeap::new(); + let lookup = unsafe { ets_lookup(table, key, &mut receiver) }; + let (projected, backing) = unsafe { + let found = (*lookup.as_cons_ptr().unwrap()).head.as_boxed_ptr().unwrap(); + let wrapper = ErlTerm(*found.add(2)); + assert!(wrapper.is_external()); + let term = ErlTerm(*wrapper.as_boxed_ptr().unwrap().add(1)); + assert!(term.is_refc_binary()); + assert!(!term.is_external()); + let ptr = *term.as_boxed_ptr().unwrap().add(crate::term::REFC_BINARY_PTR_WORD_INDEX); + let owner = crate::heap::clone_arc_from_raw(ptr); + (term, Arc::downgrade(&owner)) + }; + assert!(ets_delete_table(table)); + drop(source); + + let mut roots = [projected, ErlTerm::small_int(-7)]; + // SAFETY: the receiver retains the lookup storage and only these roots stay live. + unsafe { receiver.collect_full(&mut roots) }; + assert!(backing.upgrade().is_some(), "collection dropped live binary backing"); + assert_eq!(receiver.borrowed_heap_count(), 0); + assert_eq!(receiver.refc_binary_count(), 1); + assert_eq!(unsafe { roots[0].borrow(&receiver) }.binary_bytes(), Some(bytes.as_slice())); + + // SAFETY: only the immediate root is needed after this collection. + unsafe { receiver.collect_full(&mut roots[1..]) }; + assert!(backing.upgrade().is_none(), "collection kept dead binary backing"); + } + + #[test] + fn retained_ets_bytes_trigger_full_gc_without_dropping_live_snapshots() { + let (id, _) = make_test_table("retained_ets_bytes"); + let table = ErlTerm::small_int(id as i64); + let key = ErlTerm::small_int(7); + let mut source = ProcessHeap::new(); + let mut receiver = ProcessHeap::new(); + let anchor_bytes = vec![42; 2 * 1024 * 1024]; + let anchor = source.alloc_binary_auto(&anchor_bytes); + let prefix = source.alloc_float(1.5); + let row = source.alloc_tuple(&[key, prefix, anchor]); + // SAFETY: source owns row and lookup registers the receiver's retained owner. + unsafe { ets_insert(table, row) }.unwrap(); + let retained = unsafe { ets_lookup(table, key, &mut receiver) }; + assert!(receiver.needs_gc(), "the retained bytes alone should trigger collection"); + let anchor = unsafe { + let row = (*retained.as_cons_ptr().unwrap()).head.as_boxed_ptr().unwrap(); + ErlTerm(*row.add(3)) + }; + let mut roots = [anchor]; + // SAFETY: these are the only receiver roots needed after collection. + unsafe { receiver.collect(&mut roots) }; + assert!(!receiver.needs_gc(), "live snapshots need headroom after collection"); + + for _ in 0..8 { + unsafe { ets_lookup(table, key, &mut receiver) }; + } + assert_eq!(receiver.borrowed_heap_count(), 1); + assert!(!receiver.needs_gc(), "repeat lookups should not charge the same storage again"); + + for (i, byte) in [17, 23].into_iter().enumerate() { + let binary = source.alloc_binary_auto(&vec![byte; 1280 * 1024]); + let row = source.alloc_tuple(&[key, binary]); + unsafe { ets_insert(table, row) }.unwrap(); + unsafe { ets_lookup(table, key, &mut receiver) }; + assert_eq!(receiver.needs_gc(), i == 1); + } + assert_eq!(receiver.borrowed_heap_count(), 3); + assert!(ets_delete_table(table)); + unsafe { receiver.collect(&mut roots) }; + assert_eq!(receiver.borrowed_heap_count(), 1, "reclaim only the two discarded snapshots"); + assert!(!receiver.needs_gc()); + unsafe { + assert_eq!(roots[0].borrow(&receiver).binary_bytes(), Some(anchor_bytes.as_slice())); + receiver.collect_full(&mut []); + } + assert_eq!(receiver.borrowed_heap_count(), 0); + } + + #[test] + fn repeatedly_reading_one_large_ets_snapshot_does_not_force_full_gc() { + let (id, _) = make_test_table("repeated_large_ets_lookup"); + let table = ErlTerm::small_int(id as i64); + let key = ErlTerm::small_int(7); + let other_key = ErlTerm::small_int(8); + let mut source = ProcessHeap::new(); + let mut receiver = ProcessHeap::new(); + let binary = source.alloc_binary_auto(&vec![42; 2 * 1024 * 1024]); + let row = source.alloc_tuple(&[key, binary]); + let other = source.alloc_tuple(&[other_key, binary]); + // SAFETY: source owns the inserted terms; no lookup result is rooted. + unsafe { + ets_insert(table, row).unwrap(); + ets_insert(table, other).unwrap(); + ets_lookup(table, key, &mut receiver); + assert!(receiver.needs_gc()); + receiver.collect(&mut []); + assert_eq!(receiver.borrowed_heap_count(), 0); + for _ in 0..8 { + ets_lookup(table, key, &mut receiver); + assert!(!receiver.needs_gc(), "one large snapshot retriggered collection"); + } + ets_lookup(table, other_key, &mut receiver); + assert!(receiver.needs_gc(), "another snapshot should still trigger collection"); + assert!(ets_delete_table(table)); + receiver.collect(&mut []); + assert_eq!(receiver.borrowed_heap_count(), 0); + } + } + #[test] fn delete_table_removes_from_registry() { let (id, _name) = make_test_table("test_delete_table_1"); diff --git a/crates/nera-runtime/src/heap.rs b/crates/nera-runtime/src/heap.rs index b40a3e9..738264f 100644 --- a/crates/nera-runtime/src/heap.rs +++ b/crates/nera-runtime/src/heap.rs @@ -12,7 +12,8 @@ use crate::binary::BinaryData; use bumpalo::Bump; use std::alloc::Layout; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ops::Range; use std::sync::Arc; use crate::term::{ @@ -31,6 +32,9 @@ pub const DEFAULT_GC_THRESHOLD: usize = 2 * 1024; /// Default old-gen GC threshold: 1 MiB. pub const DEFAULT_OLD_GC_THRESHOLD: usize = 1024 * 1024; +/// Minimum retained ETS storage before it can trigger a full collection. +const DEFAULT_BORROWED_HEAP_THRESHOLD: usize = 1024 * 1024; + /// Default binary virtual heap threshold: 256 KiB. /// Matches BEAM's `BIN_VH_MIN_SIZE` (32K words on 64-bit = 256 KiB). /// GC triggers when the virtual binary overhead exceeds this threshold. @@ -271,15 +275,24 @@ pub struct ProcessHeap { binary_vheap_threshold: usize, /// Borrowed ETS heaps kept alive for zero-copy lookup results. /// Arc references prevent the backing CompactHeap from being freed - /// while the process holds external pointers into it. - /// Type-erased via `dyn Any + Send + Sync` to avoid a circular - /// dependency between heap.rs and ets.rs. - borrowed_heaps: Vec>, + /// while the process holds external pointers into it. The buffer start + /// identifies the owner and lets major GC resolve interior addresses. + /// Minor GC skips old containers, so only major GC sweeps these owners. + borrowed_heaps: BTreeMap, + borrowed_heap_bytes: usize, + borrowed_heap_threshold: usize, + single_snapshot_headroom: usize, /// Current inline allocation chunk size in words. Starts small (64 words /// = 512 bytes) and doubles on each refill up to 512 words (4 KiB). inline_chunk_words: usize, } +struct BorrowedHeap { + end: usize, + bytes: usize, + _owner: Arc, +} + /// Allocation-only storage for message fragments and process-info snapshots. /// /// The underlying heap is private: this type exposes neither GC nor mutable @@ -398,7 +411,10 @@ impl ProcessHeap { refc_unique_count: 0, binary_vheap_size: 0, binary_vheap_threshold: DEFAULT_BINARY_VHEAP_THRESHOLD, - borrowed_heaps: Vec::new(), + borrowed_heaps: BTreeMap::new(), + borrowed_heap_bytes: 0, + borrowed_heap_threshold: DEFAULT_BORROWED_HEAP_THRESHOLD, + single_snapshot_headroom: 0, inline_chunk_words: INLINE_CHUNK_MIN_WORDS, } } @@ -424,7 +440,10 @@ impl ProcessHeap { refc_unique_count: 0, binary_vheap_size: 0, binary_vheap_threshold: DEFAULT_BINARY_VHEAP_THRESHOLD, - borrowed_heaps: Vec::new(), + borrowed_heaps: BTreeMap::new(), + borrowed_heap_bytes: 0, + borrowed_heap_threshold: DEFAULT_BORROWED_HEAP_THRESHOLD, + single_snapshot_headroom: 0, inline_chunk_words: INLINE_CHUNK_MIN_WORDS, } } @@ -609,11 +628,18 @@ impl ProcessHeap { self.refc_binaries.push(data); } - /// Retain immutable external storage referenced by zero-copy lookup terms. - /// Collection releases these owners only when no external terms survive. - #[inline] - pub(crate) fn retain_borrowed_heap(&mut self, owner: Arc) { - self.borrowed_heaps.push(owner); + /// Retain a snapshot whose marked pointers all lead into this immutable, + /// contiguous range. Distinct owners have disjoint ranges. + pub(crate) fn retain_borrowed_heap( + &mut self, + owner: Arc, + range: Range, + bytes: usize, + ) { + if let std::collections::btree_map::Entry::Vacant(entry) = self.borrowed_heaps.entry(range.start) { + entry.insert(BorrowedHeap { end: range.end, bytes, _owner: owner }); + self.borrowed_heap_bytes = self.borrowed_heap_bytes.saturating_add(bytes); + } } #[cfg(test)] @@ -725,11 +751,17 @@ impl ProcessHeap { self.max_heap_size > 0 && self.bytes_allocated() > self.max_heap_size.saturating_mul(8) } + fn has_borrowed_heap_pressure(&self) -> bool { + self.borrowed_heap_bytes >= self.borrowed_heap_threshold + && (self.borrowed_heaps.len() != 1 || self.borrowed_heap_bytes > self.single_snapshot_headroom) + } + /// Returns `true` if any GC trigger condition is met. pub fn needs_gc(&self) -> bool { self.young_bytes_allocated >= self.gc_threshold || self.old_bytes_allocated >= self.old_gc_threshold || self.binary_vheap_size >= self.binary_vheap_threshold + || self.has_borrowed_heap_pressure() || self.exceeds_max_heap_size() } @@ -738,6 +770,7 @@ impl ProcessHeap { /// refc binaries too, so it's sufficient for binary-heavy workloads. fn needs_major_gc(&self) -> bool { self.old_bytes_allocated >= self.old_gc_threshold + || self.has_borrowed_heap_pressure() || self.minor_gc_count >= self.max_minor_gcs } @@ -839,7 +872,6 @@ impl ProcessHeap { let promoted_bytes = copier.bytes_copied; let live_refc_ptrs = copier.live_refc_ptrs; - let has_external_terms = copier.has_external_terms; // Give a large, freshly traced promotion headroom instead of copying // it again on the next scheduler slice. Do not double the accumulated @@ -887,9 +919,6 @@ impl ProcessHeap { self.old_refc_ptrs.contains(&(Arc::as_ptr(arc) as u64)) }); self.update_binary_vheap(); - self.sweep_borrowed_heaps(has_external_terms); - - // Drop old young gen (old_young goes out of scope). } /// Major GC: copy all live data (young + old) into a fresh Bump. @@ -900,8 +929,8 @@ impl ProcessHeap { } let bytes_copied = copier.bytes_copied; - let live_refc_ptrs = copier.live_refc_ptrs.clone(); - let has_external_terms = copier.has_external_terms; + let live_refc_ptrs = std::mem::take(&mut copier.live_refc_ptrs); + let live_external_ptrs = std::mem::take(&mut copier.live_external_ptrs); // Install copier's arena as the new old gen. self.old = copier.into_arena(); @@ -925,9 +954,34 @@ impl ProcessHeap { // Sweep refc binaries, binary vheap, borrowed heaps. self.sweep_refc_binaries(&live_refc_ptrs); + if !self.borrowed_heaps.is_empty() && !live_refc_ptrs.is_empty() { + // A projection can expose an unmarked ETS binary. Its descriptor + // was copied, but its backing still needs a process-owned Arc. + let owned: HashSet<_> = self.refc_binaries.iter() + .map(|arc| Arc::as_ptr(arc) as u64) + .collect(); + for &ptr in live_refc_ptrs.difference(&owned) { + // SAFETY: the borrowed heaps still own the backing stores. + self.refc_binaries.push(unsafe { clone_arc_from_raw(ptr) }); + } + } self.old_refc_ptrs = live_refc_ptrs; self.update_binary_vheap(); - self.sweep_borrowed_heaps(has_external_terms); + let sole_snapshot_bytes = if self.borrowed_heaps.len() == 1 { + self.borrowed_heap_bytes + } else { + 0 + }; + self.sweep_borrowed_heaps(&live_external_ptrs); + // An unchanged large row may still be table-owned after this sweep. + // Let a single read of the same size pass; never exempt accumulation. + self.single_snapshot_headroom = if self.borrowed_heaps.is_empty() { + sole_snapshot_bytes + } else { + 0 + }; + self.borrowed_heap_threshold = DEFAULT_BORROWED_HEAP_THRESHOLD + .max(self.borrowed_heap_bytes.saturating_mul(2)); } /// Sweep stale refc binaries: retain only those whose raw pointer was @@ -972,11 +1026,30 @@ impl ProcessHeap { ); } - /// Conservative borrowed_heaps sweep. - fn sweep_borrowed_heaps(&mut self, has_external_terms: bool) { - if !self.borrowed_heaps.is_empty() && !has_external_terms { - self.borrowed_heaps.clear(); + /// Called after a full trace, once copied binaries have their own owners. + fn sweep_borrowed_heaps(&mut self, external_ptrs: &HashSet) { + if self.borrowed_heaps.is_empty() { + return; } + let mut live = HashSet::new(); + for &ptr in external_ptrs { + let Some((&start, _)) = self.borrowed_heaps.range(..=ptr).next_back() + .filter(|(_, heap)| ptr < heap.end) else { + // Without a matching range we cannot prove any owner is dead. + return; + }; + live.insert(start); + } + let mut bytes = 0usize; + self.borrowed_heaps.retain(|start, heap| { + if live.contains(start) { + bytes = bytes.saturating_add(heap.bytes); + true + } else { + false + } + }); + self.borrowed_heap_bytes = bytes; } } @@ -992,11 +1065,15 @@ enum GcTarget<'a> { Borrowed(&'a mut Bump), } -/// An immediate without the external bit: the collector copies it as itself -/// with no side effect. +/// The collector can copy these terms unchanged. A small integer's high bit +/// is its sign, not an external pointer marker. #[inline] pub(crate) fn is_plain_immediate(word: u64) -> bool { - word & EXTERNAL_BIT == 0 && matches!(word & TAG_MASK, TAG_SMALL_INT | TAG_ATOM | TAG_PID | TAG_NIL) + match word & TAG_MASK { + TAG_SMALL_INT => true, + TAG_ATOM | TAG_PID | TAG_NIL => word & EXTERNAL_BIT == 0, + _ => false, + } } /// Term slots of an object already allocated in the target arena whose @@ -1025,8 +1102,8 @@ struct GcCopier<'a> { forwarding: HashMap, /// Raw Arc pointers encountered during live-data traversal. live_refc_ptrs: HashSet, - /// Set to true if any external term was encountered. - has_external_terms: bool, + /// Addresses of marked pointers encountered during a major collection. + live_external_ptrs: HashSet, /// Bytes copied (allocated in major, promoted in minor). bytes_copied: usize, } @@ -1042,7 +1119,7 @@ impl<'a> GcCopier<'a> { pending: Vec::new(), forwarding: HashMap::with_capacity(obj_estimate), live_refc_ptrs: HashSet::new(), - has_external_terms: false, + live_external_ptrs: HashSet::new(), bytes_copied: 0, } } @@ -1056,7 +1133,7 @@ impl<'a> GcCopier<'a> { pending: Vec::new(), forwarding: HashMap::with_capacity(obj_estimate), live_refc_ptrs: HashSet::new(), - has_external_terms: false, + live_external_ptrs: HashSet::new(), bytes_copied: 0, } } @@ -1224,7 +1301,9 @@ impl<'a> GcCopier<'a> { fn copy_object(&mut self, term: ErlTerm) -> ErlTerm { // External terms point into borrowed ETS heaps — preserve as-is. if term.is_external() { - self.has_external_terms = true; + if !self.is_minor() { + self.live_external_ptrs.insert((term.0 & !(TAG_MASK | EXTERNAL_BIT)) as usize); + } return term; } match term.tag() { @@ -2503,6 +2582,37 @@ mod tests { } } + #[test] + fn minor_gc_keeps_ets_storage_reachable_from_old_containers() { + for cons in [false, true] { + let mut heap = ProcessHeap::new(); + let storage = Arc::new([ + BoxedHeader::new(crate::term::BoxedSubtype::Float, 1).0, + 42.0_f64.to_bits(), + ]); + let owner = Arc::downgrade(&storage); + let borrowed = ErlTerm::boxed(storage.as_ptr()).with_external_bit(); + let start = storage.as_ptr() as usize; + let bytes = std::mem::size_of_val(storage.as_ref()); + heap.retain_borrowed_heap(storage, start..start + bytes, bytes); + let container = if cons { + heap.alloc_cons(borrowed, ErlTerm::nil()) + } else { + heap.alloc_tuple(&[borrowed]) + }; + let mut roots = [container, ErlTerm::small_int(-7)]; + + for _ in 0..3 { + heap.collect_minor(&mut roots); + assert!(owner.upgrade().is_some(), "minor GC dropped live ETS storage"); + } + heap.collect_major(&mut roots); + assert!(owner.upgrade().is_some(), "major GC dropped live ETS storage"); + heap.collect_major(&mut roots[1..]); + assert!(owner.upgrade().is_none(), "major GC kept dead ETS storage"); + } + } + #[test] fn major_gc_compacts_both_generations() { let mut heap = ProcessHeap::new(); diff --git a/crates/nera-runtime/src/message.rs b/crates/nera-runtime/src/message.rs index 4590c0d..200aca3 100644 --- a/crates/nera-runtime/src/message.rs +++ b/crates/nera-runtime/src/message.rs @@ -734,6 +734,29 @@ mod tests { BIGINT_SIGN_WORD_INDEX, BOXED_BIGINT, BOXED_MAP, }; + #[test] + fn negative_small_ints_survive_message_copies() { + let mut source = ProcessHeap::new(); + let min = ErlTerm::small_int(crate::term::SMALL_INT_MIN); + let negative = ErlTerm::small_int(-7); + let inline = source.alloc_tuple(&[min, negative]); + let simple = source.alloc_tuple(&[ErlTerm::atom(1), min, negative]); + let nested = source.alloc_tuple(&[inline, simple]); + + for root in [negative, inline, simple, nested] { + let mut target = ProcessHeap::new(); + // SAFETY: sender and target have separate, live heaps. + let direct = unsafe { direct_copy_message(root, &mut target) }; + let queued = unsafe { MessageFragment::from_term(root) }.copy_to_heap(&mut target); + for copy in [direct, queued] { + let equal = unsafe { + crate::ffi::compare::nera_rt_exact_eq(std::ptr::null_mut(), root.0, copy.0) + }; + assert_eq!(equal, ErlTerm::atom(crate::atom_table::ATOM_TRUE).0); + } + } + } + #[test] fn partial_refc_windows_keep_bit_length_through_all_message_paths() { for arity in [0,2,4] { diff --git a/crates/nera-runtime/src/process.rs b/crates/nera-runtime/src/process.rs index c2a55c4..4ac1383 100644 --- a/crates/nera-runtime/src/process.rs +++ b/crates/nera-runtime/src/process.rs @@ -3203,7 +3203,9 @@ mod tests { ]); let owner = std::sync::Arc::downgrade(&storage); let term = ErlTerm::boxed(storage.as_ptr()).with_external_bit(); - process.heap.retain_borrowed_heap(storage); + let start = storage.as_ptr() as usize; + let bytes = std::mem::size_of_val(storage.as_slice()); + process.heap.retain_borrowed_heap(storage, start..start + bytes, bytes); process.dictionary.push((ErlTerm::small_int(1), term)); // SAFETY: the initialized external graph is anchored by this heap. unsafe { process.hibernate(); } diff --git a/crates/nera-runtime/src/term.rs b/crates/nera-runtime/src/term.rs index 3fce46e..f06166f 100644 --- a/crates/nera-runtime/src/term.rs +++ b/crates/nera-runtime/src/term.rs @@ -55,9 +55,8 @@ pub const TOMBSTONE_VALUE: u64 = 0b110; /// The tombstone is never a term, and `Mailbox::send` refuses it as a message. pub const NO_MESSAGE_VALUE: u64 = TOMBSTONE_VALUE; -/// Bit 63 marks a term as "external" — it points into ETS storage -/// (Arc-owned CompactHeap), not the process arena. GC must not -/// relocate or forward external terms. +/// Bit 63 marks a cons or boxed pointer into ETS storage, which GC must not +/// relocate. On a small integer it is part of the signed payload instead. pub const EXTERNAL_BIT: u64 = 1u64 << 63; /// Minimum value representable as a small integer (61-bit signed). @@ -807,22 +806,33 @@ impl ErlTerm { // -- External bit helpers ----------------------------------------------- - /// True if this term has the EXTERNAL_BIT set (points into ETS storage). + /// True only for a pointer tagged as borrowing ETS storage. #[inline] pub fn is_external(&self) -> bool { - self.0 & EXTERNAL_BIT != 0 + self.0 & EXTERNAL_BIT != 0 && self.has_pointer_tag() + } + + #[inline] + fn has_pointer_tag(&self) -> bool { + matches!(self.tag(), TAG_BOXED | TAG_CONS) } - /// Return a copy of this term with EXTERNAL_BIT set. #[inline] pub fn with_external_bit(&self) -> ErlTerm { - ErlTerm(self.0 | EXTERNAL_BIT) + if self.has_pointer_tag() { + ErlTerm(self.0 | EXTERNAL_BIT) + } else { + *self + } } - /// Return a copy of this term with EXTERNAL_BIT cleared. #[inline] pub fn strip_external_bit(&self) -> ErlTerm { - ErlTerm(self.0 & !EXTERNAL_BIT) + if self.is_external() { + ErlTerm(self.0 & !EXTERNAL_BIT) + } else { + *self + } } } @@ -1125,6 +1135,27 @@ mod tests { } } + #[test] + fn external_marker_is_only_for_cons_and_boxed_pointers() { + let mut heap = ProcessHeap::new(); + let cons = heap.alloc_cons(ErlTerm::small_int(1), ErlTerm::nil()); + let boxed = heap.alloc_tuple(&[cons]); + for term in [cons, boxed] { + let external = term.with_external_bit(); + assert!(!term.is_external()); + assert!(external.is_external()); + assert_eq!(external.strip_external_bit(), term); + assert_eq!(external.as_cons_ptr(), term.as_cons_ptr()); + assert_eq!(external.as_boxed_ptr(), term.as_boxed_ptr()); + } + + let negative = ErlTerm::small_int(SMALL_INT_MIN); + assert!(!negative.is_external()); + assert_eq!(negative.strip_external_bit().as_small_int(), Some(SMALL_INT_MIN)); + let positive = ErlTerm::small_int(1); + assert_eq!(positive.with_external_bit(), positive); + } + #[test] fn atom_roundtrip() { for id in [0u32, 1, 42, 1000, u32::MAX >> 3] { diff --git a/docs/ETS_OPTIMIZATION_PLAN.md b/docs/ETS_OPTIMIZATION_PLAN.md index e5e6a90..8c6bdfc 100644 --- a/docs/ETS_OPTIMIZATION_PLAN.md +++ b/docs/ETS_OPTIMIZATION_PLAN.md @@ -197,15 +197,15 @@ Term operations: |------------------|--------------------------------------------| | `is_boxed()` | Check low 3 bits = 000 (unchanged) | | `is_cons()` | Check low 3 bits = 001 (unchanged) | -| `is_external()` | Check bit 63 (new) | +| `is_external()` | Check bit 63 only on boxed and cons tags | | `as_boxed_ptr()` | Mask off bit 63 + low 3 bits | | Pattern match | Follow pointer transparently (mask bit 63) | | Comparison | Follow pointer transparently | | Hashing | Follow pointer transparently | -The external bit is set ONLY on terms returned from ETS lookups. It -tells the GC: "this pointer leads to shared memory — do not copy the -target, do not write a forwarding pointer." +Only boxed and cons pointers returned from ETS lookups carry this marker. +For small integers, bit 63 is the sign bit and must be preserved. The +marker tells GC not to copy the shared target or write a forwarding pointer. #### 5c. GC integration @@ -229,36 +229,30 @@ copy_term(term): if immediate → return as-is if term.is_external(): // Shared storage — do not copy, do not write forwarding pointer - record associated Arc as "live" (like live_refc_ptrs) + record which snapshot contains the external pointer return term // keep pointing to CompactHeap if forwarding[old_addr] exists → return forwarded ... (normal copy path) ``` -Process heap adds a new field: +The process heap keeps a `BTreeMap` keyed by each +retained snapshot's buffer start address. Each entry holds its end address, +accounted byte count and owning reference. -```rust -pub struct ProcessHeap { - // ... existing fields ... - pub refc_binaries: Vec>>, - pub borrowed_heaps: Vec>, // NEW -} -``` - -Post-GC sweep for borrowed_heaps mirrors refc_binaries: +Minor GC skips old container contents, so it keeps all `borrowed_heaps` owners. +Major GC traces both generations and keeps the snapshot containing each live +external pointer. Before freeing unused snapshots, it retains the backing of +any binary copied from a projected ETS value. -```rust -// Track which Arc pointers are still reachable -// (from external terms encountered during copy_term) -self.borrowed_heaps.retain(|arc| { - let raw_ptr = Arc::as_ptr(arc) as u64; - copier.live_borrowed_ptrs.contains(&raw_ptr) -}); -``` +Each distinct retained snapshot counts once toward a full collection, including +its word buffer and binary payloads. The threshold starts at 1 MiB and grows +with the storage still live after a full collection. If a collection drops its +only snapshot, a lone snapshot up to that size does not trigger another full +collection. The normal threshold still applies when distinct snapshots accumulate. #### 5d. Lookup path — before vs after -**Before (current):** +**Before zero-copy lookups:** ``` map.read() @@ -272,58 +266,24 @@ alloc cons cell on process heap ``` map.read() -Arc::clone(inner) ← 1 atomic op +for each element: + mark boxed or cons pointers; leave immediates unchanged +if a pointer was marked: + register a retained owner by its buffer start address if not already present alloc tuple wrapper on process heap ← 1+N words -mark elements as external (set bit 63) ← N bitwise ORs alloc cons cell ← 2 words -store Arc in process.borrowed_heaps ``` -Total cost: 1 atomic + N+3 words of process heap. No recursive walk. -No data copy. O(1) regardless of term complexity. - -#### 5e. Identifying external Arcs during GC +The lookup walks the top-level fields, not the nested data. Immediate-only +rows do not register an owner. -When GC encounters an external boxed pointer, it needs to find which -`Arc` to mark as live. Options: +#### 5e. Identifying external owners during GC -- **A. Embed an identifier in the external term**: Use unused bits in - the pointer or header to encode an index into `borrowed_heaps`. - Fast but fragile (index invalidated if Vec is reordered). - -- **B. HashMap from address range to Arc index**: Pre-build a mapping - from CompactHeap word buffer address ranges to borrowed_heaps - indices. O(1) lookup with a sorted-range binary search. - -- **C. Mark ALL borrowed_heaps as live during GC, sweep separately**: - During GC, don't try to match individual external pointers to - specific Arcs. Instead, just keep a flag `has_external_terms: bool`. - After GC, if no external terms survived, clear all borrowed_heaps. - If any survived, keep all. This over-retains but is simple and - correct. On the next GC cycle, the stale Arcs will be dropped if - the process no longer holds external terms. - -- **D. Stamp each external term with the Arc's raw pointer**: Store the - `Arc::as_ptr()` value in a side table or in unused bits. GC records - seen Arc pointers in a `live_borrowed_ptrs: HashSet`, then - sweeps borrowed_heaps via `retain()`. This mirrors the refc binary - pattern exactly. - -**Recommended: Option D** — it matches the existing refc binary sweep -pattern. The Arc raw pointer can be stored in the process's own data -structure (e.g., a `HashMap` built when the Arc is -first borrowed). - -The simplest implementation: when a zero-copy lookup returns, store a -mapping `(words_ptr..words_ptr+words_len) → Arc::as_ptr()` in the -process. When GC encounters an external pointer, look up which Arc it -belongs to and add to `live_borrowed_ptrs`. After GC, sweep. - -An even simpler approach: since each `StoredTupleInner` contains a -`CompactHeap` with a known `words_ptr`, the GC can check if an external -pointer falls within any borrowed CompactHeap's range. With -borrowed_heaps being a small Vec (typically 0-10 entries), a linear -scan is fast enough. +For each external pointer seen during a full trace, look up the greatest +buffer start address at or below that pointer. Check that the address is +below the recorded end before marking the owner live. This locates interior +pointers without putting an owner identifier in the term. If an address +cannot be matched, keep all owners rather than risk releasing live storage. ### Safety argument @@ -714,10 +674,11 @@ here would be silent and devastating. #### A4. External bit tag (Rust unit) -- Create an ErlTerm with bit 63 set, verify `is_external() == true` -- Verify `is_boxed()` still works (low 3 bits unchanged) -- Verify `as_boxed_ptr()` masks bit 63 and returns correct address -- Round-trip: `boxed_external(ptr)` → `as_boxed_ptr()` → same ptr +- Mark a boxed pointer and a cons pointer with `with_external_bit()`; + verify `is_external()` recognizes each and pointer accessors return the + original addresses. +- Verify a negative small integer is not external and `strip_external_bit()` + leaves its signed value intact. #### A5. GC skips external pointers (Rust unit) @@ -725,7 +686,8 @@ here would be silent and devastating. - Run GC (collect) - Verify: local terms were relocated (new addresses) - Verify: external terms kept their original addresses (unchanged) -- Verify: borrowed_heaps Vec retains only live Arcs +- Verify: owners survive repeated minor collections even when their pointers + are reachable only through old containers. #### A6. GC does not write forwarding pointers to external memory (Rust unit) @@ -747,7 +709,7 @@ here would be silent and devastating. - Lookup term → borrowed_heaps has 1 Arc (count=2) - Overwrite the process variable (term no longer in roots) -- Run GC +- Run major GC with no external pointers left in the live graph - Verify: Arc swept from borrowed_heaps (count=1, only table) #### B6. Concurrent lookup + delete with zero-copy (Rust) @@ -871,10 +833,12 @@ After a test that inserts and deletes many entries: - Check `pool.live_region_count() == 0` - With zero-copy: after all processes drop their Arcs, verify same -After a test with zero-copy lookups + GC: -- Force GC on all processes -- Verify `borrowed_heaps.len() == 0` (all Arcs swept) -- Verify `Arc::strong_count() == 1` (only table holds it) +After a test with zero-copy lookups: +- Drop the lookup results from the roots and force a full collection in each + process. +- Verify no borrowed owners remain and only the table owns the snapshot. +- In a separate run with one lookup result rooted, verify its owner survives + while unused owners are reclaimed. ### Phase 6 verification (zero-copy message relay) diff --git a/tests/README.md b/tests/README.md index 3e17984..d461060 100644 --- a/tests/README.md +++ b/tests/README.md @@ -63,6 +63,13 @@ retained line prefix is followed by new socket data. It requires `recv_timeout_active_ok` and also runs unchanged on BEAM. These assertions prevent kernel-only readiness or line scanning from stranding retained bytes or delivering later bytes first. +## Negative integers in messages + +`nera test send_negative_small_int` checks the exact mailbox values for +inline tuples and messages sent by a spawned process, including the native +small-integer boundary. The same fixture runs on BEAM with `erlc` and +`send_negative_small_int:test/0`; it must print `send_negative_small_int_ok`. + ## Focused runtime contracts The [runtime contract index](../docs/RUNTIME_CONTRACTS.md) names the semantic diff --git a/tests/send_negative_small_int.erl b/tests/send_negative_small_int.erl new file mode 100644 index 0000000..527b69b --- /dev/null +++ b/tests/send_negative_small_int.erl @@ -0,0 +1,34 @@ +-module(send_negative_small_int). +-export([test/0, send_tuple/2]). + +%% EXPECT: send_negative_small_int_ok + +test() -> + Parent = self(), + Min = id(-(1 bsl 60)), + Parent ! {id(-3)}, + {-3} = next_message(), + Parent ! {id(-1), Min, id(0), id(42)}, + {-1, Min, 0, 42} = next_message(), + Parent ! id(-3), + -3 = next_message(), + spawn(fun() -> Parent ! id(-7) end), + -7 = next_message(), + spawn(?MODULE, send_tuple, [Parent, Min]), + {Min, -11} = next_message(), + spawn(fun() -> Parent ! {tag, id(-13), {[Min], id(-15)}} end), + {tag, -13, {[Min], -15}} = next_message(), + spawn(fun() -> Parent ! {id(-17), id(-19), id(0), id(1), id(Min - 1)} end), + {-17, -19, 0, 1, -1152921504606846977} = next_message(), + io:format("send_negative_small_int_ok~n"), + ok. + +send_tuple(Parent, Min) -> + Parent ! {Min, id(-11)}. + +id(X) -> X. + +next_message() -> + receive Value -> Value + after 5000 -> erlang:error(message_timeout) + end.