Skip to main content

cljrs_gc/
lib.rs

1//! Garbage collector (default) or region-based allocator (`no-gc` feature) for clojurust.
2
3#![allow(clippy::missing_safety_doc)]
4#![allow(private_interfaces)]
5
6use std::ptr::NonNull;
7
8pub mod region;
9pub mod stats;
10
11#[cfg(not(feature = "no-gc"))]
12pub mod cancellation;
13#[cfg(not(feature = "no-gc"))]
14pub mod config;
15
16#[cfg(feature = "no-gc")]
17pub mod alloc_ctx;
18#[cfg(feature = "no-gc")]
19pub mod static_arena;
20
21pub use stats::{CLJRS_GC_STATS_ENV, GC_STATS, GcStats, GcStatsSnapshot, dump_stats_from_env};
22
23// ── Re-exports from active implementation ─────────────────────────────────────
24
25#[cfg(not(feature = "no-gc"))]
26pub use cancellation::{
27    CancellableGuard, MutatorGuard, StwGuard, begin_stw, check_cancellation, gc_requested,
28    park_thread, register_mutator, registered_threads, request_gc, safepoint, take_gc_request,
29    unpark_thread, wait_for_threads_to_park,
30};
31#[cfg(not(feature = "no-gc"))]
32pub use config::{GC_CANCELLATION as CONFIG_CANCELLATION, GcConfig, GcParked};
33
34#[cfg(not(feature = "no-gc"))]
35pub use gc_full::{
36    AllocRootGuard, GcHeap, HEAP, HeapProxy, push_alloc_frame, trace_thread_alloc_roots,
37};
38#[cfg(feature = "no-gc")]
39pub use nogc_stubs::{
40    AllocRootGuard, CONFIG_CANCELLATION, CancellableGuard, GcConfig, GcHeap, GcParked, HEAP,
41    MutatorGuard, StwGuard, begin_stw, check_cancellation, gc_requested, park_thread,
42    push_alloc_frame, register_mutator, registered_threads, request_gc, safepoint, take_gc_request,
43    unpark_thread, wait_for_threads_to_park,
44};
45
46/// Return `true` if `addr` was allocated by the global `StaticArena`.
47///
48/// Available only in `no-gc` debug builds.  Downstream crates (`cljrs-value`)
49/// use this to implement write-site provenance assertions.
50#[cfg(all(feature = "no-gc", debug_assertions))]
51pub fn is_static_addr(addr: usize) -> bool {
52    static_arena::is_static_addr(addr)
53}
54
55// ── Trace trait ───────────────────────────────────────────────────────────────
56
57/// Implemented by every type that can be stored behind a [`GcPtr`].
58///
59/// The `gc_size_extra` method accounts for heap bytes owned by the value that
60/// are NOT captured by `size_of::<GcBox<T>>()` (e.g. `Vec` buffers, `String`
61/// capacity, `Form` AST trees stored inline).  The default returns 0, which is
62/// correct for primitives and types with no out-of-line heap.
63///
64/// Rules for implementors of `gc_size_extra`:
65/// - Count only bytes THIS value owns and will free when dropped.
66/// - Do NOT cross `GcPtr` boundaries — each pointed-to box is counted
67///   separately when it is allocated.
68pub trait Trace {
69    fn trace(&self, visitor: &mut MarkVisitor);
70
71    fn gc_size_extra(&self) -> usize {
72        0
73    }
74}
75
76// ── Leaf Trace impls ──────────────────────────────────────────────────────────
77
78impl Trace for String {
79    fn trace(&self, _: &mut MarkVisitor) {}
80
81    fn gc_size_extra(&self) -> usize {
82        self.capacity()
83    }
84}
85impl Trace for i64 {
86    fn trace(&self, _: &mut MarkVisitor) {}
87}
88impl Trace for f64 {
89    fn trace(&self, _: &mut MarkVisitor) {}
90}
91impl Trace for bool {
92    fn trace(&self, _: &mut MarkVisitor) {}
93}
94impl Trace for num_bigint::BigInt {
95    fn trace(&self, _: &mut MarkVisitor) {}
96}
97impl Trace for bigdecimal::BigDecimal {
98    fn trace(&self, _: &mut MarkVisitor) {}
99}
100impl Trace for num_rational::Ratio<num_bigint::BigInt> {
101    fn trace(&self, _: &mut MarkVisitor) {}
102}
103impl Trace for regex::Regex {
104    fn trace(&self, _: &mut MarkVisitor) {}
105}
106macro_rules! impl_trace_prim_array {
107    ($t:ty) => {
108        impl Trace for std::sync::Mutex<Vec<$t>> {
109            fn trace(&self, _: &mut MarkVisitor) {}
110            fn gc_size_extra(&self) -> usize {
111                self.lock().unwrap().capacity() * std::mem::size_of::<$t>()
112            }
113        }
114    };
115}
116impl_trace_prim_array!(i32);
117impl_trace_prim_array!(i64);
118impl_trace_prim_array!(i16);
119impl_trace_prim_array!(i8);
120impl_trace_prim_array!(char);
121impl_trace_prim_array!(f64);
122impl_trace_prim_array!(f32);
123impl_trace_prim_array!(bool);
124
125// ── GcVisitor ─────────────────────────────────────────────────────────────────
126
127pub trait GcVisitor {
128    fn visit<T: Trace + 'static>(&mut self, ptr: &GcPtr<T>);
129}
130
131// =============================================================================
132// GC build: GcBox with header, MarkVisitor with grey stack
133// =============================================================================
134
135#[cfg(not(feature = "no-gc"))]
136pub use self::gc_header::{GcBox, GcBoxHeader};
137
138#[cfg(not(feature = "no-gc"))]
139mod gc_header {
140    use crate::{MarkVisitor, Trace};
141    use std::cell::Cell;
142
143    // Objects start at lives = GC_INITIAL_LIVES - 1.  The mark phase sets
144    // lives = GC_INITIAL_LIVES for reachable objects; sweep frees objects
145    // whose lives reach 0.  A value of 2 gives exactly one cycle of grace:
146    // enough to cover the window between an alloc frame dropping and the
147    // next GC safepoint (where VALUE_ROOTS or a new alloc frame re-roots it).
148    // 10 was chosen conservatively but keeps 9× more garbage in RAM than
149    // necessary, worsening OOM pressure under test suites with many forms.
150    pub(crate) const GC_INITIAL_LIVES: u8 = 2;
151
152    #[cfg(debug_assertions)]
153    pub(crate) const GC_MAGIC_ALIVE: u64 = 0xCAFE_BABE_DEAD_BEEF;
154    #[cfg(debug_assertions)]
155    pub(crate) const GC_MAGIC_FREED: u64 = 0xDEAD_DEAD_DEAD_DEAD;
156
157    #[repr(C)]
158    pub struct GcBoxHeader {
159        #[cfg(debug_assertions)]
160        pub(crate) magic: Cell<u64>,
161        /// Exact size of the GcBox<T> allocation in bytes.
162        pub(crate) size: usize,
163        pub(crate) lives: Cell<u8>,
164        pub(crate) next: Cell<*mut GcBoxHeader>,
165        pub(crate) trace_fn: unsafe fn(*const GcBoxHeader, &mut MarkVisitor),
166        pub(crate) drop_fn: unsafe fn(*mut GcBoxHeader),
167    }
168
169    impl GcBoxHeader {
170        pub(crate) fn new<T: Trace + 'static>(heap_extra: usize) -> Self {
171            Self {
172                #[cfg(debug_assertions)]
173                magic: Cell::new(GC_MAGIC_ALIVE),
174                size: std::mem::size_of::<GcBox<T>>() + heap_extra,
175                lives: Cell::new(GC_INITIAL_LIVES - 1),
176                next: Cell::new(std::ptr::null_mut()),
177                trace_fn: trace_gc_box::<T>,
178                drop_fn: drop_gc_box::<T>,
179            }
180        }
181    }
182
183    unsafe impl Send for GcBoxHeader {}
184    unsafe impl Sync for GcBoxHeader {}
185
186    #[repr(C)]
187    pub struct GcBox<T: Trace + 'static> {
188        pub(crate) header: GcBoxHeader,
189        pub value: T,
190    }
191
192    pub(crate) unsafe fn trace_gc_box<T: Trace + 'static>(
193        header: *const GcBoxHeader,
194        visitor: &mut MarkVisitor,
195    ) {
196        unsafe {
197            let gc_box = header as *const GcBox<T>;
198            (*gc_box).value.trace(visitor);
199        }
200    }
201
202    pub(crate) unsafe fn drop_gc_box<T: Trace + 'static>(header: *mut GcBoxHeader) {
203        unsafe {
204            #[cfg(debug_assertions)]
205            {
206                (*header).magic.set(GC_MAGIC_FREED);
207            }
208            let gc_box = header as *mut GcBox<T>;
209            drop(Box::from_raw(gc_box));
210        }
211    }
212}
213
214// =============================================================================
215// no-gc build: GcBox without header
216// =============================================================================
217
218#[cfg(feature = "no-gc")]
219pub use self::nogc_box::GcBox;
220
221#[cfg(feature = "no-gc")]
222mod nogc_box {
223    use crate::Trace;
224
225    pub struct GcBox<T: Trace + 'static> {
226        pub value: T,
227    }
228}
229
230// =============================================================================
231// MarkVisitor: full under GC, stub under no-gc
232// =============================================================================
233
234#[cfg(not(feature = "no-gc"))]
235#[derive(Default)]
236pub struct MarkVisitor {
237    pub(crate) grey: Vec<*mut GcBoxHeader>,
238}
239
240#[cfg(feature = "no-gc")]
241pub struct MarkVisitor;
242
243#[cfg(not(feature = "no-gc"))]
244impl MarkVisitor {
245    pub fn new() -> Self {
246        Self::default()
247    }
248
249    pub fn grey_len(&self) -> usize {
250        self.grey.len()
251    }
252
253    pub unsafe fn mark_header(&mut self, header: *mut GcBoxHeader) {
254        use gc_header::GC_INITIAL_LIVES;
255        let h = unsafe { &*header };
256        if h.lives.get() < GC_INITIAL_LIVES {
257            h.lives.set(GC_INITIAL_LIVES);
258            self.grey.push(header);
259        }
260    }
261
262    pub(crate) fn drain(&mut self) {
263        let mut visited = 0usize;
264        while let Some(header) = self.grey.pop() {
265            visited += 1;
266            let h = unsafe { &*header };
267            unsafe { (h.trace_fn)(header as *const GcBoxHeader, self) };
268        }
269        cljrs_logging::feat_debug!("gc", "drain visited {} objects", visited);
270    }
271}
272
273#[cfg(not(feature = "no-gc"))]
274impl GcVisitor for MarkVisitor {
275    fn visit<T: Trace + 'static>(&mut self, ptr: &GcPtr<T>) {
276        use gc_header::GC_INITIAL_LIVES;
277        // Region-allocated objects are not on the GC heap; their lifetime is
278        // bounded by the enclosing `Region`, not the collector.  Never
279        // dereference one here: once the region's scope ends its memory is
280        // freed/reused, so the header would be garbage and we'd follow a
281        // dangling `trace_fn`.  Live regions are traced as roots separately
282        // (see `region::trace_active_regions`), so a region's heap-allocated
283        // children are still kept alive.
284        if ptr.is_region_alloc() {
285            return;
286        }
287        let raw = ptr.raw();
288        let header = unsafe { &(*raw).header };
289        if header.lives.get() < GC_INITIAL_LIVES {
290            header.lives.set(GC_INITIAL_LIVES);
291            self.grey.push(raw as *mut GcBoxHeader);
292        }
293    }
294}
295
296#[cfg(feature = "no-gc")]
297impl MarkVisitor {
298    pub fn grey_len(&self) -> usize {
299        0
300    }
301    pub unsafe fn mark_header(&mut self, _: *mut u8) {}
302}
303
304#[cfg(feature = "no-gc")]
305impl GcVisitor for MarkVisitor {
306    fn visit<T: Trace + 'static>(&mut self, _: &GcPtr<T>) {}
307}
308
309// =============================================================================
310// GcPtr — always present
311// =============================================================================
312
313pub struct GcPtr<T: Trace + 'static>(NonNull<GcBox<T>>);
314
315/// Low pointer bit reserved to mark region-allocated `GcPtr`s in GC builds.
316///
317/// `GcBox<T>` (a `GcBoxHeader` followed by the value) is always ≥8-byte
318/// aligned in GC builds, so bit 0 is free.  Region-allocated pointers set it;
319/// GC-heap pointers leave it clear.  This lets the mark phase distinguish a
320/// region object from a heap object **without dereferencing it** — essential,
321/// because a region whose scope has ended leaves dangling pointers whose
322/// headers point at freed (or reused) memory.
323#[cfg(not(feature = "no-gc"))]
324pub(crate) const REGION_PTR_TAG: usize = 1;
325
326impl<T: Trace + 'static> GcPtr<T> {
327    #[cfg(not(feature = "no-gc"))]
328    pub fn new(value: T) -> Self {
329        gc_full::HEAP.alloc(value)
330    }
331
332    #[cfg(feature = "no-gc")]
333    pub fn new(value: T) -> Self {
334        alloc_ctx::alloc_in_ctx(value)
335    }
336
337    /// The untagged `GcBox<T>` address.  In GC builds this masks off the
338    /// region-provenance tag bit; in no-gc builds pointers are never tagged.
339    #[inline]
340    fn raw(&self) -> *mut GcBox<T> {
341        #[cfg(not(feature = "no-gc"))]
342        {
343            (self.0.as_ptr() as usize & !REGION_PTR_TAG) as *mut GcBox<T>
344        }
345        #[cfg(feature = "no-gc")]
346        {
347            self.0.as_ptr()
348        }
349    }
350
351    /// `true` if this pointer was bump-allocated in a [`region::Region`]
352    /// rather than the GC heap.  Region objects are not GC-managed.
353    #[cfg(not(feature = "no-gc"))]
354    #[inline]
355    pub fn is_region_alloc(&self) -> bool {
356        (self.0.as_ptr() as usize & REGION_PTR_TAG) != 0
357    }
358
359    /// Construct a region-tagged pointer from a raw `GcBox<T>` allocated in a
360    /// bump region.
361    ///
362    /// # Safety
363    /// `raw` must be a valid, non-null, ≥8-aligned `GcBox<T>` whose header was
364    /// initialised by [`region::Region::alloc`].
365    #[cfg(not(feature = "no-gc"))]
366    #[inline]
367    pub(crate) unsafe fn from_region_raw(raw: *mut GcBox<T>) -> Self {
368        GcPtr(unsafe { NonNull::new_unchecked((raw as usize | REGION_PTR_TAG) as *mut GcBox<T>) })
369    }
370
371    pub fn get(&self) -> &T {
372        #[cfg(all(debug_assertions, not(feature = "no-gc")))]
373        {
374            use gc_header::GC_MAGIC_ALIVE;
375            let header = unsafe { &(*self.raw()).header };
376            assert_eq!(
377                header.magic.get(),
378                GC_MAGIC_ALIVE,
379                "GcPtr::get() on freed object! magic={:#x}",
380                header.magic.get(),
381            );
382        }
383        unsafe { &(*self.raw()).value }
384    }
385
386    pub fn get_mut(&mut self) -> &mut T {
387        #[cfg(all(debug_assertions, not(feature = "no-gc")))]
388        {
389            use gc_header::GC_MAGIC_ALIVE;
390            let header = unsafe { &(*self.raw()).header };
391            assert_eq!(
392                header.magic.get(),
393                GC_MAGIC_ALIVE,
394                "GcPtr::get_mut() on freed object! magic={:#x}",
395                header.magic.get(),
396            );
397        }
398        unsafe { &mut (*self.raw()).value }
399    }
400
401    pub fn ptr_eq(a: &Self, b: &Self) -> bool {
402        a.0 == b.0
403    }
404
405    /// Return `true` if this pointer was allocated by the global `StaticArena`.
406    ///
407    /// Only meaningful (and only compiled) in `no-gc` debug builds.  Used by
408    /// write-site assertions in `Atom::reset` / `Var::bind` to catch
409    /// region-local values being stored in program-lifetime containers.
410    #[cfg(all(feature = "no-gc", debug_assertions))]
411    pub fn is_static_alloc(&self) -> bool {
412        static_arena::is_static_addr(self.0.as_ptr() as usize)
413    }
414}
415
416impl<T: Trace + 'static> Clone for GcPtr<T> {
417    fn clone(&self) -> Self {
418        GcPtr(self.0)
419    }
420}
421
422impl<T: Trace + 'static + std::fmt::Debug> std::fmt::Debug for GcPtr<T> {
423    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
424        unsafe { (*self.raw()).value.fmt(f) }
425    }
426}
427
428impl<T: Trace + 'static> Drop for GcPtr<T> {
429    fn drop(&mut self) {}
430}
431
432// =============================================================================
433// StaticGcPtr — Send+Sync pointer to program-lifetime data
434// =============================================================================
435
436/// A raw pointer to a value that lives for the entire program lifetime.
437///
438/// Backed by the global `StaticArena` (in `no-gc` builds) or by `Box::leak`
439/// (in GC builds).  Either way the pointee is never freed and never moved, so
440/// it is safe to share across isolate threads.
441///
442/// `StaticGcPtr<T>` wraps `*const T` — it does **not** involve a `GcBox`
443/// header — so it is independent of the GC build mode and carries no GC
444/// overhead.
445pub struct StaticGcPtr<T: 'static>(NonNull<T>);
446
447// SAFETY: program-lifetime allocations are never moved, freed, or mutated
448// after the initial write.  The stored types (Keyword, Symbol, …) are
449// themselves `Sync` (no unsynchronised interior mutability).
450unsafe impl<T: 'static> Send for StaticGcPtr<T> {}
451unsafe impl<T: 'static> Sync for StaticGcPtr<T> {}
452
453impl<T: 'static> StaticGcPtr<T> {
454    /// Borrow the contained value.
455    pub fn get(&self) -> &T {
456        // SAFETY: pointer is program-lifetime, always valid.
457        unsafe { self.0.as_ref() }
458    }
459
460    /// Pointer equality: `true` iff both `StaticGcPtr`s point to the exact
461    /// same allocation (i.e. the same interned entry).
462    pub fn ptr_eq(a: &Self, b: &Self) -> bool {
463        a.0 == b.0
464    }
465}
466
467impl<T: 'static> Clone for StaticGcPtr<T> {
468    fn clone(&self) -> Self {
469        StaticGcPtr(self.0)
470    }
471}
472
473impl<T: 'static + std::fmt::Debug> std::fmt::Debug for StaticGcPtr<T> {
474    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
475        unsafe { self.0.as_ref().fmt(f) }
476    }
477}
478
479/// Allocate `value` as program-lifetime memory and return a [`StaticGcPtr`].
480///
481/// In `no-gc` builds the allocation comes from the global bump-allocated
482/// `StaticArena` (never freed, no GC header overhead).  In GC builds
483/// `Box::leak` is used instead — the memory lives until the process exits.
484pub fn static_alloc<T: 'static>(value: T) -> StaticGcPtr<T> {
485    #[cfg(feature = "no-gc")]
486    {
487        static_arena::static_alloc_val(value)
488    }
489    #[cfg(not(feature = "no-gc"))]
490    {
491        StaticGcPtr(NonNull::from(Box::leak(Box::new(value))))
492    }
493}
494
495// =============================================================================
496// Full GC implementation (default build)
497// =============================================================================
498
499#[cfg(not(feature = "no-gc"))]
500mod gc_full {
501    use std::cell::RefCell;
502    use std::ptr::NonNull;
503    use std::sync::atomic::{AtomicUsize, Ordering};
504    use std::sync::{Arc, Mutex};
505
506    use crate::config::GcConfig;
507    use crate::gc_header::GC_INITIAL_LIVES;
508    use crate::{GcBox, GcBoxHeader, GcPtr, MarkVisitor, Trace};
509
510    type RootTracer = Box<dyn Fn(&mut MarkVisitor)>;
511
512    pub struct GcHeap {
513        inner: Mutex<GcHeapInner>,
514        config: Mutex<Option<Arc<GcConfig>>>,
515        memory_in_use: AtomicUsize,
516        total_allocated_bytes: AtomicUsize,
517        root_tracers: Mutex<Vec<RootTracer>>,
518        gc_suppressed: std::sync::atomic::AtomicBool,
519        /// memory_in_use threshold above which GC is re-enabled after a
520        /// zero-yield collection.  The headroom doubles on each consecutive
521        /// zero-yield cycle (exponential backoff, capped at soft_limit) so a
522        /// long computation where all objects are live doesn't spin in a
523        /// constant GC storm of O(N) sweeps.  Resets to the base headroom
524        /// (soft_limit / 10) once GC actually frees something.
525        suppressed_threshold: AtomicUsize,
526        /// Current headroom used for exponential backoff after zero-yield cycles.
527        zero_yield_headroom: AtomicUsize,
528    }
529
530    struct GcHeapInner {
531        head: *mut GcBoxHeader,
532        count: usize,
533        total_allocated: usize,
534        total_freed: usize,
535    }
536
537    unsafe impl Send for GcHeapInner {}
538
539    impl GcHeapInner {
540        const fn new() -> Self {
541            Self {
542                head: std::ptr::null_mut(),
543                count: 0,
544                total_allocated: 0,
545                total_freed: 0,
546            }
547        }
548    }
549
550    unsafe impl Sync for GcHeap {}
551
552    impl Default for GcHeap {
553        fn default() -> Self {
554            Self::new()
555        }
556    }
557
558    impl GcHeap {
559        pub const fn new() -> Self {
560            Self {
561                inner: Mutex::new(GcHeapInner::new()),
562                config: Mutex::new(None),
563                memory_in_use: AtomicUsize::new(0),
564                total_allocated_bytes: AtomicUsize::new(0),
565                root_tracers: Mutex::new(Vec::new()),
566                gc_suppressed: std::sync::atomic::AtomicBool::new(false),
567                suppressed_threshold: AtomicUsize::new(0),
568                zero_yield_headroom: AtomicUsize::new(0),
569            }
570        }
571
572        pub fn set_config(&self, config: Arc<GcConfig>) {
573            *self.config.lock().unwrap() = Some(config);
574        }
575
576        pub fn set_config_from_env(&self) {
577            #[cfg(not(target_arch = "wasm32"))]
578            let default_soft_limit: usize = (system_memory::total() / 3) as usize;
579            #[cfg(target_arch = "wasm32")]
580            let default_soft_limit: usize = 64 * 1024 * 1024;
581
582            let soft_limit_mb: usize = match std::env::var("CLJRS_GC_SOFT_LIMIT_MB").ok() {
583                Some(s) => s.parse::<usize>().unwrap() * (1024 * 1024),
584                None => default_soft_limit,
585            };
586            let hard_limit_mb: usize = match std::env::var("CLJRS_GC_HARD_LIMIT_MB").ok() {
587                Some(s) => s.parse::<usize>().unwrap() * (1024 * 1024),
588                None => soft_limit_mb,
589            };
590            self.set_config(Arc::new(GcConfig::with_limits(
591                soft_limit_mb,
592                hard_limit_mb,
593            )));
594        }
595
596        pub fn register_root_tracer(&self, tracer: impl Fn(&mut MarkVisitor) + 'static) {
597            self.root_tracers.lock().unwrap().push(Box::new(tracer));
598        }
599
600        pub fn trace_registered_roots(&self, visitor: &mut MarkVisitor) {
601            let tracers = self.root_tracers.lock().unwrap();
602            for tracer in tracers.iter() {
603                tracer(visitor);
604            }
605        }
606
607        pub fn memory_in_use(&self) -> usize {
608            self.memory_in_use.load(Ordering::Relaxed)
609        }
610
611        #[cfg(test)]
612        pub fn set_memory_in_use(&self, bytes: usize) {
613            self.memory_in_use.store(bytes, Ordering::Relaxed);
614        }
615
616        pub fn alloc<T: Trace + 'static>(&self, value: T) -> GcPtr<T> {
617            crate::cancellation::safepoint();
618            let heap_extra = value.gc_size_extra();
619            let gc_box = Box::new(GcBox {
620                header: GcBoxHeader::new::<T>(heap_extra),
621                value,
622            });
623            let obj_size = gc_box.header.size; // GcBox<T> size + gc_size_extra()
624            let raw: *mut GcBox<T> = Box::into_raw(gc_box);
625            {
626                let mut inner = self.inner.lock().unwrap();
627                unsafe {
628                    (*raw).header.next.set(inner.head);
629                    inner.head = raw as *mut GcBoxHeader;
630                }
631                inner.count += 1;
632                inner.total_allocated += 1;
633            }
634            self.total_allocated_bytes
635                .fetch_add(obj_size, Ordering::Relaxed);
636            crate::stats::GC_STATS.record_gc_alloc(obj_size);
637            let current_usage =
638                self.memory_in_use.fetch_add(obj_size, Ordering::Relaxed) + obj_size;
639
640            if let Some(config) = self.config.lock().unwrap().as_ref()
641                && config.soft_limit_exceeded(current_usage)
642            {
643                if self.gc_suppressed.load(Ordering::Relaxed) {
644                    // Suppression active: only re-enable GC once memory has
645                    // grown past the threshold set by the last zero-yield
646                    // collection (current_memory + soft_limit/10).
647                    let threshold = self.suppressed_threshold.load(Ordering::Relaxed);
648                    if current_usage > threshold {
649                        self.gc_suppressed.store(false, Ordering::Relaxed);
650                        crate::cancellation::request_gc();
651                    }
652                } else {
653                    crate::cancellation::request_gc();
654                }
655            }
656
657            register_alloc(raw as *mut GcBoxHeader);
658            GcPtr(unsafe { NonNull::new_unchecked(raw) })
659        }
660
661        pub fn collect<F: FnOnce(&mut MarkVisitor)>(&self, trace_roots: F) {
662            let pre_count = self.inner.lock().unwrap().count;
663            let pre_memory = self.memory_in_use.load(Ordering::Relaxed);
664            cljrs_logging::feat_debug!(
665                "gc",
666                "starting collection: {} objects, ~{} bytes in use",
667                pre_count,
668                pre_memory
669            );
670            let mark_start = std::time::Instant::now();
671            let mut visitor = MarkVisitor::new();
672            trace_roots(&mut visitor);
673            // Active bump regions are additional roots: a live region object
674            // may hold `GcPtr`s into the heap, and those heap objects must not
675            // be collected while the region can still reach them.  The mark
676            // phase skips region objects themselves (they are not heap-managed),
677            // so we trace their children here instead.
678            crate::region::trace_active_regions(&mut visitor);
679            cljrs_logging::feat_debug!(
680                "gc",
681                "starting drain with {} grey objects",
682                visitor.grey.len()
683            );
684            visitor.drain();
685            let mark_elapsed = mark_start.elapsed();
686
687            let sweep_start = std::time::Instant::now();
688            let mut inner = self.inner.lock().unwrap();
689            let mut live: Vec<*mut GcBoxHeader> = Vec::with_capacity(inner.count);
690            let mut dead: Vec<*mut GcBoxHeader> = Vec::new();
691            // Bytes of objects with lives==0 that will be freed now.
692            let mut freed_bytes: usize = 0;
693            let mut current = inner.head;
694            while !current.is_null() {
695                let header = unsafe { &*current };
696                let next = header.next.get();
697                let lives = header.lives.get();
698                let obj_size = header.size;
699                if lives >= GC_INITIAL_LIVES {
700                    // Marked reachable this cycle — reset grace counter.
701                    header.lives.set(GC_INITIAL_LIVES - 1);
702                    live.push(current);
703                } else if lives > 0 {
704                    // In grace period (unreachable but not yet freed).
705                    header.lives.set(lives - 1);
706                    live.push(current);
707                } else {
708                    // Grace period exhausted — collect now.
709                    freed_bytes += obj_size;
710                    dead.push(current);
711                }
712                current = next;
713            }
714            let freed_count = dead.len();
715            for ptr in dead {
716                let header = unsafe { &*ptr };
717                unsafe { (header.drop_fn)(ptr) };
718                inner.count -= 1;
719                inner.total_freed += 1;
720            }
721            inner.head = std::ptr::null_mut();
722            for ptr in live {
723                let header = unsafe { &*ptr };
724                header.next.set(inner.head);
725                inner.head = ptr;
726            }
727            // Decrement memory_in_use by the bytes actually freed.  All heap
728            // objects (live + grace-period) remain counted; only physically
729            // freed objects are subtracted.  This keeps memory pressure
730            // accurate so GC fires again when the heap genuinely grows.
731            self.memory_in_use.fetch_sub(freed_bytes, Ordering::Relaxed);
732            let sweep_elapsed = sweep_start.elapsed();
733            crate::stats::GC_STATS.record_gc_pause(
734                mark_elapsed + sweep_elapsed,
735                freed_count as u64,
736                freed_bytes as u64,
737            );
738            let post_memory = self.memory_in_use.load(Ordering::Relaxed);
739            cljrs_logging::feat_debug!(
740                "gc",
741                "collection complete: freed {} (~{} bytes), {} remaining (~{} bytes), mark={:.2?} sweep={:.2?}",
742                freed_count,
743                freed_bytes,
744                inner.count,
745                post_memory,
746                mark_elapsed,
747                sweep_elapsed
748            );
749            if freed_count == 0 {
750                // Zero-yield collection: exponential-backoff suppression.
751                // Each consecutive zero-yield cycle doubles the headroom before
752                // the next GC attempt (capped at soft_limit/4).  This prevents a
753                // GC storm during deep recursion where all objects are live —
754                // without backoff, GC fires every soft_limit/10 bytes, tracing
755                // the entire live set O(N) times to no benefit.
756                // The headroom resets to soft_limit/10 when GC frees something.
757                // Cap at soft_limit/4 (not soft_limit) so that GC still fires
758                // frequently enough to catch short-lived test allocations after
759                // a long namespace-loading phase of zero-yield cycles.
760                let soft_limit = self
761                    .config
762                    .lock()
763                    .unwrap()
764                    .as_ref()
765                    .map(|c| c.soft_limit())
766                    .unwrap_or(64 * 1024 * 1024);
767                let base_headroom = (soft_limit / 10).max(1);
768                let max_headroom = (soft_limit / 4).max(base_headroom);
769                let prev_headroom = self.zero_yield_headroom.load(Ordering::Relaxed);
770                let headroom = if prev_headroom == 0 {
771                    base_headroom
772                } else {
773                    prev_headroom.saturating_mul(2).min(max_headroom)
774                };
775                self.zero_yield_headroom.store(headroom, Ordering::Relaxed);
776                self.suppressed_threshold
777                    .store(post_memory + headroom, Ordering::Relaxed);
778                self.gc_suppressed.store(true, Ordering::Relaxed);
779            } else {
780                // GC freed something: reset exponential backoff.
781                self.zero_yield_headroom.store(0, Ordering::Relaxed);
782                self.gc_suppressed.store(false, Ordering::Relaxed);
783            }
784        }
785
786        pub fn count(&self) -> usize {
787            self.inner.lock().unwrap().count
788        }
789        pub fn total_allocated(&self) -> usize {
790            self.inner.lock().unwrap().total_allocated
791        }
792        pub fn total_freed(&self) -> usize {
793            self.inner.lock().unwrap().total_freed
794        }
795
796        pub fn collect_auto(&self) -> bool {
797            cljrs_logging::feat_debug!("gc", "automatic collection requested");
798            let Some(_stw_guard) = crate::cancellation::begin_stw() else {
799                cljrs_logging::feat_debug!("gc", "automatic collection skipped");
800                return false;
801            };
802            self.collect(|visitor| self.trace_registered_roots(visitor));
803            true
804        }
805    }
806
807    thread_local! {
808        static ISOLATE_HEAP: GcHeap = const { GcHeap::new() };
809    }
810
811    /// Zero-sized proxy that dispatches all heap operations to the calling
812    /// thread's [`GcHeap`] via the `ISOLATE_HEAP` thread-local.
813    ///
814    /// This means every isolate (OS thread) owns an independent heap; GC runs
815    /// fully in parallel on different threads with no cross-isolate coordination.
816    pub struct HeapProxy;
817
818    impl HeapProxy {
819        pub fn alloc<T: Trace + 'static>(&self, value: T) -> GcPtr<T> {
820            ISOLATE_HEAP.with(|h| h.alloc(value))
821        }
822
823        pub fn set_config(&self, config: Arc<GcConfig>) {
824            ISOLATE_HEAP.with(|h| h.set_config(config));
825        }
826
827        pub fn set_config_from_env(&self) {
828            ISOLATE_HEAP.with(|h| h.set_config_from_env());
829        }
830
831        pub fn register_root_tracer(&self, tracer: impl Fn(&mut MarkVisitor) + 'static) {
832            ISOLATE_HEAP.with(|h| h.register_root_tracer(tracer));
833        }
834
835        pub fn trace_registered_roots(&self, visitor: &mut MarkVisitor) {
836            ISOLATE_HEAP.with(|h| h.trace_registered_roots(visitor));
837        }
838
839        pub fn memory_in_use(&self) -> usize {
840            ISOLATE_HEAP.with(|h| h.memory_in_use())
841        }
842
843        pub fn count(&self) -> usize {
844            ISOLATE_HEAP.with(|h| h.count())
845        }
846
847        pub fn total_allocated(&self) -> usize {
848            ISOLATE_HEAP.with(|h| h.total_allocated())
849        }
850
851        pub fn total_freed(&self) -> usize {
852            ISOLATE_HEAP.with(|h| h.total_freed())
853        }
854
855        pub fn collect<F: FnOnce(&mut MarkVisitor)>(&self, trace_roots: F) {
856            ISOLATE_HEAP.with(|h| h.collect(trace_roots));
857        }
858
859        pub fn collect_auto(&self) -> bool {
860            ISOLATE_HEAP.with(|h| h.collect_auto())
861        }
862
863        #[cfg(test)]
864        pub fn set_memory_in_use(&self, bytes: usize) {
865            ISOLATE_HEAP.with(|h| h.set_memory_in_use(bytes));
866        }
867    }
868
869    // SAFETY: HeapProxy is zero-sized; all state lives in a thread-local GcHeap.
870    // The Send + Sync impls are needed so `pub static HEAP: HeapProxy` is valid.
871    unsafe impl Sync for HeapProxy {}
872
873    pub static HEAP: HeapProxy = HeapProxy;
874
875    thread_local! {
876        pub(crate) static ALLOC_ROOTS: RefCell<Vec<*mut GcBoxHeader>> = const { RefCell::new(Vec::new()) };
877    }
878
879    pub struct AllocRootGuard {
880        saved_len: usize,
881    }
882
883    impl Drop for AllocRootGuard {
884        fn drop(&mut self) {
885            ALLOC_ROOTS.with(|roots| roots.borrow_mut().truncate(self.saved_len));
886        }
887    }
888
889    pub fn push_alloc_frame() -> AllocRootGuard {
890        let saved_len = ALLOC_ROOTS.with(|roots| roots.borrow().len());
891        AllocRootGuard { saved_len }
892    }
893
894    fn register_alloc(header: *mut GcBoxHeader) {
895        ALLOC_ROOTS.with(|roots| roots.borrow_mut().push(header));
896    }
897
898    pub fn trace_thread_alloc_roots(visitor: &mut MarkVisitor) {
899        ALLOC_ROOTS.with(|roots| {
900            let roots = roots.borrow();
901            for &header in roots.iter() {
902                unsafe { visitor.mark_header(header) };
903            }
904        });
905    }
906}
907
908// =============================================================================
909// no-gc stubs
910// =============================================================================
911
912#[cfg(feature = "no-gc")]
913mod nogc_stubs {
914    use crate::MarkVisitor;
915    use std::sync::Arc;
916
917    #[derive(Debug, Clone)]
918    pub struct GcConfig;
919    impl GcConfig {
920        pub fn new() -> Self {
921            Self
922        }
923        pub fn with_hard_limit(_: usize) -> Self {
924            Self
925        }
926        pub fn with_limits(_: usize, _: usize) -> Self {
927            Self
928        }
929    }
930    impl Default for GcConfig {
931        fn default() -> Self {
932            Self::new()
933        }
934    }
935
936    pub struct GcHeap;
937    impl Default for GcHeap {
938        fn default() -> Self {
939            Self::new()
940        }
941    }
942    impl GcHeap {
943        pub const fn new() -> Self {
944            Self
945        }
946        pub fn set_config(&self, _: Arc<GcConfig>) {}
947        pub fn register_root_tracer(&self, _: impl Fn(&mut MarkVisitor) + 'static) {}
948        pub fn trace_registered_roots(&self, _: &mut MarkVisitor) {}
949        pub fn memory_in_use(&self) -> usize {
950            0
951        }
952        pub fn count(&self) -> usize {
953            0
954        }
955        pub fn total_allocated(&self) -> usize {
956            0
957        }
958        pub fn total_freed(&self) -> usize {
959            0
960        }
961        pub fn collect<F: FnOnce(&mut MarkVisitor)>(&self, _: F) {}
962        pub fn collect_auto(&self) -> bool {
963            false
964        }
965    }
966    unsafe impl Sync for GcHeap {}
967    pub static HEAP: GcHeap = GcHeap::new();
968
969    pub struct MutatorGuard;
970    impl Drop for MutatorGuard {
971        fn drop(&mut self) {}
972    }
973    pub struct StwGuard;
974    impl Drop for StwGuard {
975        fn drop(&mut self) {}
976    }
977    pub struct GcParked;
978    pub struct CancellableGuard;
979
980    pub struct GcCancellationStub;
981    impl GcCancellationStub {
982        pub const fn new() -> Self {
983            Self
984        }
985        pub fn in_progress(&self) -> bool {
986            false
987        }
988    }
989    pub static CONFIG_CANCELLATION: GcCancellationStub = GcCancellationStub::new();
990
991    pub fn safepoint() {}
992    pub fn gc_requested() -> bool {
993        false
994    }
995    pub fn take_gc_request() -> bool {
996        false
997    }
998    pub fn begin_stw() -> Option<StwGuard> {
999        None
1000    }
1001    pub fn register_mutator() -> MutatorGuard {
1002        MutatorGuard
1003    }
1004    pub fn registered_threads() -> usize {
1005        0
1006    }
1007    pub fn request_gc() {}
1008    pub fn check_cancellation() -> Result<(), GcParked> {
1009        Ok(())
1010    }
1011    pub fn park_thread() {}
1012    pub fn unpark_thread() {}
1013    pub fn wait_for_threads_to_park() {}
1014
1015    pub struct AllocRootGuard;
1016    impl Drop for AllocRootGuard {
1017        fn drop(&mut self) {}
1018    }
1019    pub fn push_alloc_frame() -> AllocRootGuard {
1020        AllocRootGuard
1021    }
1022}
1023
1024// =============================================================================
1025// Tests
1026// =============================================================================
1027
1028#[cfg(all(test, not(feature = "no-gc")))]
1029mod tests {
1030    use super::*;
1031    use std::sync::{Arc, Mutex};
1032
1033    #[derive(Debug)]
1034    #[allow(dead_code)]
1035    struct Tracked {
1036        value: i32,
1037        dropped: Arc<Mutex<bool>>,
1038    }
1039    impl Drop for Tracked {
1040        fn drop(&mut self) {
1041            *self.dropped.lock().unwrap() = true;
1042        }
1043    }
1044    impl Trace for Tracked {
1045        fn trace(&self, _: &mut MarkVisitor) {}
1046    }
1047
1048    #[derive(Debug)]
1049    #[allow(dead_code)]
1050    struct Parent {
1051        child: GcPtr<Tracked>,
1052    }
1053    impl Trace for Parent {
1054        fn trace(&self, visitor: &mut MarkVisitor) {
1055            visitor.visit(&self.child);
1056        }
1057    }
1058
1059    fn fresh_heap() -> gc_full::GcHeap {
1060        let heap = gc_full::GcHeap::new();
1061        heap.set_config(Arc::new(GcConfig::with_limits(10000, 50000)));
1062        heap
1063    }
1064
1065    #[test]
1066    fn alloc_and_get() {
1067        let heap = fresh_heap();
1068        let p = heap.alloc(42i64);
1069        assert_eq!(*p.get(), 42);
1070        assert_eq!(heap.count(), 1);
1071    }
1072
1073    #[test]
1074    fn clone_is_same_ptr() {
1075        let heap = fresh_heap();
1076        let p = heap.alloc(99i64);
1077        let q = p.clone();
1078        assert!(GcPtr::ptr_eq(&p, &q));
1079    }
1080
1081    #[test]
1082    fn collect_keeps_reachable() {
1083        let heap = fresh_heap();
1084        let dropped = Arc::new(Mutex::new(false));
1085        let p = heap.alloc(Tracked {
1086            value: 2,
1087            dropped: dropped.clone(),
1088        });
1089        heap.collect(|vis| vis.visit(&p));
1090        assert_eq!(heap.count(), 1);
1091        assert!(!*dropped.lock().unwrap());
1092    }
1093
1094    #[test]
1095    fn b1_two_isolates_independent_heaps() {
1096        use std::sync::{Arc, Barrier};
1097        // Each thread has its own ISOLATE_HEAP; allocations on one do not appear
1098        // in the other.
1099        let barrier = Arc::new(Barrier::new(2));
1100        let b1 = barrier.clone();
1101        let h1 = std::thread::Builder::new()
1102            .name("isolate-1".into())
1103            .spawn(move || {
1104                let _mutator = crate::register_mutator();
1105                // Allocate 100 objects on this isolate's heap
1106                let _ptrs: Vec<_> = (0_i64..100)
1107                    .map(|i| crate::gc_full::HEAP.alloc(i))
1108                    .collect();
1109                b1.wait(); // both threads are now at peak allocation
1110                // This isolate has exactly 100 live objects
1111                assert_eq!(
1112                    crate::gc_full::HEAP.count(),
1113                    100,
1114                    "isolate-1 heap count should be 100"
1115                );
1116            })
1117            .unwrap();
1118
1119        let b2 = barrier.clone();
1120        let h2 = std::thread::Builder::new()
1121            .name("isolate-2".into())
1122            .spawn(move || {
1123                let _mutator = crate::register_mutator();
1124                // Allocate 200 objects on this isolate's heap
1125                let _ptrs: Vec<_> = (0_i64..200)
1126                    .map(|i| crate::gc_full::HEAP.alloc(i))
1127                    .collect();
1128                b2.wait();
1129                // This isolate has exactly 200 live objects, unaffected by isolate-1
1130                assert_eq!(
1131                    crate::gc_full::HEAP.count(),
1132                    200,
1133                    "isolate-2 heap count should be 200"
1134                );
1135            })
1136            .unwrap();
1137
1138        h1.join().expect("isolate-1 panicked");
1139        h2.join().expect("isolate-2 panicked");
1140    }
1141
1142    #[test]
1143    fn b1_two_isolates_gc_independently() {
1144        // Two threads run allocation-heavy loops and GC their own heaps independently.
1145        let h1 = std::thread::Builder::new()
1146            .name("gc-isolate-1".into())
1147            .spawn(|| {
1148                let _mutator = crate::register_mutator();
1149                let heap = &crate::gc_full::HEAP;
1150                heap.set_config(Arc::new(GcConfig::with_limits(16_384, 65_536)));
1151                // Allocate in batches and collect; each collection touches only this heap
1152                for _ in 0..5 {
1153                    let _ptrs: Vec<_> = (0_i64..50).map(|i| heap.alloc(i)).collect();
1154                    // drive a manual collect with no roots so objects are freed
1155                    heap.collect(|_| {});
1156                    heap.collect(|_| {}); // second pass clears grace-period objects
1157                }
1158                // After all collections the heap should be empty (or close to it).
1159                // We don't assert an exact count because alloc_frame roots may keep
1160                // some alive; just assert we can collect without panicking.
1161            })
1162            .unwrap();
1163
1164        let h2 = std::thread::Builder::new()
1165            .name("gc-isolate-2".into())
1166            .spawn(|| {
1167                let _mutator = crate::register_mutator();
1168                let heap = &crate::gc_full::HEAP;
1169                heap.set_config(Arc::new(GcConfig::with_limits(16_384, 65_536)));
1170                for _ in 0..5 {
1171                    let _ptrs: Vec<_> = (0_i64..50).map(|i| heap.alloc(i)).collect();
1172                    heap.collect(|_| {});
1173                    heap.collect(|_| {});
1174                }
1175            })
1176            .unwrap();
1177
1178        h1.join().expect("gc-isolate-1 panicked");
1179        h2.join().expect("gc-isolate-2 panicked");
1180    }
1181}
1182
1183#[cfg(all(test, feature = "no-gc"))]
1184mod nogc_tests {
1185    use super::*;
1186    use alloc_ctx::{ScratchGuard, StaticCtxGuard};
1187
1188    #[test]
1189    fn alloc_in_static_context() {
1190        let _g = StaticCtxGuard::new();
1191        let p = GcPtr::new(42i64);
1192        assert_eq!(*p.get(), 42);
1193    }
1194
1195    #[test]
1196    fn alloc_in_scratch_region() {
1197        let mut scratch = ScratchGuard::new();
1198        let p = GcPtr::new(99i64);
1199        assert_eq!(*p.get(), 99);
1200        scratch.pop_for_return();
1201        assert_eq!(*p.get(), 99);
1202        // scratch drops here, resets the region
1203    }
1204
1205    #[test]
1206    fn ptr_eq() {
1207        let _g = StaticCtxGuard::new();
1208        let p = GcPtr::new(1i64);
1209        let q = p.clone();
1210        assert!(GcPtr::ptr_eq(&p, &q));
1211    }
1212}