seq_runtime/
arena.rs

1//! Arena Allocator - Thread-local bump allocation for Values
2//!
3//! Uses bumpalo for fast bump allocation of Strings and Variants.
4//! Each OS thread has an arena that's used by strands executing on it.
5//!
6//! # Design
7//! - Thread-local Bump allocator
8//! - Fast allocation (~5ns vs ~100ns for malloc)
9//! - Periodic reset to prevent unbounded growth
10//! - Manual reset when strand completes
11//!
12//! # ⚠️ IMPORTANT: Thread-Local, Not Strand-Local
13//!
14//! The arena is **thread-local**, not strand-local. This has implications
15//! if May's scheduler migrates a strand to a different thread:
16//!
17//! **What happens:**
18//! - Strand starts on Thread A, allocates strings from Arena A
19//! - May migrates strand to Thread B (rare, but possible)
20//! - Strand now allocates from Arena B
21//! - When strand exits, Arena B is reset (not Arena A)
22//! - Arena A still contains the strings from earlier allocation
23//!
24//! **Why this is safe:**
25//! - Arena reset only happens on strand exit (see `scheduler.rs:203`)
26//! - A migrated strand continues executing, doesn't trigger reset of Arena A
27//! - Arena A will be reset when the *next* strand on Thread A exits
28//! - Channel sends clone to global allocator (see `cemstring.rs:73-76`)
29//!
30//! **Performance impact:**
31//! - Minimal in practice - May rarely migrates strands
32//! - If migration occurs, some memory stays in old arena until next reset
33//! - Auto-reset at 10MB threshold prevents unbounded growth
34//!
35//! **Alternative considered:**
36//! Strand-local arenas would require passing arena pointer with every
37//! strand migration. This adds complexity and overhead for a rare case.
38//! Thread-local is simpler and faster for the common case.
39//!
40//! See: `docs/ARENA_ALLOCATION_DESIGN.md` for full design rationale.
41
42use crate::memory_stats::{get_or_register_slot, update_arena_stats};
43use bumpalo::Bump;
44use std::cell::RefCell;
45
46/// Configuration for the arena
47const ARENA_RESET_THRESHOLD: usize = 10 * 1024 * 1024; // 10MB - reset when we exceed this
48
49// Thread-local arena for value allocations
50thread_local! {
51    static ARENA: RefCell<Bump> = {
52        // Register thread with memory stats registry once during initialization
53        get_or_register_slot();
54        RefCell::new(Bump::new())
55    };
56    static ARENA_BYTES_ALLOCATED: RefCell<usize> = const { RefCell::new(0) };
57}
58
59/// Execute a function with access to the thread-local arena
60///
61/// This is used by CemString to allocate strings from the arena.
62///
63/// # Performance
64/// ~5ns vs ~100ns for global allocator (20x faster)
65///
66/// # Example
67/// ```ignore
68/// let arena_str = with_arena(|arena| arena.alloc_str("Hello"));
69/// ```
70pub fn with_arena<F, R>(f: F) -> R
71where
72    F: FnOnce(&Bump) -> R,
73{
74    // Thread registration happens once during ARENA initialization,
75    // not on every arena access (keeping the fast path fast).
76    ARENA.with(|arena| {
77        let bump = arena.borrow();
78        let result = f(&bump);
79
80        // Track allocation size
81        let allocated = bump.allocated_bytes();
82        drop(bump); // Drop borrow before accessing ARENA_BYTES_ALLOCATED
83
84        ARENA_BYTES_ALLOCATED.with(|bytes| {
85            *bytes.borrow_mut() = allocated;
86        });
87
88        // Update cross-thread memory stats registry
89        update_arena_stats(allocated);
90
91        // Auto-reset if threshold exceeded
92        if should_reset() {
93            arena_reset();
94        }
95
96        result
97    })
98}
99
100/// Reset the thread-local arena
101///
102/// Call this when a strand completes to free memory.
103/// Also called automatically when arena exceeds threshold.
104pub fn arena_reset() {
105    ARENA.with(|arena| {
106        arena.borrow_mut().reset();
107    });
108    ARENA_BYTES_ALLOCATED.with(|bytes| {
109        *bytes.borrow_mut() = 0;
110    });
111    // Update cross-thread memory stats registry
112    update_arena_stats(0);
113}
114
115/// Check if arena should be reset (exceeded threshold)
116fn should_reset() -> bool {
117    ARENA_BYTES_ALLOCATED.with(|bytes| *bytes.borrow() > ARENA_RESET_THRESHOLD)
118}
119
120/// Get current arena statistics
121#[allow(dead_code)]
122pub fn arena_stats() -> ArenaStats {
123    // Read from our tracked bytes instead of Bump's internal state
124    // This ensures consistency with arena_reset() which sets ARENA_BYTES_ALLOCATED to 0
125    let allocated = ARENA_BYTES_ALLOCATED.with(|bytes| *bytes.borrow());
126    ArenaStats {
127        allocated_bytes: allocated,
128    }
129}
130
131/// Arena statistics for debugging/monitoring
132#[derive(Debug, Clone, Copy)]
133pub struct ArenaStats {
134    pub allocated_bytes: usize,
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn test_arena_reset() {
143        arena_reset(); // Start fresh
144
145        // Allocate some strings via with_arena
146        with_arena(|arena| {
147            let _s1 = arena.alloc_str("Hello");
148            let _s2 = arena.alloc_str("World");
149        });
150
151        let stats_before = arena_stats();
152        assert!(stats_before.allocated_bytes > 0);
153
154        // Reset arena
155        arena_reset();
156
157        let stats_after = arena_stats();
158        // After reset, allocated bytes should be much less than before
159        // (Bump might keep some internal overhead, so we don't assert == 0)
160        assert!(
161            stats_after.allocated_bytes < stats_before.allocated_bytes,
162            "Arena should have less memory after reset (before: {}, after: {})",
163            stats_before.allocated_bytes,
164            stats_after.allocated_bytes
165        );
166    }
167
168    #[test]
169    fn test_with_arena() {
170        arena_reset(); // Start fresh
171
172        // We can't return the &str from the closure (lifetime issue)
173        // Instead, test that allocation works and stats update
174        let len = with_arena(|arena| {
175            let s = arena.alloc_str("Test string");
176            assert_eq!(s, "Test string");
177            s.len()
178        });
179
180        assert_eq!(len, 11);
181
182        let stats = arena_stats();
183        assert!(stats.allocated_bytes > 0);
184    }
185
186    #[test]
187    fn test_auto_reset_threshold() {
188        arena_reset(); // Start fresh
189
190        // Allocate just under threshold
191        let big_str = "x".repeat(ARENA_RESET_THRESHOLD / 2);
192        with_arena(|arena| {
193            let _s = arena.alloc_str(&big_str);
194        });
195
196        let stats1 = arena_stats();
197        let initial_bytes = stats1.allocated_bytes;
198        assert!(initial_bytes > 0);
199
200        // Allocate more to exceed threshold - this should trigger auto-reset
201        let big_str2 = "y".repeat(ARENA_RESET_THRESHOLD / 2 + 1000);
202        with_arena(|arena| {
203            let _s = arena.alloc_str(&big_str2);
204        });
205
206        // Arena should have been reset and re-allocated with just the second string
207        let stats2 = arena_stats();
208        // After reset, we should only have the second allocation
209        // (which is slightly larger than ARENA_RESET_THRESHOLD / 2)
210        assert!(
211            stats2.allocated_bytes < initial_bytes + (ARENA_RESET_THRESHOLD / 2 + 2000),
212            "Arena should have reset: stats2={}, initial={}, threshold={}",
213            stats2.allocated_bytes,
214            initial_bytes,
215            ARENA_RESET_THRESHOLD
216        );
217    }
218}