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            // Retired (poisoned) regions are immortal roots: their objects may
680            // still be referenced and may hold `GcPtr`s into the heap.
681            crate::region::trace_retired_regions(&mut visitor);
682            cljrs_logging::feat_debug!(
683                "gc",
684                "starting drain with {} grey objects",
685                visitor.grey.len()
686            );
687            visitor.drain();
688            let mark_elapsed = mark_start.elapsed();
689
690            let sweep_start = std::time::Instant::now();
691            let mut inner = self.inner.lock().unwrap();
692            let mut live: Vec<*mut GcBoxHeader> = Vec::with_capacity(inner.count);
693            let mut dead: Vec<*mut GcBoxHeader> = Vec::new();
694            // Bytes of objects with lives==0 that will be freed now.
695            let mut freed_bytes: usize = 0;
696            let mut current = inner.head;
697            while !current.is_null() {
698                let header = unsafe { &*current };
699                let next = header.next.get();
700                let lives = header.lives.get();
701                let obj_size = header.size;
702                if lives >= GC_INITIAL_LIVES {
703                    // Marked reachable this cycle — reset grace counter.
704                    header.lives.set(GC_INITIAL_LIVES - 1);
705                    live.push(current);
706                } else if lives > 0 {
707                    // In grace period (unreachable but not yet freed).
708                    header.lives.set(lives - 1);
709                    live.push(current);
710                } else {
711                    // Grace period exhausted — collect now.
712                    freed_bytes += obj_size;
713                    dead.push(current);
714                }
715                current = next;
716            }
717            let freed_count = dead.len();
718            for ptr in dead {
719                let header = unsafe { &*ptr };
720                unsafe { (header.drop_fn)(ptr) };
721                inner.count -= 1;
722                inner.total_freed += 1;
723            }
724            inner.head = std::ptr::null_mut();
725            for ptr in live {
726                let header = unsafe { &*ptr };
727                header.next.set(inner.head);
728                inner.head = ptr;
729            }
730            // Decrement memory_in_use by the bytes actually freed.  All heap
731            // objects (live + grace-period) remain counted; only physically
732            // freed objects are subtracted.  This keeps memory pressure
733            // accurate so GC fires again when the heap genuinely grows.
734            self.memory_in_use.fetch_sub(freed_bytes, Ordering::Relaxed);
735            let sweep_elapsed = sweep_start.elapsed();
736            crate::stats::GC_STATS.record_gc_pause(
737                mark_elapsed + sweep_elapsed,
738                freed_count as u64,
739                freed_bytes as u64,
740            );
741            let post_memory = self.memory_in_use.load(Ordering::Relaxed);
742            cljrs_logging::feat_debug!(
743                "gc",
744                "collection complete: freed {} (~{} bytes), {} remaining (~{} bytes), mark={:.2?} sweep={:.2?}",
745                freed_count,
746                freed_bytes,
747                inner.count,
748                post_memory,
749                mark_elapsed,
750                sweep_elapsed
751            );
752            if freed_count == 0 {
753                // Zero-yield collection: exponential-backoff suppression.
754                // Each consecutive zero-yield cycle doubles the headroom before
755                // the next GC attempt (capped at soft_limit/4).  This prevents a
756                // GC storm during deep recursion where all objects are live —
757                // without backoff, GC fires every soft_limit/10 bytes, tracing
758                // the entire live set O(N) times to no benefit.
759                // The headroom resets to soft_limit/10 when GC frees something.
760                // Cap at soft_limit/4 (not soft_limit) so that GC still fires
761                // frequently enough to catch short-lived test allocations after
762                // a long namespace-loading phase of zero-yield cycles.
763                let soft_limit = self
764                    .config
765                    .lock()
766                    .unwrap()
767                    .as_ref()
768                    .map(|c| c.soft_limit())
769                    .unwrap_or(64 * 1024 * 1024);
770                let base_headroom = (soft_limit / 10).max(1);
771                let max_headroom = (soft_limit / 4).max(base_headroom);
772                let prev_headroom = self.zero_yield_headroom.load(Ordering::Relaxed);
773                let headroom = if prev_headroom == 0 {
774                    base_headroom
775                } else {
776                    prev_headroom.saturating_mul(2).min(max_headroom)
777                };
778                self.zero_yield_headroom.store(headroom, Ordering::Relaxed);
779                self.suppressed_threshold
780                    .store(post_memory + headroom, Ordering::Relaxed);
781                self.gc_suppressed.store(true, Ordering::Relaxed);
782            } else {
783                // GC freed something: reset exponential backoff.
784                self.zero_yield_headroom.store(0, Ordering::Relaxed);
785                self.gc_suppressed.store(false, Ordering::Relaxed);
786            }
787        }
788
789        pub fn count(&self) -> usize {
790            self.inner.lock().unwrap().count
791        }
792        pub fn total_allocated(&self) -> usize {
793            self.inner.lock().unwrap().total_allocated
794        }
795        pub fn total_freed(&self) -> usize {
796            self.inner.lock().unwrap().total_freed
797        }
798
799        pub fn collect_auto(&self) -> bool {
800            cljrs_logging::feat_debug!("gc", "automatic collection requested");
801            let Some(_stw_guard) = crate::cancellation::begin_stw() else {
802                cljrs_logging::feat_debug!("gc", "automatic collection skipped");
803                return false;
804            };
805            self.collect(|visitor| self.trace_registered_roots(visitor));
806            true
807        }
808    }
809
810    thread_local! {
811        static ISOLATE_HEAP: GcHeap = const { GcHeap::new() };
812    }
813
814    /// Zero-sized proxy that dispatches all heap operations to the calling
815    /// thread's [`GcHeap`] via the `ISOLATE_HEAP` thread-local.
816    ///
817    /// This means every isolate (OS thread) owns an independent heap; GC runs
818    /// fully in parallel on different threads with no cross-isolate coordination.
819    pub struct HeapProxy;
820
821    impl HeapProxy {
822        pub fn alloc<T: Trace + 'static>(&self, value: T) -> GcPtr<T> {
823            ISOLATE_HEAP.with(|h| h.alloc(value))
824        }
825
826        pub fn set_config(&self, config: Arc<GcConfig>) {
827            ISOLATE_HEAP.with(|h| h.set_config(config));
828        }
829
830        pub fn set_config_from_env(&self) {
831            ISOLATE_HEAP.with(|h| h.set_config_from_env());
832        }
833
834        pub fn register_root_tracer(&self, tracer: impl Fn(&mut MarkVisitor) + 'static) {
835            ISOLATE_HEAP.with(|h| h.register_root_tracer(tracer));
836        }
837
838        pub fn trace_registered_roots(&self, visitor: &mut MarkVisitor) {
839            ISOLATE_HEAP.with(|h| h.trace_registered_roots(visitor));
840        }
841
842        pub fn memory_in_use(&self) -> usize {
843            ISOLATE_HEAP.with(|h| h.memory_in_use())
844        }
845
846        pub fn count(&self) -> usize {
847            ISOLATE_HEAP.with(|h| h.count())
848        }
849
850        pub fn total_allocated(&self) -> usize {
851            ISOLATE_HEAP.with(|h| h.total_allocated())
852        }
853
854        pub fn total_freed(&self) -> usize {
855            ISOLATE_HEAP.with(|h| h.total_freed())
856        }
857
858        pub fn collect<F: FnOnce(&mut MarkVisitor)>(&self, trace_roots: F) {
859            ISOLATE_HEAP.with(|h| h.collect(trace_roots));
860        }
861
862        pub fn collect_auto(&self) -> bool {
863            ISOLATE_HEAP.with(|h| h.collect_auto())
864        }
865
866        #[cfg(test)]
867        pub fn set_memory_in_use(&self, bytes: usize) {
868            ISOLATE_HEAP.with(|h| h.set_memory_in_use(bytes));
869        }
870    }
871
872    // SAFETY: HeapProxy is zero-sized; all state lives in a thread-local GcHeap.
873    // The Send + Sync impls are needed so `pub static HEAP: HeapProxy` is valid.
874    unsafe impl Sync for HeapProxy {}
875
876    pub static HEAP: HeapProxy = HeapProxy;
877
878    thread_local! {
879        pub(crate) static ALLOC_ROOTS: RefCell<Vec<*mut GcBoxHeader>> = const { RefCell::new(Vec::new()) };
880    }
881
882    pub struct AllocRootGuard {
883        saved_len: usize,
884    }
885
886    impl Drop for AllocRootGuard {
887        fn drop(&mut self) {
888            ALLOC_ROOTS.with(|roots| roots.borrow_mut().truncate(self.saved_len));
889        }
890    }
891
892    pub fn push_alloc_frame() -> AllocRootGuard {
893        let saved_len = ALLOC_ROOTS.with(|roots| roots.borrow().len());
894        AllocRootGuard { saved_len }
895    }
896
897    fn register_alloc(header: *mut GcBoxHeader) {
898        ALLOC_ROOTS.with(|roots| roots.borrow_mut().push(header));
899    }
900
901    pub fn trace_thread_alloc_roots(visitor: &mut MarkVisitor) {
902        ALLOC_ROOTS.with(|roots| {
903            let roots = roots.borrow();
904            for &header in roots.iter() {
905                unsafe { visitor.mark_header(header) };
906            }
907        });
908    }
909}
910
911// =============================================================================
912// no-gc stubs
913// =============================================================================
914
915#[cfg(feature = "no-gc")]
916mod nogc_stubs {
917    use crate::MarkVisitor;
918    use std::sync::Arc;
919
920    #[derive(Debug, Clone)]
921    pub struct GcConfig;
922    impl GcConfig {
923        pub fn new() -> Self {
924            Self
925        }
926        pub fn with_hard_limit(_: usize) -> Self {
927            Self
928        }
929        pub fn with_limits(_: usize, _: usize) -> Self {
930            Self
931        }
932    }
933    impl Default for GcConfig {
934        fn default() -> Self {
935            Self::new()
936        }
937    }
938
939    pub struct GcHeap;
940    impl Default for GcHeap {
941        fn default() -> Self {
942            Self::new()
943        }
944    }
945    impl GcHeap {
946        pub const fn new() -> Self {
947            Self
948        }
949        pub fn set_config(&self, _: Arc<GcConfig>) {}
950        pub fn register_root_tracer(&self, _: impl Fn(&mut MarkVisitor) + 'static) {}
951        pub fn trace_registered_roots(&self, _: &mut MarkVisitor) {}
952        pub fn memory_in_use(&self) -> usize {
953            0
954        }
955        pub fn count(&self) -> usize {
956            0
957        }
958        pub fn total_allocated(&self) -> usize {
959            0
960        }
961        pub fn total_freed(&self) -> usize {
962            0
963        }
964        pub fn collect<F: FnOnce(&mut MarkVisitor)>(&self, _: F) {}
965        pub fn collect_auto(&self) -> bool {
966            false
967        }
968    }
969    unsafe impl Sync for GcHeap {}
970    pub static HEAP: GcHeap = GcHeap::new();
971
972    pub struct MutatorGuard;
973    impl Drop for MutatorGuard {
974        fn drop(&mut self) {}
975    }
976    pub struct StwGuard;
977    impl Drop for StwGuard {
978        fn drop(&mut self) {}
979    }
980    pub struct GcParked;
981    pub struct CancellableGuard;
982
983    pub struct GcCancellationStub;
984    impl GcCancellationStub {
985        pub const fn new() -> Self {
986            Self
987        }
988        pub fn in_progress(&self) -> bool {
989            false
990        }
991    }
992    pub static CONFIG_CANCELLATION: GcCancellationStub = GcCancellationStub::new();
993
994    pub fn safepoint() {}
995    pub fn gc_requested() -> bool {
996        false
997    }
998    pub fn take_gc_request() -> bool {
999        false
1000    }
1001    pub fn begin_stw() -> Option<StwGuard> {
1002        None
1003    }
1004    pub fn register_mutator() -> MutatorGuard {
1005        MutatorGuard
1006    }
1007    pub fn registered_threads() -> usize {
1008        0
1009    }
1010    pub fn request_gc() {}
1011    pub fn check_cancellation() -> Result<(), GcParked> {
1012        Ok(())
1013    }
1014    pub fn park_thread() {}
1015    pub fn unpark_thread() {}
1016    pub fn wait_for_threads_to_park() {}
1017
1018    pub struct AllocRootGuard;
1019    impl Drop for AllocRootGuard {
1020        fn drop(&mut self) {}
1021    }
1022    pub fn push_alloc_frame() -> AllocRootGuard {
1023        AllocRootGuard
1024    }
1025}
1026
1027// =============================================================================
1028// Tests
1029// =============================================================================
1030
1031#[cfg(all(test, not(feature = "no-gc")))]
1032mod tests {
1033    use super::*;
1034    use std::sync::{Arc, Mutex};
1035
1036    #[derive(Debug)]
1037    #[allow(dead_code)]
1038    struct Tracked {
1039        value: i32,
1040        dropped: Arc<Mutex<bool>>,
1041    }
1042    impl Drop for Tracked {
1043        fn drop(&mut self) {
1044            *self.dropped.lock().unwrap() = true;
1045        }
1046    }
1047    impl Trace for Tracked {
1048        fn trace(&self, _: &mut MarkVisitor) {}
1049    }
1050
1051    #[derive(Debug)]
1052    #[allow(dead_code)]
1053    struct Parent {
1054        child: GcPtr<Tracked>,
1055    }
1056    impl Trace for Parent {
1057        fn trace(&self, visitor: &mut MarkVisitor) {
1058            visitor.visit(&self.child);
1059        }
1060    }
1061
1062    fn fresh_heap() -> gc_full::GcHeap {
1063        let heap = gc_full::GcHeap::new();
1064        heap.set_config(Arc::new(GcConfig::with_limits(10000, 50000)));
1065        heap
1066    }
1067
1068    #[test]
1069    fn alloc_and_get() {
1070        let heap = fresh_heap();
1071        let p = heap.alloc(42i64);
1072        assert_eq!(*p.get(), 42);
1073        assert_eq!(heap.count(), 1);
1074    }
1075
1076    #[test]
1077    fn clone_is_same_ptr() {
1078        let heap = fresh_heap();
1079        let p = heap.alloc(99i64);
1080        let q = p.clone();
1081        assert!(GcPtr::ptr_eq(&p, &q));
1082    }
1083
1084    #[test]
1085    fn collect_keeps_reachable() {
1086        let heap = fresh_heap();
1087        let dropped = Arc::new(Mutex::new(false));
1088        let p = heap.alloc(Tracked {
1089            value: 2,
1090            dropped: dropped.clone(),
1091        });
1092        heap.collect(|vis| vis.visit(&p));
1093        assert_eq!(heap.count(), 1);
1094        assert!(!*dropped.lock().unwrap());
1095    }
1096
1097    #[test]
1098    fn b1_two_isolates_independent_heaps() {
1099        use std::sync::{Arc, Barrier};
1100        // Each thread has its own ISOLATE_HEAP; allocations on one do not appear
1101        // in the other.
1102        let barrier = Arc::new(Barrier::new(2));
1103        let b1 = barrier.clone();
1104        let h1 = std::thread::Builder::new()
1105            .name("isolate-1".into())
1106            .spawn(move || {
1107                let _mutator = crate::register_mutator();
1108                // Allocate 100 objects on this isolate's heap
1109                let _ptrs: Vec<_> = (0_i64..100)
1110                    .map(|i| crate::gc_full::HEAP.alloc(i))
1111                    .collect();
1112                b1.wait(); // both threads are now at peak allocation
1113                // This isolate has exactly 100 live objects
1114                assert_eq!(
1115                    crate::gc_full::HEAP.count(),
1116                    100,
1117                    "isolate-1 heap count should be 100"
1118                );
1119            })
1120            .unwrap();
1121
1122        let b2 = barrier.clone();
1123        let h2 = std::thread::Builder::new()
1124            .name("isolate-2".into())
1125            .spawn(move || {
1126                let _mutator = crate::register_mutator();
1127                // Allocate 200 objects on this isolate's heap
1128                let _ptrs: Vec<_> = (0_i64..200)
1129                    .map(|i| crate::gc_full::HEAP.alloc(i))
1130                    .collect();
1131                b2.wait();
1132                // This isolate has exactly 200 live objects, unaffected by isolate-1
1133                assert_eq!(
1134                    crate::gc_full::HEAP.count(),
1135                    200,
1136                    "isolate-2 heap count should be 200"
1137                );
1138            })
1139            .unwrap();
1140
1141        h1.join().expect("isolate-1 panicked");
1142        h2.join().expect("isolate-2 panicked");
1143    }
1144
1145    #[test]
1146    fn b1_two_isolates_gc_independently() {
1147        // Two threads run allocation-heavy loops and GC their own heaps independently.
1148        let h1 = std::thread::Builder::new()
1149            .name("gc-isolate-1".into())
1150            .spawn(|| {
1151                let _mutator = crate::register_mutator();
1152                let heap = &crate::gc_full::HEAP;
1153                heap.set_config(Arc::new(GcConfig::with_limits(16_384, 65_536)));
1154                // Allocate in batches and collect; each collection touches only this heap
1155                for _ in 0..5 {
1156                    let _ptrs: Vec<_> = (0_i64..50).map(|i| heap.alloc(i)).collect();
1157                    // drive a manual collect with no roots so objects are freed
1158                    heap.collect(|_| {});
1159                    heap.collect(|_| {}); // second pass clears grace-period objects
1160                }
1161                // After all collections the heap should be empty (or close to it).
1162                // We don't assert an exact count because alloc_frame roots may keep
1163                // some alive; just assert we can collect without panicking.
1164            })
1165            .unwrap();
1166
1167        let h2 = std::thread::Builder::new()
1168            .name("gc-isolate-2".into())
1169            .spawn(|| {
1170                let _mutator = crate::register_mutator();
1171                let heap = &crate::gc_full::HEAP;
1172                heap.set_config(Arc::new(GcConfig::with_limits(16_384, 65_536)));
1173                for _ in 0..5 {
1174                    let _ptrs: Vec<_> = (0_i64..50).map(|i| heap.alloc(i)).collect();
1175                    heap.collect(|_| {});
1176                    heap.collect(|_| {});
1177                }
1178            })
1179            .unwrap();
1180
1181        h1.join().expect("gc-isolate-1 panicked");
1182        h2.join().expect("gc-isolate-2 panicked");
1183    }
1184}
1185
1186#[cfg(all(test, feature = "no-gc"))]
1187mod nogc_tests {
1188    use super::*;
1189    use alloc_ctx::{ScratchGuard, StaticCtxGuard};
1190
1191    #[test]
1192    fn alloc_in_static_context() {
1193        let _g = StaticCtxGuard::new();
1194        let p = GcPtr::new(42i64);
1195        assert_eq!(*p.get(), 42);
1196    }
1197
1198    #[test]
1199    fn alloc_in_scratch_region() {
1200        let mut scratch = ScratchGuard::new();
1201        let p = GcPtr::new(99i64);
1202        assert_eq!(*p.get(), 99);
1203        scratch.pop_for_return();
1204        assert_eq!(*p.get(), 99);
1205        // scratch drops here, resets the region
1206    }
1207
1208    #[test]
1209    fn ptr_eq() {
1210        let _g = StaticCtxGuard::new();
1211        let p = GcPtr::new(1i64);
1212        let q = p.clone();
1213        assert!(GcPtr::ptr_eq(&p, &q));
1214    }
1215}