ruvector-graph 2.0.6

Distributed Neo4j-compatible hypergraph database with SIMD optimization
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Custom memory allocators for graph query execution
//!
//! This module provides specialized allocators:
//! - Arena allocation for query-scoped memory
//! - Object pooling for frequent allocations
//! - NUMA-aware allocation for distributed systems

use parking_lot::Mutex;
use std::alloc::{alloc, dealloc, Layout};
use std::cell::Cell;
use std::ptr::{self, NonNull};
use std::sync::Arc;

/// Arena allocator for query execution
/// All allocations are freed together when the arena is dropped
pub struct ArenaAllocator {
    /// Current chunk
    current: Cell<Option<NonNull<Chunk>>>,
    /// All chunks (for cleanup)
    chunks: Mutex<Vec<NonNull<Chunk>>>,
    /// Default chunk size
    chunk_size: usize,
}

struct Chunk {
    /// Data buffer
    data: NonNull<u8>,
    /// Current offset in buffer
    offset: Cell<usize>,
    /// Total capacity
    capacity: usize,
    /// Next chunk in linked list
    next: Cell<Option<NonNull<Chunk>>>,
}

impl ArenaAllocator {
    /// Create a new arena with default chunk size (1MB)
    pub fn new() -> Self {
        Self::with_chunk_size(1024 * 1024)
    }

    /// Create arena with specific chunk size
    pub fn with_chunk_size(chunk_size: usize) -> Self {
        Self {
            current: Cell::new(None),
            chunks: Mutex::new(Vec::new()),
            chunk_size,
        }
    }

    /// Allocate memory from the arena
    pub fn alloc<T>(&self) -> NonNull<T> {
        let layout = Layout::new::<T>();
        let ptr = self.alloc_layout(layout);
        ptr.cast()
    }

    /// Allocate with specific layout
    pub fn alloc_layout(&self, layout: Layout) -> NonNull<u8> {
        let size = layout.size();
        let align = layout.align();

        // SECURITY: Validate layout parameters
        assert!(size > 0, "Cannot allocate zero bytes");
        assert!(
            align > 0 && align.is_power_of_two(),
            "Alignment must be a power of 2"
        );
        assert!(size <= isize::MAX as usize, "Allocation size too large");

        // Get current chunk or allocate new one
        let chunk = match self.current.get() {
            Some(chunk) => chunk,
            None => {
                let chunk = self.allocate_chunk();
                self.current.set(Some(chunk));
                chunk
            }
        };

        unsafe {
            let chunk_ref = chunk.as_ref();
            let offset = chunk_ref.offset.get();

            // Align offset
            let aligned_offset = (offset + align - 1) & !(align - 1);

            // SECURITY: Check for overflow in alignment calculation
            if aligned_offset < offset {
                panic!("Alignment calculation overflow");
            }

            let new_offset = aligned_offset
                .checked_add(size)
                .expect("Arena allocation overflow");

            if new_offset > chunk_ref.capacity {
                // Need a new chunk
                let new_chunk = self.allocate_chunk();
                chunk_ref.next.set(Some(new_chunk));
                self.current.set(Some(new_chunk));

                // Retry allocation with new chunk
                return self.alloc_layout(layout);
            }

            chunk_ref.offset.set(new_offset);

            // SECURITY: Verify pointer arithmetic is safe
            let result_ptr = chunk_ref.data.as_ptr().add(aligned_offset);
            debug_assert!(
                result_ptr as usize >= chunk_ref.data.as_ptr() as usize,
                "Pointer arithmetic underflow"
            );
            debug_assert!(
                result_ptr as usize <= chunk_ref.data.as_ptr().add(chunk_ref.capacity) as usize,
                "Pointer arithmetic overflow"
            );

            NonNull::new_unchecked(result_ptr)
        }
    }

    /// Allocate a new chunk
    fn allocate_chunk(&self) -> NonNull<Chunk> {
        unsafe {
            let layout = Layout::from_size_align_unchecked(self.chunk_size, 64);
            let data = NonNull::new_unchecked(alloc(layout));

            let chunk_layout = Layout::new::<Chunk>();
            let chunk_ptr = alloc(chunk_layout) as *mut Chunk;

            ptr::write(
                chunk_ptr,
                Chunk {
                    data,
                    offset: Cell::new(0),
                    capacity: self.chunk_size,
                    next: Cell::new(None),
                },
            );

            let chunk = NonNull::new_unchecked(chunk_ptr);
            self.chunks.lock().push(chunk);
            chunk
        }
    }

    /// Reset arena (reuse existing chunks)
    pub fn reset(&self) {
        let chunks = self.chunks.lock();
        for &chunk in chunks.iter() {
            unsafe {
                chunk.as_ref().offset.set(0);
                chunk.as_ref().next.set(None);
            }
        }

        if let Some(first_chunk) = chunks.first() {
            self.current.set(Some(*first_chunk));
        }
    }

    /// Get total allocated bytes across all chunks
    pub fn total_allocated(&self) -> usize {
        self.chunks.lock().len() * self.chunk_size
    }
}

impl Default for ArenaAllocator {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for ArenaAllocator {
    fn drop(&mut self) {
        let chunks = self.chunks.lock();
        for &chunk in chunks.iter() {
            unsafe {
                let chunk_ref = chunk.as_ref();

                // Deallocate data buffer
                let data_layout = Layout::from_size_align_unchecked(chunk_ref.capacity, 64);
                dealloc(chunk_ref.data.as_ptr(), data_layout);

                // Deallocate chunk itself
                let chunk_layout = Layout::new::<Chunk>();
                dealloc(chunk.as_ptr() as *mut u8, chunk_layout);
            }
        }
    }
}

unsafe impl Send for ArenaAllocator {}
unsafe impl Sync for ArenaAllocator {}

/// Query-scoped arena that resets after each query
pub struct QueryArena {
    arena: Arc<ArenaAllocator>,
}

impl QueryArena {
    pub fn new() -> Self {
        Self {
            arena: Arc::new(ArenaAllocator::new()),
        }
    }

    pub fn execute_query<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&ArenaAllocator) -> R,
    {
        let result = f(&self.arena);
        self.arena.reset();
        result
    }

    pub fn arena(&self) -> &ArenaAllocator {
        &self.arena
    }
}

impl Default for QueryArena {
    fn default() -> Self {
        Self::new()
    }
}

/// NUMA-aware allocator for multi-socket systems
pub struct NumaAllocator {
    /// Allocators per NUMA node
    node_allocators: Vec<Arc<ArenaAllocator>>,
    /// Current thread's preferred NUMA node
    preferred_node: Cell<usize>,
}

impl NumaAllocator {
    /// Create NUMA-aware allocator
    pub fn new() -> Self {
        let num_nodes = Self::detect_numa_nodes();
        let node_allocators = (0..num_nodes)
            .map(|_| Arc::new(ArenaAllocator::new()))
            .collect();

        Self {
            node_allocators,
            preferred_node: Cell::new(0),
        }
    }

    /// Detect number of NUMA nodes (simplified)
    fn detect_numa_nodes() -> usize {
        // In a real implementation, this would use platform-specific APIs
        // For now, assume 1 node per 8 CPUs
        let cpus = num_cpus::get();
        ((cpus + 7) / 8).max(1)
    }

    /// Allocate from preferred NUMA node
    pub fn alloc<T>(&self) -> NonNull<T> {
        let node = self.preferred_node.get();
        self.node_allocators[node].alloc()
    }

    /// Set preferred NUMA node for current thread
    pub fn set_preferred_node(&self, node: usize) {
        if node < self.node_allocators.len() {
            self.preferred_node.set(node);
        }
    }

    /// Bind current thread to NUMA node
    pub fn bind_to_node(&self, node: usize) {
        self.set_preferred_node(node);

        // In a real implementation, this would use platform-specific APIs
        // to bind the thread to CPUs on the specified NUMA node
        #[cfg(target_os = "linux")]
        {
            // Would use libnuma or similar
        }
    }
}

impl Default for NumaAllocator {
    fn default() -> Self {
        Self::new()
    }
}

/// Object pool for reducing allocation overhead
pub struct ObjectPool<T> {
    /// Pool of available objects
    available: Arc<crossbeam::queue::SegQueue<T>>,
    /// Factory function
    factory: Arc<dyn Fn() -> T + Send + Sync>,
    /// Maximum pool size
    max_size: usize,
}

impl<T> ObjectPool<T> {
    pub fn new<F>(max_size: usize, factory: F) -> Self
    where
        F: Fn() -> T + Send + Sync + 'static,
    {
        Self {
            available: Arc::new(crossbeam::queue::SegQueue::new()),
            factory: Arc::new(factory),
            max_size,
        }
    }

    pub fn acquire(&self) -> PooledObject<T> {
        let object = self.available.pop().unwrap_or_else(|| (self.factory)());

        PooledObject {
            object: Some(object),
            pool: Arc::clone(&self.available),
        }
    }

    pub fn len(&self) -> usize {
        self.available.len()
    }

    pub fn is_empty(&self) -> bool {
        self.available.is_empty()
    }
}

/// RAII wrapper for pooled objects
pub struct PooledObject<T> {
    object: Option<T>,
    pool: Arc<crossbeam::queue::SegQueue<T>>,
}

impl<T> PooledObject<T> {
    pub fn get(&self) -> &T {
        self.object.as_ref().unwrap()
    }

    pub fn get_mut(&mut self) -> &mut T {
        self.object.as_mut().unwrap()
    }
}

impl<T> Drop for PooledObject<T> {
    fn drop(&mut self) {
        if let Some(object) = self.object.take() {
            let _ = self.pool.push(object);
        }
    }
}

impl<T> std::ops::Deref for PooledObject<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        self.object.as_ref().unwrap()
    }
}

impl<T> std::ops::DerefMut for PooledObject<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.object.as_mut().unwrap()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_arena_allocator() {
        let arena = ArenaAllocator::new();

        let ptr1 = arena.alloc::<u64>();
        let ptr2 = arena.alloc::<u64>();

        unsafe {
            ptr1.as_ptr().write(42);
            ptr2.as_ptr().write(84);

            assert_eq!(ptr1.as_ptr().read(), 42);
            assert_eq!(ptr2.as_ptr().read(), 84);
        }
    }

    #[test]
    fn test_arena_reset() {
        let arena = ArenaAllocator::new();

        for _ in 0..100 {
            arena.alloc::<u64>();
        }

        let allocated_before = arena.total_allocated();
        arena.reset();
        let allocated_after = arena.total_allocated();

        assert_eq!(allocated_before, allocated_after);
    }

    #[test]
    fn test_query_arena() {
        let query_arena = QueryArena::new();

        let result = query_arena.execute_query(|arena| {
            let ptr = arena.alloc::<u64>();
            unsafe {
                ptr.as_ptr().write(123);
                ptr.as_ptr().read()
            }
        });

        assert_eq!(result, 123);
    }

    #[test]
    fn test_object_pool() {
        let pool = ObjectPool::new(10, || Vec::<u8>::with_capacity(1024));

        let mut obj = pool.acquire();
        obj.push(42);
        assert_eq!(obj[0], 42);

        drop(obj);

        let obj2 = pool.acquire();
        assert!(obj2.capacity() >= 1024);
    }
}