Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
460c0d5
fix(store): a replaced splayed table keeps one copy of itself (#713)
singaraiona Oct 5, 2026
b3c8222
Merge pull request #714 from RayforceDB/feat/splay-retention-713
singaraiona Oct 5, 2026
6537eb3
fix(query): exclude null symbols from not-in (#739)
singaraiona Oct 8, 2026
00f5ea8
Merge pull request #742 from RayforceDB/fix/739-sym-not-in-nulls
singaraiona Oct 8, 2026
21e0d0c
perf(index): store hash slot table and group offsets as 32-bit
ser-vasilich Oct 6, 2026
506bc68
fix(heap): count off-heap allocations toward the spill watermark (#712)
ser-vasilich Oct 6, 2026
8e9b7d7
perf(index): store hash index row ids as 32-bit
ser-vasilich Oct 6, 2026
46c0608
fix(arena): grow chunks so a large arena can spill (#712)
ser-vasilich Oct 6, 2026
b00e1fe
fix(index): keep the wide arrays when narrowing is interrupted
ser-vasilich Oct 6, 2026
2883f55
fix(heap): hand memory back between statements when it is short
ser-vasilich Oct 7, 2026
13bcf74
perf(index): build hash indexes partition by partition within the mem…
ser-vasilich Oct 7, 2026
32f338c
fix(heap): relieve only when it brings the footprint back under the w…
ser-vasilich Oct 8, 2026
433c85c
Merge pull request #745 from RayforceDB/perf/hash-index-build
singaraiona Oct 8, 2026
e767c04
Merge pull request #746 from RayforceDB/fix/heap-watermark-712
singaraiona Oct 8, 2026
06a7b56
perf(scan): read ahead the columns a pass reads on cold storage (#747)
ser-vasilich Oct 8, 2026
9c76c90
fix(store): a reader keeps up with a table that is being rewritten (#…
ser-vasilich Oct 8, 2026
d02757c
perf(parquet): import column by column when memory is short, through …
ser-vasilich Oct 8, 2026
0fe8318
perf(query): isolate sparse group-count worker slices (#741)
singaraiona Oct 8, 2026
57f5cfe
fix(query): compare ordered symbols by lexical value (#743)
singaraiona Oct 8, 2026
24c14e8
perf(query): compose safe nested selects before planning (#754)
singaraiona Oct 8, 2026
f91f52f
fix(query): align membership, concat, and grouped fallback semantics …
singaraiona Oct 10, 2026
676c2f0
fix(query): sort and take a no-output grouping on a computed key (#772)
ser-vasilich Oct 11, 2026
869ded1
perf(import): bound parquet symbol import and splayed hash-index I/O …
ser-vasilich Oct 11, 2026
86bc380
fix(eval): closure scoping, eval windows and key purity (#777)
ser-vasilich Oct 11, 2026
d17dfbc
fix(heap): relieve memory on evidence of a spill, discard parked spil…
ser-vasilich Oct 11, 2026
16f9401
perf(store): reuse unchanged partitions across parted mounts (#761)
singaraiona Oct 11, 2026
92e37db
fix(store): release unused partition domains before splayed I/O (#782)
singaraiona Oct 11, 2026
1789a4d
fix(test): read pf_sink so clang accepts test_pool.c (#775)
vbmithr Oct 12, 2026
5c4dde9
fix(query): a multi-key select with a distinct count beside an expres…
singaraiona Oct 12, 2026
c5f2765
fix(query): release the filter result in the count-distinct rewrite (…
ihrfv Oct 12, 2026
43b9941
fix: empty-left in answers B8; balance sys-mapped on map and unmap (#…
ser-vasilich Oct 12, 2026
b5a813a
fix: string membership in and out of queries; null equality across ty…
ser-vasilich Oct 12, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ jobs:
scripts/fuzz-seed-frames.sh || true
- name: Fuzz smoke
run: make fuzz-smoke
- name: Nested select differential fuzz (serial and parallel)
run: |
# Start each mode from committed seeds. Replaying the growing cache
# can exhaust the short run before it reaches any mutations.
corpus_root=$(mktemp -d "$RUNNER_TEMP/select-merge.XXXXXX")
make fuzz-select_merge FUZZ_RUNTIME=60 FUZZ_CORPUS_ROOT="$corpus_root/serial"
RAY_FUZZ_CORES=4 make fuzz-select_merge FUZZ_RUNTIME=60 FUZZ_CORPUS_ROOT="$corpus_root/parallel"
- name: Upload crash artifacts
if: failure()
uses: actions/upload-artifact@v4
Expand All @@ -108,7 +115,7 @@ jobs:
- uses: actions/checkout@v4
- name: TSan concurrency suites
run: |
for f in pool heap parallel stress; do
for f in pool heap parallel stress store/parted_concurrent_mounts; do
echo "::group::tsan -f $f"
make tsan-test TSAN_FILTER=$f || exit 1
echo "::endgroup::"
Expand Down
7 changes: 6 additions & 1 deletion .github/workflows/nightly.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ jobs:
strategy:
fail-fast: false
matrix:
target: [parse, numparse, de, eval, csv, journal]
target: [parse, numparse, de, eval, csv, journal, select_merge]
include:
- target: select_merge
cores: 4
steps:
- uses: actions/checkout@v4
with: { ref: dev }
Expand All @@ -67,6 +70,8 @@ jobs:
scripts/fuzz-seed-parse.sh || true
scripts/fuzz-seed-frames.sh || true
- name: Fuzz ${{ matrix.target }} (15 min)
env:
RAY_FUZZ_CORES: ${{ matrix.cores || 0 }}
run: make fuzz-${{ matrix.target }} FUZZ_RUNTIME=900
- name: Upload crash artifacts
if: failure()
Expand Down
7 changes: 4 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,9 @@ compdb:
# The system toolchain on macOS does not ship the fuzzer runtime, so
# these targets are Linux-only by design; CI gates them to ubuntu.
FUZZ_RUNTIME ?= 60
FUZZ_CORPUS_ROOT ?= fuzz/corpus
FUZZ_OPTS = -rss_limit_mb=4096 -timeout=10 -max_len=65536 -print_final_stats=1
FUZZ_TARGETS = parse numparse de eval csv journal parquet
FUZZ_TARGETS = parse numparse de eval csv journal parquet select_merge
# Escape hatch for hosts where clang auto-selects a gcc toolchain dir that
# lacks libstdc++ (e.g. a partially-installed newer gcc shadowing the real
# one). Normally empty; set on such a box, e.g.
Expand Down Expand Up @@ -406,14 +407,14 @@ build_fuzz/fuzz_%: fuzz/fuzz_%.c $(FUZZ_LIB_OBJ)
.PRECIOUS: build_fuzz/fuzz_%

fuzz-%: build_fuzz/fuzz_%
@mkdir -p fuzz/corpus/$*
@mkdir -p "$(FUZZ_CORPUS_ROOT)/$*"
@dict=$(DICT_$*); \
dictopt=$${dict:+-dict=fuzz/dict/$$dict.dict}; \
seeds=$$( [ -d fuzz/seeds/$* ] && echo fuzz/seeds/$* ); \
set -x; \
ASAN_OPTIONS=detect_leaks=1:abort_on_error=1 \
UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 \
./build_fuzz/fuzz_$* fuzz/corpus/$* $$seeds \
./build_fuzz/fuzz_$* "$(FUZZ_CORPUS_ROOT)/$*" $$seeds \
$$dictopt $(FUZZ_OPTS) -max_total_time=$(FUZZ_RUNTIME)

# Short smoke pass for PR CI — a healthy corpus finds nothing new in a
Expand Down
17 changes: 17 additions & 0 deletions bench/concat_fallback.rfl
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
;; PR #744 concat helper / per-group fallback. Release build, -c 8.
;; Two million rows, one million two-row groups; first timing is warmup.
(set n 2000000)
(set i (til n))
(set T (table [x k s t] (list i (% i 1000000) (take ['ab 'cd] n) (take ["a" "b"] n))))
(set sfx (fn [v] (concat v "!")))
(println "str-helper-projection")
(map (fn [_] (println (timeit (select {v: (sfx t) from: T})))) (til 4))
(println "computed-text-group-fallback")
(map (fn [_] (println (timeit (select {n: (+ (count (concat (upper s) "!")) (count (distinct x))) by: k from: T})))) (til 4))
;; Small inputs expose planning overhead. Timings cover 10,000 queries.
(set i (til 10))
(set T (table [x k s] (list i (% i 3) (take ['a 'b] 10))))
(set sfq (fn [v] (concat v "?")))
(println "tiny-two-helper-group-fallback-10000")
(map (fn [_] (println (timeit (times 10000 (select {n: (+ (+ (count (sfx s)) (count (sfq s))) (count (distinct x))) by: k from: T}))))) (til 6))
(exit 0)
11 changes: 11 additions & 0 deletions bench/concat_update_fallback.rfl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
(set n 2000000)
(set i (til n))
(set T (table [x k s] (list i (% i 1000000) (take ['ab 'cd] n))))
(set sfx (fn [v] (concat v "!")))
(println "no-concat")
(map (fn [_] (println (timeit (update {n: (+ (count s) (count (distinct x))) by: k from: T})))) (til 4))
(println "computed-text")
(map (fn [_] (println (timeit (update {n: (+ (count (concat (upper s) "!")) (count (distinct x))) by: k from: T})))) (til 4))
(println "helper")
(map (fn [_] (println (timeit (update {n: (+ (count (sfx s)) (count (distinct x))) by: k from: T})))) (til 4))
(exit 0)
16 changes: 16 additions & 0 deletions bench/membership_fallback.rfl
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
;; PR #744 evaluator membership regression. Release build, -c 8.
;; Twenty million rows; milliseconds, first iteration is warmup.
(set n 20000000)
(set x (% (til n) 10))
(set vocab (as 'SYM (as 'STR (til 10))))
(set T (table [x s] (list x (at vocab x))))
(println "symbol-inline-probe")
(map (fn [_] (println (timeit (select {from: T where: (in s (as 'SYM (list "1" "5" "7")))})))) (til 7))
(println "integer-inline-probe")
(map (fn [_] (println (timeit (select {from: T where: (in x (distinct [1 5 7]))})))) (til 7))
(println "symbol-planned-probe")
(set probe (as 'SYM (list "1" "5" "7")))
(map (fn [_] (println (timeit (select {from: T where: (in s probe)})))) (til 7))
(println "integer-planned-probe")
(map (fn [_] (println (timeit (select {from: T where: (in x [1 5 7])})))) (til 7))
(exit 0)
135 changes: 135 additions & 0 deletions bench/nested_select.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Issue #752: compare literal nesting, do-materialization and hand composition.

Build: make release
Run: python3 bench/nested_select.py --binary ./rayforce --rows 5000000
Sparse: add --a-period 1000 --widths 4 --rows 20000000
The baseline uses `do` to keep the inner select materialized, without a runtime
optimizer flag. Every available variant must serialize identically before timing.
"""
import argparse
import os
import re
from pathlib import Path
import statistics
import subprocess
import tempfile


def materialized(expr):
"""Wrap every literal from/select boundary, including three-layer cases."""
insertions = []
for match in re.finditer(r"from:\s*(?=\(select)", expr):
start = match.end()
depth = 0
for end in range(start, len(expr)):
depth += (expr[end] == "(") - (expr[end] == ")")
if depth == 0:
insertions.extend(((start, "(do "), (end + 1, ")")))
break
for pos, text in sorted(insertions, reverse=True):
expr = expr[:pos] + text + expr[pos:]
return expr


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", default="./rayforce")
parser.add_argument("--rows", type=int, default=5_000_000)
parser.add_argument("--runs", type=int, default=7)
parser.add_argument("--cores", type=int, default=4)
parser.add_argument("--a-period", type=int, default=3,
help="inner equality selectivity is 1 / a-period")
parser.add_argument("--widths", type=int, nargs="+", choices=(4, 40), default=(4, 40))
args = parser.parse_args()
if args.rows < 1 or args.runs < 1 or args.a_period < 2:
parser.error("rows/runs must be positive and a-period must be at least 2")
lines = [f"(set I (til {args.rows}))"]
cases = []
check_count = 0
for width in args.widths:
cols = ["a", "b", "k", "p"] + [f"c{i}" for i in range(width - 4)]
vals = [f"(% I {args.a_period})", "(% I 5)", "(% I 100)", "(as 'F64 I)"] + [f"(+ I {i})" for i in range(width - 4)]
lines.append(f"(set T (table [{' '.join(cols)}] (list {' '.join(vals)})))")
identity = " ".join(f"{c}:{c}" for c in cols)
shapes = [
("from:T where:(== a 1)", "where:(== b 1) total:(sum p)",
"from:T where:(and (== a 1) (== b 1)) total:(sum p)"),
(f"from:T where:(== a 1) {identity} q:(* p 2)", "by:k total:(sum q)",
"from:T where:(== a 1) by:k total:(sum (* p 2))"),
("from:T where:(== a 1)", "take:10", "from:T where:(== a 1) take:10"),
(f"from:T {identity}", "where:(== a 1) total:(sum p)",
"from:T where:(== a 1) total:(sum p)"),
# Review regressions: single predicate, rare/late and absent matches.
("from:T where:(== b 1)", "total:(sum p)",
"from:T where:(== b 1) total:(sum p)"),
("from:T where:(> b 3)", "total:(count a)",
"from:T where:(> b 3) total:(count a)"),
(f"from:T where:(> p {max(0, args.rows - 10)}.0)", "total:(sum p)", None),
(f"from:T where:(== p {args.rows * 3 // 4}.0)", "total:(sum p)", None),
(f"from:T where:(> p {max(0, args.rows - 10)}.0)", "by:k total:(sum p)", None),
(f"from:T where:(> p {args.rows}.0)", "total:(sum p)", None),
(f"from:T where:(> p {args.rows}.0)", "by:k total:(sum p)", None),
("from:T q0:(* p 1.0001) q1:(+ q0 q0) q2:(+ q1 q1) q3:(+ q2 q2) q4:(+ q3 q3) q5:(+ q4 q4)",
"where:(> q5 1) v:q5", None),
(f"from:(select {{from:T where:(> p {max(0, args.rows - 10)}.0)}}) by:k total:(sum p)",
"total:total", None),
# Vary --a-period to compare selective and dense inner filters.
("from:T where:(< a 10)", "where:(== b 1) total:(sum p)", None),
("from:T where:(== a 1) q:p", "where:(> q 5) total:(avg q)", None),
(f"from:T where:(< a {max(1, args.a_period * 4 // 5)})",
"where:(== b 1) total:(sum p)", None),
("from:T where:(== a 1)", "where:(== b 1) p:p", None),
]
for number, (inner, outer, flat) in enumerate(shapes, 1):
tag = f"{width}/S{number}"
nested = f"(select {{from:(select {{{inner}}}) {outer}}})"
variants = {"materialized": materialized(nested), "nested": nested}
if flat is not None:
variants["manual"] = f"(select {{{flat}}})"
for name, expr in variants.items():
lines.append(f"(set B_{name} (ser {expr}))")
for name in list(variants)[1:]:
check_count += 1
lines.append(f'(println "CHECK {tag} {name} %" (if (== (count B_materialized) (count B_{name})) (all (== B_materialized B_{name})) false))')
for expr in variants.values():
lines.append(f"(timeit {expr})")
for run in range(args.runs):
names = list(variants) if run % 2 == 0 else list(reversed(variants))
for name in names:
lines.append(f'(println "TIME {tag} {name} %" (timeit {variants[name]}))')
cases.append(tag)
lines.append("(exit 0)")
with tempfile.TemporaryDirectory(prefix="ray-nested-select-") as tmp:
script = Path(tmp) / "bench.rfl"
# Keep the expanded matrix below the parser's top-level expression limit.
script.write_text("\n".join(
"(do\n" + "\n".join(lines[i:i + 64]) + "\n)"
for i in range(0, len(lines), 64)) + "\n")
result = subprocess.run([str(Path(args.binary).resolve()), str(script)],
env={**os.environ, "RAYFORCE_CORES": str(args.cores)},
capture_output=True, text=True)
if result.returncode:
raise RuntimeError(f"benchmark failed:\n{result.stdout}\n{result.stderr}")
checks = [line for line in result.stdout.splitlines() if line.startswith("CHECK ")]
if len(checks) != check_count or any(not line.endswith("true") for line in checks):
raise RuntimeError(f"serialized results differ or benchmark failed:\n{result.stdout}\n{result.stderr}")
times = {}
for line in result.stdout.splitlines():
if line.startswith("TIME "):
_, case, variant, ms = line.split()
times.setdefault((case, variant), []).append(float(ms))
print(f"{args.rows:,} rows, {args.cores} workers, a-period {args.a_period}, median of {args.runs} interleaved runs; all serialized results equal.")
print("| Columns/shape | Materialized ms | Nested ms | Manual ms | Speedup |")
print("|---|---:|---:|---:|---:|")
for case in cases:
values = [times[(case, name)] for name in ("materialized", "nested")]
if any(len(v) != args.runs for v in values):
raise RuntimeError("incomplete timing output")
old, new = map(statistics.median, values)
manual = f"{statistics.median(times[(case, 'manual')]):.4f}" if (case, "manual") in times else "—"
print(f"| {case} | {old:.4f} | {new:.4f} | {manual} | {old / new:.2f}x |")


if __name__ == "__main__":
main()
47 changes: 47 additions & 0 deletions bench/sym_ordered_query.rfl
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
;; Regression benchmark for #738 / PR #743. Run a release build with:
;; ./rayforce -c 8 bench/sym_ordered_query.rfl
;; Timings are milliseconds; the first of five runs warms each query.
;; Vocabulary padding is outside the timed regions. Peak memory exceeds 1 GiB.

(set Tiny (table [s] (list (as 'SYM ["zz" "mm" "" "aa" "mm"]))))
(println "tiny-small-vocabulary")
(map (fn [_] (println (timeit (select {from: Tiny where: (< s 'mm)})))) (til 5))
(set pad (as 'SYM (as 'STR (+ 10000000 (til 1000000)))))
(set pad null)
(println "tiny-1m-vocabulary")
(map (fn [_] (println (timeit (select {from: Tiny where: (< s 'mm)})))) (til 5))
(set vocabulary (as 'SYM (as 'STR (til 1000))))
(set ids (% (til 20000000) 1000))
(set T (table [a b n] (list (at vocabulary ids) (at vocabulary (% (+ ids 337) 1000)) ids)))
(println "column-column-20m-1m-vocabulary")
(map (fn [_] (println (timeit (select {v: (< a b) from: T})))) (til 5))
(println "literal-projection-20m-1m-vocabulary")
(map (fn [_] (println (timeit (select {v: (< a "500") from: T})))) (til 5))
(println "count-20m-1m-vocabulary")
(map (fn [_] (println (timeit (count (select {from: T where: (< a "500")}))))) (til 5))
(println "group-20m-1m-vocabulary")
(map (fn [_] (println (timeit (select {v: (count a) from: T where: (< a "500") by: n})))) (til 5))
(set T null)
(set ids null)
(set B (table [s] (list (as 'SYM (at ["zz" "mm" "" "aa" "mm"] (% (til 2000000) 5))))))
(println "literal-2m-1m-vocabulary")
(map (fn [_] (println (timeit (select {v: (< s 'mm) from: B})))) (til 5))
(set pad (as 'SYM (as 'STR (+ 11000000 (til 3000000)))))
(set pad null)
(println "tiny-4m-vocabulary")
(map (fn [_] (println (timeit (select {from: Tiny where: (< s 'mm)})))) (til 5))
(set pad (as 'SYM (as 'STR (+ 14000000 (til 300000)))))
(set pad null)
(println "literal-2m-above-cutoff")
(map (fn [_] (println (timeit (select {v: (< s 'mm) from: B})))) (til 5))
;; Warm metric keys and query syntax before measuring literal pollution.
(set LL "warmup")
(set literal_probe (fn [i] (do (set LL (format "unseen-743-%" i)) (count (select {from: Tiny where: (< s LL)})))))
(set probes (til 10000))
(literal_probe -1)
(.sys.mem)
(set before (at (.sys.mem) 'sym-count))
(map literal_probe probes)
(println "runtime-symbol-growth-for-10000-string-literals")
(println (- (at (.sys.mem) 'sym-count) before))
(exit 0)
30 changes: 18 additions & 12 deletions docs/docs/guides/memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Rayforce uses a custom memory subsystem — no calls to `malloc` or `free` ever
- **Slab cache** — Small allocations (common for atoms and short vectors) are served from pre-sized slab pools, avoiding buddy-tree overhead.
- **COW ref counting** — Vectors use copy-on-write semantics via `ray_retain`/`ray_release`. Shared vectors are only copied when mutated. Note that `ray_retain`/`ray_release`/`ray_cow` are no-ops on `RAY_ERROR` objects, so an error block must be reclaimed with `ray_error_free()` rather than `ray_release()`.
- **Arena allocator** — For bulk short-lived blocks (e.g., intermediate query results). Arena objects carry an `RAY_ATTR_ARENA` flag that makes retain/release no-ops. The entire arena is freed at once when work completes.
- **Out-of-core spill** — There is no enforced memory ceiling. The heap tracks how much anonymous (RAM) memory it has committed; once an allocation would push that past the **anon watermark** (by default total physical RAM, or the container's cgroup memory limit when that is smaller — `docker run --memory`, systemd `MemoryMax=`; `-m SIZE` overrides it), it is backed by a preallocated disk file instead of anonymous RAM. File-backed pages are always reclaimable to disk, so they can't trigger the OOM killer — the working set spills and the query completes (slowly) rather than being killed. This never rejects work. Total physical RAM is detected at startup for this threshold and for reporting (see `.sys.info` → `total-mem`).
- **Out-of-core spill** — There is no enforced memory ceiling. The heap tracks how much anonymous (RAM) memory it has committed; once an allocation would push that past the **anon watermark** (by default total physical RAM, or the container's cgroup memory limit when that is smaller — `docker run --memory`, systemd `MemoryMax=` — less a quarter of it, at least 3 GiB and at most half, left to the page cache; `-m SIZE` overrides it), it is backed by a preallocated disk file instead of anonymous RAM. File-backed pages are always reclaimable to disk, so they can't trigger the OOM killer — the working set spills and the query completes (slowly) rather than being killed. This never rejects work. Total physical RAM is detected at startup for this threshold and for reporting (see `.sys.info` → `total-mem`).

For a deep dive into the allocator internals, see [Memory Model](../architecture/memory.md).

Expand Down Expand Up @@ -234,12 +234,14 @@ disk-full error.
has committed, and when a new pool or large allocation would push that past the
watermark — by default the smaller of total physical RAM and the container's
cgroup memory limit (cgroup v2 `memory.max` / v1 `memory.limit_in_bytes`,
including limits set on a parent slice), or the `-m SIZE` flag when given — it
including limits set on a parent slice), less a quarter of it (at least 3 GiB,
at most half) left to the page cache, or the `-m SIZE` flag when given — it
backs that allocation with a disk spill file **instead of** anonymous RAM. This never rejects work; it just routes
the overflow to disk so it spills rather than getting OOM-killed. A query like
`(til 10000000000)` (a 74 GiB vector) on a smaller machine now spills to disk and
completes (slowly) instead of being terminated. The progress bar's `used / total`
figure shows the footprint approaching total RAM — the point where spill begins.
figure shows the footprint approaching total RAM; spill begins below it, at the
watermark.

### Checking total RAM

Expand All @@ -256,24 +258,28 @@ total-mem | 16777216000

### Gauging headroom

To see how close a workload is to spilling to disk, compare the live object
footprint (`bytes-allocated + direct-bytes` from `(.sys.mem)`) against
`total-mem` from `(.sys.info)`:
To see how close a workload is to spilling to disk, compare the anonymous
footprint the heap has committed (`anon-committed` from `(.sys.mem)`: pools,
large blocks and the off-heap tables such as the symbol arenas) against the
spill threshold (`anon-watermark`):

```lisp
;; Live footprint as a percentage of physical RAM
;; Committed RAM as a percentage of the spill threshold
(set stats (.sys.mem))
(set info (.sys.info))
(* 100.0 (/ (+ (get stats 'bytes-allocated) (get stats 'direct-bytes))
(get info 'total-mem)))
(* 100.0 (/ (get stats 'anon-committed) (get stats 'anon-watermark)))
```

```text
29.4
```

This shows 29.4% of physical RAM is in use — plenty of headroom before the heap
begins spilling to disk.
This shows the workload uses 29.4% of the RAM it may take before new memory
starts going to spill files.

A spill file is mapped shared. An embedding process that `fork()`s and keeps
running rayforce code in the child shares the spilled blocks with the parent
instead of getting its own copy, so the child must not write them; run the
child through `exec` (as `.sys.exec` does) or start it before anything spills.

## 9. Practical Patterns

Expand Down
Loading
Loading