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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/*
* Copyright (c) 2025-2026 Anton Kundenko <singaraiona@gmail.com>
* All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* heap.h -- Rayforce-style per-thread heap allocator (zero-prefix layout).
*
* Each thread owns one ray_heap_t. Blocks are allocated from self-aligned
* mmap'd pools via buddy splitting. ray_t IS the block — no prefix.
*
* Pool metadata (heap_id, pool_order) is stored in a pool header at
* offset 0 of each self-aligned pool (first min-block reserved).
* Pool base is derived in O(1): ptr & ~(pool_size - 1).
*
* Free-list prev/next overlay aux bytes 0-15 of ray_t (unused when free).
* rc == 0 indicates a free block (replaces the old ray_blk_t.used flag).
*
* Cross-thread free uses a foreign_blocks list (checked via pool heap_id).
*/
/* ===== Attribute Flags =====
*
* The `attrs` byte in ray_t is type-namespaced: the same bit positions carry
* different meanings depending on the object's type tag.
*
* Bits 0x01-0x03 RAY_SYM vectors: sym index width (RAY_SYM_W8/W16/W32/W64)
* Bits 0x01-0x10 function objects (RAY_UNARY/BINARY/VARY): RAY_FN_* flags
* Bit 0x02 -RAY_I64 atoms: RAY_ATTR_GRAPH (ray_rel_t* CSR handle in .i64)
* Bit 0x04 -RAY_I64 atoms: RAY_ATTR_HNSW (HNSW handle in .i64)
* Bit 0x08 vectors: RAY_ATTR_HAS_INDEX (index ray_t* in aux[0..7])
* Bit 0x10 vectors: RAY_ATTR_SLICE
* Bit 0x20 -RAY_SYM: ATTR_QUOTED (quoted/literal symbol; default = name reference)
* Bit 0x20 vectors: RAY_ATTR_SORTED (non-descending order marker)
* Bit 0x40 vectors: RAY_ATTR_HAS_NULLS (sentinel-encoded; payload is truth;
* a slice inherits its parent's bit)
* Bit 0x80 all types: RAY_ATTR_ARENA (arena-allocated, no refcount)
*
* Overlapping bit values are safe because consumers always check the type tag
* before interpreting attrs.
*
* Bit 0x20 on vectors is now RAY_ATTR_SORTED (see below).
*/
/* RAY_ATTR_SORTED (vectors): the vector's elements are known to be in
* non-descending order. A pure marker — no backing structure, no
* allocation. Set only via (.attr.set 'sorted v) after an O(n) verify
* scan, so it never lies. 0x20 is free for vectors (on -RAY_SYM atoms
* the same bit is ATTR_QUOTED). Order-aware operators (asof-join) may trust it. */
/* I64 atom carries an owning ray_rel_t* (CSR graph) in its .i64 slot.
* Checked by .graph.* builtins before dereferencing. User may call
* (.graph.free h) explicitly; the heap finalizer also frees the underlying
* ray_rel_t when the atom's rc drops to zero so rebindings/scope-exit
* never leak the graph. */
/* I64 atom carries an owning ray_hnsw_t* in its .i64 slot.
* Checked by HNSW builtins before dereferencing. User must (hnsw-free h). */
/* I64 atom carries an owning dl_program_t* (a Datalog program) in its .i64
* slot. Checked by the dl-* builtins before dereferencing, so a forged/plain
* integer or an arithmetic copy (which drops attrs) is rejected with a type
* error instead of being reinterpreted as a pointer — see dl_unwrap_program.
* Reuses 0x20 (RAY_ATTR_SORTED on vectors / ATTR_QUOTED on -RAY_SYM); the
* -RAY_I64 type tag disambiguates, and no free-path or generic check reads
* 0x20 on a -RAY_I64 atom. User must (dl-free h). */
/* Vector is a linked column. The 8 bytes of the aux union at offset
* 8 (i.e. parent->_idx_pad / parent->slice_offset / parent->str_pool
* slot, depending on which arm is in use) hold an int64
* sym ID naming the target table. Resolved against the global env at
* deref time. Restricted to RAY_I32 / RAY_I64 vectors — STR/SYM/SLICE
* already use bytes 8-15 for their own pointers/data so HAS_LINK on
* those types would alias.
*
* Coexists with HAS_INDEX: bytes 0-7 carry the index pointer (or saved
* aux), bytes 8-15 carry the link sym; both bits can be set on the
* same column.
*
* Same numeric value as RAY_ATTR_HNSW (HNSW handles are -RAY_I64 atoms,
* the type tag disambiguates). */
/* Vector carries an attached accelerator index in aux[0..7] (a ray_t*
* of type RAY_INDEX). The original 16-byte aux union content
* (slice_offset, str_pool, link_target) is preserved inside the
* index ray_t and restored on detach.
*
* HAS_NULLS is preserved on the parent across attach/detach; many call
* sites use it as a cheap "do I need null-aware logic?" gate. Null state
* itself is sentinel-encoded in the payload (see src/vec/vec.c) so the
* index pointer overlay at bytes 0-7 does not affect ray_vec_is_null. */
/* == */
ray_t* ;
ray_t* ;
ray_t* ;
/* == */
ray_t* ;
/* == */
typedef struct ray_mem_stats_t;
/* Query-scoped allocation trace. Unlike ray_mem_stats_t (a lifetime snapshot
* of one heap), this aggregates allocation/free activity from every thread
* while active. Only one scope may be active process-wide. */
typedef struct ray_mem_trace_t;
/* One file mapping that more than one block lives in.
*
* A splayed string column and its pool are written contiguously and mapped
* together, so the region cannot end when either one of them does: a
* selection may hold the pool after the column it was gathered from is
* gone. The descriptor lives on the heap rather than inside the mapping —
* it has to outlive it to unmap it — and the pool holds it (mmod 3) while
* the column merely references the pool.
*
* Kept off the buddy heap (ray_sys_alloc) so a block being freed can drop
* the last reference without re-entering the allocator it is inside. */
typedef struct ray_file_map_s ray_file_map_t;
/* Make a mapping findable by the address it was mapped at. Only needed
* once a block inside it loses its own route to the descriptor — see
* str_pool_cow — so the table holds mutated mapped columns only. */
void ;
/* The mapping that starts at `base`, or NULL. A mapped column's header is
* the start of its region, so a column passes itself. */
ray_file_map_t* ;
void ;
/* == */
typedef struct ray_heap ray_heap_t;
typedef struct ray_sym_table ray_sym_table_t;
typedef struct ray_sym_map ray_sym_map_t;
typedef struct ray_task ray_task_t;
typedef struct ray_dispatch ray_dispatch_t;
/* == */
void ;
void ;
/* Detach the calling thread from its heap WITHOUT tearing the heap down:
* the heap stays registered with its pools intact and is handed to the next
* thread that calls ray_heap_init().
*
* This is what a thread that exits must use. A cross-thread free resolves
* the owning heap through ray_heap_registry and pushes the block onto it
* without taking a lock — that lookup is only sound while every registered
* heap outlives the blocks it owns, so a thread may never unregister and
* munmap a heap that another thread might still be freeing into.
* ray_heap_destroy remains the real teardown, for process shutdown. */
void ;
void ;
void ;
void ;
void ;
uint8_t ;
void ;
bool ;
void ;
void ;
void ;
/* ===== Idle decay =====
*
* Free blocks keep their pages so the next query reuses them without
* faulting. That makes a process hold its peak footprint forever, which
* costs nothing to the process and everything to whatever shares the
* machine with it. The decay gives those pages back once the process has
* been quiet for longer than a threshold, without a background thread:
* work stamps a timestamp, maintenance points compare it.
*
* ray_heap_note_activity — stamp; call at the START of a unit of work (a
* statement, an IPC request). A stamp at the end would zero the elapsed
* time seen by the boundary check that immediately follows it.
* ray_heap_decay_due_ms — ms until a sweep is due, 0 if due now, -1 if
* none is pending (nothing to release, or decay disabled). An event loop
* uses it to bound a wait it would otherwise make indefinite.
* ray_heap_decay — sweep if due and if the worker pool is
* quiescent; returns the number of blocks released, or -1 if it did
* nothing. Safe to call from any maintenance point.
*
* The threshold is fixed policy, reachable only through
* ray_heap_set_decay_ms: negative disables the decay, 0 releases at the
* next maintenance point after any work. */
void ;
int64_t ;
int64_t ;
/* Set the threshold directly; negative disables. The environment is read
* once on first use, so this exists to let a test drive the policy without
* re-exec — not as a runtime knob. */
void ;
/* --------------------------------------------------------------------------
* Constants
* -------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------
* Block size helper
* -------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------
* Direct large allocation
*
* An allocation that would otherwise need a dedicated OVERSIZED buddy pool
* (order >= RAY_HEAP_POOL_ORDER) is instead mmap'd at its EXACT page-rounded
* size — no power-of-2 block rounding, no order+1 pool doubling. Layout:
* [ray_direct_hdr_t (32B) | ray_t header (32B) | data], page-rounded. The
* ray_t is marked with an order ABOVE the max real order, so every buddy path
* (freelist indexing, coalescing, pool masking, capacity) skips it, and it is
* freed by a standalone munmap from any thread (address space is
* process-wide); its bytes live in a single global atomic.
* -------------------------------------------------------------------------- */
typedef struct ray_direct_hdr_t;
;
static inline bool
static inline size_t
/* Usable data bytes (block minus the 32-byte ray_t header). Handles both
* buddy blocks and direct blocks, so capacity math is uniform. */
static inline size_t
/* True if a direct block is backed by a disk spill file (vs anonymous RAM). */
static inline bool
/* Anonymous (RAM-resident, OOM-killable) pool + direct bytes currently
* committed by the heap. Allocations that would push this past the anon
* watermark (default: total physical RAM) are backed by a disk spill file
* instead — file-backed pages are always reclaimable, so they cannot trigger
* the OOM killer. ray_heap_set_anon_watermark overrides the threshold (0
* restores the default); intended for diagnostics and tests. */
int64_t ;
/* High-water mark of the anon-committed footprint since process start — the
* peak RAM an operator actually demanded (pools + direct; excludes spill). */
int64_t ;
/* Current anon watermark in bytes (the effective spill threshold; resolves 0
* to total physical RAM). */
int64_t ;
void ;
/* Release every block held by the direct-allocation reuse cache back to
* the kernel (their committed-RAM accounting drops with them). The cache
* self-drains under watermark pressure; this is for tests and explicit
* memory trimming. */
void ;
/* --------------------------------------------------------------------------
* Pool header: first min-block (64B) of each self-aligned pool.
*
* Overlaid on bytes 0-15 of the ray_t at pool offset 0.
* The ray_t at pool offset 0 has rc=1 (prevents coalescing) and
* order=RAY_ORDER_MIN (correct for buddy math).
* -------------------------------------------------------------------------- */
typedef struct ray_pool_hdr_t;
;
/* --------------------------------------------------------------------------
* Circular sentinel freelist (Rayforce-style)
*
* Each freelist[order] is a sentinel node with prev/next pointers at
* offsets 0/8 — same layout as ray_t.fl_prev/fl_next. This makes
* fl_remove() work without knowing which freelist the block belongs to,
* enabling safe cross-heap buddy coalescing.
*
* Empty list: sentinel.prev = sentinel.next = &sentinel.
* -------------------------------------------------------------------------- */
typedef struct RAY_ALIGN ray_fl_head_t;
static inline void
static inline bool
/* Unlink a block from whatever circular list it belongs to.
* Works across heaps — no head pointer needed. */
static inline void
/* --------------------------------------------------------------------------
* Pool tracking entry (in ray_heap_t)
*
* Pools are normally backed by anonymous mmap. When anon mmap fails (the
* OS refuses an N-byte allocation because RAM+swap can't satisfy it), the
* allocator falls back to a file-backed mmap pointed at a tempfile in the
* heap's swap directory — this lets fresh allocations exceed RAM, with
* dirty pages flushed to disk by the kernel.
*
* backed=0: anonymous mmap (the common case). swap_fd unused,
* swap_path NULL.
* backed=1: file-backed mmap. swap_fd holds the open fd and
* swap_path holds the absolute path; teardown closes the
* fd, unlinks the file, and ray_sys_frees the path string.
* -------------------------------------------------------------------------- */
typedef struct ray_pool_entry_t;
/* --------------------------------------------------------------------------
* Pool derivation helpers
*
* ray_pool_of: derive pool header from any block pointer.
*
* All pools are self-aligned (pool base = multiple of pool_size). Standard
* pools (32 MB) are derived in O(1) via a single AND mask. Oversized pools
* (> 32 MB) use a downward walk at 32 MB stride to find the pool header.
*
* Pool header validation: order == RAY_ORDER_MIN, mmod == 0, rc == 1.
* These conditions uniquely identify pool header blocks — cascade/split
* blocks always have order > RAY_ORDER_MIN.
* -------------------------------------------------------------------------- */
/* A pool header is the leftmost min-block of a self-aligned pool: it always
* carries order==RAY_ORDER_MIN, mmod==0 and the sentinel rc==1 (it is never
* freed, so it never coalesces — see the pool-init at heap.c). These three
* together uniquely identify a header: every cascade/split block has
* order>RAY_ORDER_MIN, and live/free blocks never hold rc==1+order==MIN+mmod==0
* at a 32 MB boundary. ray_pool_of MUST gate EVERY header it returns on this
* signature — pool_order alone is not enough. */
static inline bool
static inline ray_pool_hdr_t*
/* --------------------------------------------------------------------------
* Buddy derivation: uses self-aligned pool base
* -------------------------------------------------------------------------- */
static inline ray_t*
/* --------------------------------------------------------------------------
* Slab cache for small blocks (orders 6-16, i.e., 64B-64KB)
* -------------------------------------------------------------------------- */
typedef struct ray_slab_t;
/* --------------------------------------------------------------------------
* Per-thread heap
* -------------------------------------------------------------------------- */
typedef struct ray_heap ray_heap_t;
/* --------------------------------------------------------------------------
* Bitmap-based heap ID allocator (atomic CAS, reusable IDs)
* -------------------------------------------------------------------------- */
/* Global pending-merge queue head (lock-free LIFO) */
extern ray_heap_pending_merge;
/* --------------------------------------------------------------------------
* Pool-list scan: find which pool a block belongs to without reading the
* remote pool header (avoids cold cache line 32MB away on hot path).
* Returns pool index in h->pools[], or -1 if block is foreign.
* -------------------------------------------------------------------------- */
static inline int
/* --------------------------------------------------------------------------
* Thread-local state
* -------------------------------------------------------------------------- */
extern RAY_TLS ray_heap_t* ray_tl_heap;
/* --------------------------------------------------------------------------
* Global heap registry: look up any heap by ID so foreign blocks can be
* returned to their owning heap instead of accumulating on the freeing heap.
* -------------------------------------------------------------------------- */
extern ray_heap_t* ray_heap_registry;
/* --------------------------------------------------------------------------
* Scratch arena: bump-allocator backed by buddy-allocated pages.
* O(1) push (pointer bump), O(n_backing) reset (free all backing blocks).
* -------------------------------------------------------------------------- */
typedef struct ray_scratch_arena_t;
static inline void
/* Retain all child/owned refs inside a compound block (STR/LIST/TABLE/etc.).
* Used by ray_block_copy and ray_alloc_copy after shallow-copying a block.
*
* Returns true on success, false if a deep-clone of a uniquely-owned
* resource (e.g. an HNSW index) failed. On failure, any owned state that
* was memcpy'd into the copy has been neutralized (attr flags cleared,
* pointers zeroed) so the caller may safely ray_free(v) without leaks or
* double-frees. */
bool ;
void* ;
void ;
/* RAY_HEAP_H */