seq_core/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:512-525`)
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 `seqstring.rs:123-132`)
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
121pub fn arena_stats() -> ArenaStats {
122 // Read from our tracked bytes instead of Bump's internal state
123 // This ensures consistency with arena_reset() which sets ARENA_BYTES_ALLOCATED to 0
124 let allocated = ARENA_BYTES_ALLOCATED.with(|bytes| *bytes.borrow());
125 ArenaStats {
126 allocated_bytes: allocated,
127 }
128}
129
130/// Arena statistics for debugging/monitoring
131#[derive(Debug, Clone, Copy)]
132pub struct ArenaStats {
133 pub allocated_bytes: usize,
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139
140 #[test]
141 fn test_arena_reset() {
142 arena_reset(); // Start fresh
143
144 // Allocate some strings via with_arena
145 with_arena(|arena| {
146 let _s1 = arena.alloc_str("Hello");
147 let _s2 = arena.alloc_str("World");
148 });
149
150 let stats_before = arena_stats();
151 assert!(stats_before.allocated_bytes > 0);
152
153 // Reset arena
154 arena_reset();
155
156 let stats_after = arena_stats();
157 // After reset, allocated bytes should be much less than before
158 // (Bump might keep some internal overhead, so we don't assert == 0)
159 assert!(
160 stats_after.allocated_bytes < stats_before.allocated_bytes,
161 "Arena should have less memory after reset (before: {}, after: {})",
162 stats_before.allocated_bytes,
163 stats_after.allocated_bytes
164 );
165 }
166
167 #[test]
168 fn test_with_arena() {
169 arena_reset(); // Start fresh
170
171 // We can't return the &str from the closure (lifetime issue)
172 // Instead, test that allocation works and stats update
173 let len = with_arena(|arena| {
174 let s = arena.alloc_str("Test string");
175 assert_eq!(s, "Test string");
176 s.len()
177 });
178
179 assert_eq!(len, 11);
180
181 let stats = arena_stats();
182 assert!(stats.allocated_bytes > 0);
183 }
184
185 #[test]
186 fn test_auto_reset_threshold() {
187 arena_reset(); // Start fresh
188
189 // Allocate just under threshold
190 let big_str = "x".repeat(ARENA_RESET_THRESHOLD / 2);
191 with_arena(|arena| {
192 let _s = arena.alloc_str(&big_str);
193 });
194
195 let stats1 = arena_stats();
196 let initial_bytes = stats1.allocated_bytes;
197 assert!(initial_bytes > 0);
198
199 // Allocate more to exceed threshold - this should trigger auto-reset
200 let big_str2 = "y".repeat(ARENA_RESET_THRESHOLD / 2 + 1000);
201 with_arena(|arena| {
202 let _s = arena.alloc_str(&big_str2);
203 });
204
205 // Arena should have been reset and re-allocated with just the second string
206 let stats2 = arena_stats();
207 // After reset, we should only have the second allocation
208 // (which is slightly larger than ARENA_RESET_THRESHOLD / 2)
209 assert!(
210 stats2.allocated_bytes < initial_bytes + (ARENA_RESET_THRESHOLD / 2 + 2000),
211 "Arena should have reset: stats2={}, initial={}, threshold={}",
212 stats2.allocated_bytes,
213 initial_bytes,
214 ARENA_RESET_THRESHOLD
215 );
216 }
217}