zu_vector/arena.rs
1//! Per-morsel bump arena (perf/02 section 2).
2//!
3//! Every vector buffer, bitmap, and selection in a morsel comes from one
4//! arena. Allocation is a pointer bump into 256 KiB blocks; reset keeps
5//! the blocks and zeroes the offsets, so a warm morsel allocates nothing
6//! from the heap. Blocks are handed out zeroed once at birth and reused
7//! dirty after that, which keeps every byte a buffer can see initialized.
8//!
9//! A `RawBuf` does not borrow the arena in the type system; the executor
10//! contract is that vectors never outlive their morsel unless copied into
11//! a sink. Debug builds tag each buffer with the arena generation at
12//! allocation time and assert it on every access, so a vector read after
13//! reset fails loudly instead of reading recycled bytes.
14
15use std::alloc::{Layout, alloc_zeroed, dealloc, handle_alloc_error};
16use std::ptr::NonNull;
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU64, Ordering};
19
20/// Largest arena block. Matches the storage block so a decoded chunk and
21/// its working vectors have the same granularity.
22pub const BLOCK_BYTES: usize = 256 * 1024;
23
24/// The first block an arena takes, and the step it grows by after that:
25/// each new block is twice the last until it reaches [`BLOCK_BYTES`].
26///
27/// An arena is born per run, and most runs are small. A point read
28/// wants a few vectors of working memory and used to pay a 256 KiB
29/// block for them, which on a warm read is the largest single thing the
30/// whole query asks the allocator for and is large enough that the
31/// allocator hands back fresh pages the query then faults in one by
32/// one. Starting small and doubling costs a big query one extra block
33/// allocation on the way up, which it does not notice, and saves a small
34/// query the other 248 KiB, which it does.
35const FIRST_BLOCK_BYTES: usize = 8 * 1024;
36
37/// Every allocation is aligned to at least a cache line, which is also
38/// the widest alignment any physical type needs.
39const BLOCK_ALIGN: usize = 64;
40
41struct Block {
42 ptr: NonNull<u8>,
43 bytes: usize,
44}
45
46// A block is a plain byte allocation with no thread affinity.
47unsafe impl Send for Block {}
48
49impl Block {
50 fn new(bytes: usize) -> Self {
51 let layout = Layout::from_size_align(bytes, BLOCK_ALIGN).expect("block layout");
52 // Zeroed at birth so recycled reads see initialized memory, never
53 // uninit. Reset does not re-zero; stale bytes are fine, uninit is
54 // undefined behavior.
55 let raw = unsafe { alloc_zeroed(layout) };
56 let Some(ptr) = NonNull::new(raw) else {
57 handle_alloc_error(layout)
58 };
59 Self { ptr, bytes }
60 }
61}
62
63impl Drop for Block {
64 fn drop(&mut self) {
65 let layout = unsafe { Layout::from_size_align_unchecked(self.bytes, BLOCK_ALIGN) };
66 unsafe { dealloc(self.ptr.as_ptr(), layout) };
67 }
68}
69
70/// Bump allocator for one morsel's working memory.
71pub struct MorselArena {
72 blocks: Vec<Block>,
73 cur: usize,
74 off: usize,
75 generation: Arc<AtomicU64>,
76}
77
78impl Default for MorselArena {
79 fn default() -> Self {
80 Self::new()
81 }
82}
83
84impl MorselArena {
85 pub fn new() -> Self {
86 Self {
87 blocks: Vec::new(),
88 cur: 0,
89 off: 0,
90 generation: Arc::new(AtomicU64::new(0)),
91 }
92 }
93
94 /// Bump-allocate `bytes` with the given alignment (a power of two,
95 /// at most 64: blocks themselves are 64-byte aligned so any larger
96 /// request could not be honored from a bump offset).
97 pub fn alloc(&mut self, bytes: usize, align: usize) -> RawBuf {
98 assert!(
99 align.is_power_of_two() && align <= BLOCK_ALIGN,
100 "align {align}"
101 );
102 if bytes == 0 {
103 return RawBuf::empty();
104 }
105 // Oversize requests get a dedicated block so the bump path never
106 // has to think about them again. It stays owned by the arena and
107 // is recycled like any other block only in the sense that it is
108 // freed when the arena drops.
109 if bytes > BLOCK_BYTES {
110 let block = Block::new(bytes);
111 let ptr = block.ptr;
112 // Keep the current bump block last so cur/off stay valid.
113 let at = self.cur.min(self.blocks.len());
114 self.blocks.insert(at, block);
115 self.cur += 1;
116 return self.tag(RawBuf {
117 ptr,
118 len: bytes,
119 #[cfg(debug_assertions)]
120 tag: None,
121 #[cfg(debug_assertions)]
122 borrowed: false,
123 });
124 }
125 let cap = self.blocks.get(self.cur).map_or(0, |b| b.bytes);
126 let off = self.off.next_multiple_of(align);
127 if self.cur >= self.blocks.len() || off + bytes > cap {
128 if self.cur < self.blocks.len() && off + bytes > cap {
129 self.cur += 1;
130 }
131 if self.cur >= self.blocks.len() {
132 let want = self.next_block_bytes().max(bytes);
133 self.blocks.push(Block::new(want));
134 self.cur = self.blocks.len() - 1;
135 }
136 self.off = 0;
137 return self.alloc(bytes, align);
138 }
139 self.off = off + bytes;
140 let ptr = unsafe { NonNull::new_unchecked(self.blocks[self.cur].ptr.as_ptr().add(off)) };
141 self.tag(RawBuf {
142 ptr,
143 len: bytes,
144 #[cfg(debug_assertions)]
145 tag: None,
146 #[cfg(debug_assertions)]
147 borrowed: false,
148 })
149 }
150
151 /// The size of the next block to push: twice the last one, held
152 /// between the first size and the largest. An oversize block can
153 /// make the last one bigger than [`BLOCK_BYTES`], and the clamp
154 /// covers that too.
155 fn next_block_bytes(&self) -> usize {
156 let last = self.blocks.last().map_or(0, |b| b.bytes);
157 (last * 2).clamp(FIRST_BLOCK_BYTES, BLOCK_BYTES)
158 }
159
160 /// Allocate a typed buffer for `count` values.
161 pub fn alloc_of<T: Pod>(&mut self, count: usize) -> RawBuf {
162 self.alloc(count * size_of::<T>(), align_of::<T>())
163 }
164
165 /// O(1) reset: keep the blocks, rewind the offsets. Called once per
166 /// morsel. Buffers handed out before the reset are dead; debug builds
167 /// catch any survivor on its next access.
168 pub fn reset(&mut self) {
169 self.cur = 0;
170 self.off = 0;
171 self.generation.fetch_add(1, Ordering::Release);
172 }
173
174 /// Bytes currently held, for budget accounting.
175 pub fn capacity(&self) -> usize {
176 self.blocks.iter().map(|b| b.bytes).sum()
177 }
178
179 /// An arena off this thread's pool, or a new one when the pool is
180 /// empty, handed back to the pool when it is dropped.
181 ///
182 /// An arena is born per run and dies with it, so a warm query that
183 /// allocates nothing per morsel still pays three trips to the heap
184 /// before its first row: the block list, the generation counter and
185 /// the first block, which at eight kilobytes is most of what a warm
186 /// point read asks the allocator for. None of that is about the run.
187 /// A thread runs one worker at a time and the pool threads outlive
188 /// any one query, so the arena the last query left is the arena this
189 /// one wants.
190 ///
191 /// Reuse is safe for the same reason a reset is: taking one resets
192 /// it, which moves the generation, so a buffer that outlived the
193 /// query it was cut from fails its tag in debug rather than reading
194 /// the next query's bytes.
195 pub fn pooled() -> PooledArena {
196 let arena = POOL.with(|p| p.borrow_mut().pop()).map(|mut a| {
197 a.reset();
198 a
199 });
200 PooledArena {
201 arena: arena.or_else(|| Some(MorselArena::new())),
202 }
203 }
204
205 /// Drops every block but the first, which is what an arena that grew
206 /// for one wide query hands back so the next small one does not keep
207 /// its memory.
208 fn shrink(&mut self) {
209 self.blocks.truncate(1);
210 self.cur = 0;
211 self.off = 0;
212 }
213}
214
215/// Arenas one thread keeps between runs. One is the working number,
216/// since a thread runs one worker at a time; the rest of the room is for
217/// a run that nests, which costs a pointer each and saves that run the
218/// same three allocations.
219const POOL_ARENAS: usize = 4;
220
221/// The most an arena may still hold when it comes back and be kept
222/// whole. A query that grew past this grew for itself, and holding its
223/// blocks on the thread would charge every later query for it, so it is
224/// cut back to its first block and kept for that.
225const POOL_KEEP_BYTES: usize = BLOCK_BYTES;
226
227thread_local! {
228 static POOL: std::cell::RefCell<Vec<MorselArena>> =
229 const { std::cell::RefCell::new(Vec::new()) };
230}
231
232/// An arena on loan from this thread's pool.
233///
234/// It is a [`MorselArena`] in every way that matters, through `Deref`,
235/// and the only thing it adds is where it goes when it is dropped.
236pub struct PooledArena {
237 /// Always `Some` until the drop takes it.
238 arena: Option<MorselArena>,
239}
240
241impl std::ops::Deref for PooledArena {
242 type Target = MorselArena;
243
244 fn deref(&self) -> &MorselArena {
245 self.arena.as_ref().expect("arena is taken only on drop")
246 }
247}
248
249impl std::ops::DerefMut for PooledArena {
250 fn deref_mut(&mut self) -> &mut MorselArena {
251 self.arena.as_mut().expect("arena is taken only on drop")
252 }
253}
254
255impl Drop for PooledArena {
256 fn drop(&mut self) {
257 let Some(mut arena) = self.arena.take() else {
258 return;
259 };
260 if arena.capacity() > POOL_KEEP_BYTES {
261 arena.shrink();
262 }
263 // A thread on its way out has already torn its locals down, and
264 // an arena that cannot be handed back is simply dropped here.
265 let _ = POOL.try_with(|p| {
266 let mut pool = p.borrow_mut();
267 if pool.len() < POOL_ARENAS {
268 pool.push(arena);
269 }
270 });
271 }
272}
273
274impl MorselArena {
275 #[cfg(debug_assertions)]
276 fn tag(&self, mut buf: RawBuf) -> RawBuf {
277 buf.tag = Some((
278 Arc::clone(&self.generation),
279 self.generation.load(Ordering::Acquire),
280 ));
281 buf
282 }
283
284 #[cfg(not(debug_assertions))]
285 fn tag(&self, buf: RawBuf) -> RawBuf {
286 buf
287 }
288}
289
290/// An untyped byte buffer handed out by the arena. Unique: not Clone, so
291/// mutable access cannot alias. The typed accessors are safe because the
292/// arena zeroes blocks at birth and every `Pod` type tolerates any bit
293/// pattern.
294pub struct RawBuf {
295 ptr: NonNull<u8>,
296 len: usize,
297 #[cfg(debug_assertions)]
298 tag: Option<(Arc<AtomicU64>, u64)>,
299 /// Whether the bytes belong to somebody else, which is the one
300 /// thing that decides whether they may be written. Debug only,
301 /// like the generation tag: it is a rule the type cannot state and
302 /// a mistake worth catching where it is made.
303 #[cfg(debug_assertions)]
304 borrowed: bool,
305}
306
307// The buffer is plain bytes; the arena outliving it is the executor
308// contract, not a thread question.
309unsafe impl Send for RawBuf {}
310unsafe impl Sync for RawBuf {}
311
312impl RawBuf {
313 /// A zero-length buffer not backed by any arena.
314 pub fn empty() -> Self {
315 Self {
316 ptr: NonNull::dangling(),
317 len: 0,
318 #[cfg(debug_assertions)]
319 tag: None,
320 #[cfg(debug_assertions)]
321 borrowed: false,
322 }
323 }
324
325 /// A buffer over memory the arena did not hand out and does not
326 /// own: a column of a registered frame, which is somebody else's
327 /// allocation for as long as it stays registered.
328 ///
329 /// This is what makes a scan of borrowed data a scan rather than a
330 /// copy. A vector built over one of these reads exactly as a vector
331 /// over arena memory reads, because a buffer was never more than a
332 /// pointer and a length; what differs is who frees it, and the
333 /// answer is nobody here. It carries no generation tag, so the
334 /// use-after-reset assert that guards arena buffers does not fire
335 /// on it and cannot: the memory has nothing to do with the morsel.
336 ///
337 /// # Safety
338 ///
339 /// `ptr` must point at `len` initialized bytes, aligned for every
340 /// type the buffer is read as, unwritten and unfreed by anyone for
341 /// as long as this buffer and every vector built over it live. The
342 /// caller keeps them alive; in the engine that is the frame
343 /// registration holding the handle its columns arrived on.
344 pub unsafe fn borrowed(ptr: NonNull<u8>, len: usize) -> Self {
345 Self {
346 ptr,
347 len,
348 #[cfg(debug_assertions)]
349 tag: None,
350 #[cfg(debug_assertions)]
351 borrowed: true,
352 }
353 }
354
355 pub fn len(&self) -> usize {
356 self.len
357 }
358
359 pub fn is_empty(&self) -> bool {
360 self.len == 0
361 }
362
363 #[inline]
364 fn check(&self) {
365 #[cfg(debug_assertions)]
366 if let Some((cell, born)) = &self.tag {
367 assert_eq!(
368 cell.load(Ordering::Acquire),
369 *born,
370 "vector buffer used after its arena was reset"
371 );
372 }
373 }
374
375 /// View the buffer as a typed slice. The element count is the byte
376 /// length over the element width; a partial trailing element is
377 /// unreachable because allocation sizes come from `alloc_of`.
378 #[inline]
379 pub fn as_slice<T: Pod>(&self) -> &[T] {
380 self.check();
381 debug_assert_eq!(self.ptr.as_ptr() as usize % align_of::<T>(), 0);
382 unsafe { std::slice::from_raw_parts(self.ptr.as_ptr().cast(), self.len / size_of::<T>()) }
383 }
384
385 #[inline]
386 pub fn as_mut_slice<T: Pod>(&mut self) -> &mut [T] {
387 self.check();
388 #[cfg(debug_assertions)]
389 assert!(!self.borrowed, "a borrowed buffer was written to");
390 debug_assert_eq!(self.ptr.as_ptr() as usize % align_of::<T>(), 0);
391 unsafe {
392 std::slice::from_raw_parts_mut(self.ptr.as_ptr().cast(), self.len / size_of::<T>())
393 }
394 }
395}
396
397/// Types a `RawBuf` may be viewed as: fixed layout, any bit pattern valid.
398///
399/// # Safety
400/// Implementors must be `repr(C)` or primitive, contain no padding that a
401/// read could observe as uninit (the arena zeroes blocks, so padding reads
402/// see zero), and tolerate every bit pattern.
403pub unsafe trait Pod: Copy {}
404
405unsafe impl Pod for u8 {}
406unsafe impl Pod for u16 {}
407unsafe impl Pod for u32 {}
408unsafe impl Pod for u64 {}
409unsafe impl Pod for i64 {}
410unsafe impl Pod for f64 {}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415
416 #[test]
417 fn bump_and_reuse() {
418 let mut arena = MorselArena::new();
419 let mut a = arena.alloc_of::<u64>(1024);
420 a.as_mut_slice::<u64>().fill(7);
421 let b = arena.alloc_of::<u64>(1024);
422 assert_eq!(a.as_slice::<u64>()[1023], 7);
423 assert_eq!(b.as_slice::<u64>()[0], 0, "fresh block memory is zeroed");
424 let held = arena.capacity();
425 arena.reset();
426 let _c = arena.alloc_of::<u64>(1024);
427 assert_eq!(arena.capacity(), held, "reset keeps blocks");
428 }
429
430 #[test]
431 fn a_small_run_pays_a_small_block() {
432 let mut arena = MorselArena::new();
433 let _one_vector = arena.alloc(64, 64);
434 assert_eq!(
435 arena.capacity(),
436 FIRST_BLOCK_BYTES,
437 "a run that wants 64 bytes does not take 256 KiB"
438 );
439 // Spilling the first block takes one twice its size.
440 let _spill = arena.alloc(FIRST_BLOCK_BYTES, 64);
441 assert_eq!(arena.capacity(), FIRST_BLOCK_BYTES * 3);
442 // Doubling stops at the largest block, however far it runs.
443 for _ in 0..8 {
444 arena.alloc(BLOCK_BYTES, 64);
445 }
446 assert!(
447 arena.blocks.iter().all(|b| b.bytes <= BLOCK_BYTES),
448 "no block grows past the cap"
449 );
450 assert!(
451 arena.blocks.iter().any(|b| b.bytes == BLOCK_BYTES),
452 "a run that keeps asking reaches the cap"
453 );
454 }
455
456 #[test]
457 fn oversize_gets_own_block() {
458 let mut arena = MorselArena::new();
459 let small = arena.alloc_of::<u64>(4);
460 let big = arena.alloc(BLOCK_BYTES * 2, 64);
461 let small2 = arena.alloc_of::<u64>(4);
462 assert_eq!(big.len(), BLOCK_BYTES * 2);
463 assert_eq!(small.as_slice::<u64>().len(), 4);
464 assert_eq!(small2.as_slice::<u64>().len(), 4);
465 }
466
467 #[test]
468 fn alignment_honored() {
469 let mut arena = MorselArena::new();
470 let _odd = arena.alloc(3, 1);
471 let aligned = arena.alloc_of::<u64>(1);
472 assert_eq!(aligned.as_slice::<u64>().len(), 1);
473 }
474
475 #[test]
476 fn borrowed_reads_the_memory_it_was_given() {
477 // A column of a registered frame: the values are read where
478 // they lie, and the arena never sees them.
479 let outside = [7u64, 8, 9];
480 let buf = unsafe {
481 RawBuf::borrowed(
482 NonNull::new(outside.as_ptr() as *mut u8).expect("a real pointer"),
483 size_of_val(&outside[..]),
484 )
485 };
486 assert_eq!(buf.as_slice::<u64>(), &outside[..]);
487 let mut arena = MorselArena::new();
488 arena.reset();
489 // Nothing about the morsel reaches it: it survives the reset
490 // that kills every buffer the arena handed out.
491 assert_eq!(buf.as_slice::<u64>()[2], 9);
492 }
493
494 #[test]
495 #[should_panic(expected = "borrowed buffer was written")]
496 #[cfg(debug_assertions)]
497 fn writing_a_borrowed_buffer_asserts() {
498 let outside = [7u64];
499 let mut buf = unsafe {
500 RawBuf::borrowed(
501 NonNull::new(outside.as_ptr() as *mut u8).expect("a real pointer"),
502 8,
503 )
504 };
505 buf.as_mut_slice::<u64>()[0] = 1;
506 }
507
508 #[test]
509 fn a_pooled_arena_comes_back_with_the_block_the_last_run_left() {
510 // On a thread of its own, because the pool is per thread and
511 // what is being checked is what one thread hands itself between
512 // two runs.
513 std::thread::spawn(|| {
514 let first = {
515 let mut arena = MorselArena::pooled();
516 let _ = arena.alloc_of::<u64>(64);
517 arena.blocks[0].ptr
518 };
519 let mut arena = MorselArena::pooled();
520 assert_eq!(arena.capacity(), FIRST_BLOCK_BYTES, "the block is kept");
521 assert_eq!(arena.blocks[0].ptr, first, "and it is the same block");
522 // Taken means reset, so the second run bumps from the top of
523 // it rather than from where the first one stopped.
524 assert_eq!(arena.alloc_of::<u64>(64).as_slice::<u64>().len(), 64);
525 assert_eq!(arena.capacity(), FIRST_BLOCK_BYTES, "nothing new is taken");
526 })
527 .join()
528 .expect("thread");
529 }
530
531 #[test]
532 fn an_arena_that_grew_for_one_run_does_not_charge_the_next() {
533 std::thread::spawn(|| {
534 {
535 let mut arena = MorselArena::pooled();
536 let _ = arena.alloc(64, 64);
537 for _ in 0..8 {
538 arena.alloc(BLOCK_BYTES, 64);
539 }
540 assert!(arena.capacity() > POOL_KEEP_BYTES, "this run went wide");
541 }
542 let arena = MorselArena::pooled();
543 assert_eq!(
544 arena.capacity(),
545 FIRST_BLOCK_BYTES,
546 "a wide run hands back its first block and no more"
547 );
548 })
549 .join()
550 .expect("thread");
551 }
552
553 #[test]
554 #[should_panic(expected = "arena was reset")]
555 #[cfg(debug_assertions)]
556 fn a_buffer_that_outlived_its_run_fails_on_the_next_one() {
557 // Reuse is only as safe as the reset, and this is the reset: a
558 // buffer that escaped the run it was cut from reads as a use
559 // after reset on the run that takes the arena next, rather than
560 // quietly reading that run's bytes.
561 let buf = {
562 let mut arena = MorselArena::pooled();
563 arena.alloc_of::<u64>(8)
564 };
565 let _next = MorselArena::pooled();
566 let _ = buf.as_slice::<u64>();
567 }
568
569 #[test]
570 #[should_panic(expected = "arena was reset")]
571 #[cfg(debug_assertions)]
572 fn use_after_reset_asserts() {
573 let mut arena = MorselArena::new();
574 let buf = arena.alloc_of::<u64>(8);
575 arena.reset();
576 let _ = buf.as_slice::<u64>();
577 }
578}