Skip to content

v2.6.0 - #463

Merged
singaraiona merged 176 commits into
masterfrom
dev
Sep 2, 2026
Merged

v2.6.0#463
singaraiona merged 176 commits into
masterfrom
dev

Conversation

@singaraiona

Copy link
Copy Markdown
Collaborator

What & why

Checklist

  • PR targets dev (not master)
  • Commits follow Conventional Commits (feat: / fix: / perf: / docs: / …)
  • make builds cleanly (no new warnings)
  • make test passes; tests added/updated for behaviour changes

singaraiona and others added 30 commits July 11, 2026 10:44
Add immutable live-tail growth with explicit partition keys, shared FILE-domain symbol handling, atomic symbol rebinding, adversarial coverage, documentation, and a runnable rollover example.
fix(parse) Fix nonstring if not defined
In RAY_JOURNAL_SYNC mode ray_journal_write_bytes checks fsync's return on
POSIX and fails the write with RAY_ERR_IO, but the Windows branch ignored
FlushFileBuffers' return. A failed flush there was silently swallowed, so
SYNC mode reported success while the data may not have reached disk —
dropping the durability guarantee the mode exists to provide.

Check FlushFileBuffers (0 = failure) and return RAY_ERR_IO, mirroring the
POSIX path. Windows-only branch (not built on the Linux/macOS CI matrix),
so it is verified by inspection against the adjacent fsync check; the
failure path is not unit-testable, like the existing POSIX one.

Co-authored-by: Evgen Byelozorov <[email protected]>
ray_hnsw_build sized the copied vector block as n_nodes * dim *
sizeof(float) with no overflow check. Dimensions whose product wraps
size_t under-allocate the copy while the memcpy — and every later distance
read (vectors + id*dim) — run past the buffer. Guard the product before any
allocation, mirroring the per-layer neighbor guard in the loader, and
reject overflowing dimensions.

This hardens the public C API boundary; the in-tree (hnsw-build ...) path
sizes vectors from an in-memory list and cannot reach the overflow, so it
is defense-in-depth.

Add a regression test driving an overflowing n_nodes/dim pair; with the
guard removed it faults under ASan (stack-buffer-overflow at the copy).

Co-authored-by: Evgen Byelozorov <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
…334)

try_load_link_sidecar read the target table's sym name into a fixed
256-byte buffer (fread of 255 bytes). A name longer than 255 bytes was
silently truncated, so ray_sym_intern interned a DIFFERENT symbol and the
loaded column linked to the wrong table — silent data corruption on a
save/load round-trip. The writer already emits the full, untruncated name.

Read the whole sidecar into a buffer sized to the file (capped at 1 MiB to
bound a corrupt/oversized file), and reject a short read (fread returning
fewer bytes than the file size — an I/O error or a race-truncated sidecar)
so a partial name can't be interned as a different symbol either.

Add a regression test that links through a 300-byte target name and asserts
the loaded link_target matches; it fails without the fix.

Co-authored-by: Evgen Byelozorov <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
hnsw_load_impl read n_nodes and dim straight from the file header and
sized the vectors allocation as n_nodes * dim * sizeof(float) with no
overflow check. A crafted header could make that product wrap size_t, so
ray_sys_alloc under-allocated the buffer while the following fread still
read the full (large) element count and wrote past the allocation — a
heap-overflow write driven by an untrusted index file.

Factor the check into ray_hnsw_vec_size_valid(n_nodes, dim) and reject the
header before any allocation, mirroring the per-layer neighbor guard.

Add a unit test that drives the helper directly (ordinary dims, non-positive
dims, an overflowing pair, and the exact size_t boundary). It is tested at
the helper rather than through ray_hnsw_load because an overflow-patched
header is refused earlier — the huge node-level read fails first — so a
full-load test could not distinguish the guard.

Co-authored-by: Evgen Byelozorov <[email protected]>
Escalate F-0002, F-0003, F-0004, and F-0006 into CF-0001 through CF-0004 after the required corpus census.
Rebuild the MkDocs and marketing surfaces around the Rayforce brand, add the live market demo and cloud preview, unify responsive navigation, and eliminate reload layout shifts.
* fix(null): avoid f64 null casts to integers

* fix(expr): guard f64 to i64 fallback casts

* fix(null): clamp finite f64 narrow casts

---------

Co-authored-by: Evgen Byelozorov <[email protected]>
* fix(expr): avoid null truthiness casts in fallback binary ops

binary_range's fallback OP_AND/OP_OR kernels cast the widened `double`
operand straight to `uint8_t`:

    uint8_t li = (uint8_t)LV_READ(i);

`LV_READ` widens integer operands to `double` and yields NaN for float
nulls, so this had two defects:
  - Wrong answers from 8-bit truncation: `(uint8_t)256.0 == 0`, so
    `256 and 1b` returned false.
  - Undefined behavior: casting NaN (NULL_F64) or a widened NULL_I64
    (-9.2e18) to `uint8_t` is UB per C11 6.3.1.4.
UBSan flagged the latter via expr_null/diff_i64_{and,or}_raw and
expr_null/diff_f64_andor_chokes.

Route AND/OR through two truthiness helpers that compare on the widened
double and never cast it back to an integer:
  - truthy_intish(v, nullv) — false for 0 and for the operand's null
    sentinel. The fallback reads raw column memory, so a null arrives as
    the per-type sentinel widened to double (NULL_I16 / NULL_I32 /
    NULL_I64, with DATE/TIME stored as I32) rather than the NULL_I64 the
    VM kernel sees; `nullv` is derived per operand from the bound pointer
    type so I16/I32 nulls read as false, not just I64.
  - truthy_f64ish(v) — false for 0.0 and NaN (float null).

Non-null truthiness is unchanged and null-input positions still agree
with the VM kernel (documented "AND/OR with any null operand -> 0" and
the fix_null_comparisons post-pass), keeping fallback ≡ fused.

Add regression tests pinning fallback ≡ fused for nullable I64, I32 and
I16 AND/OR operands (expr_null/diff_i{64,32,16}_{and,or}_raw).

* fix(expr): preserve near-sentinel i64 truthiness

---------

Co-authored-by: Evgen Byelozorov <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
…l semantics (#341)

* wip(group): parallel binary aggregates (pearson/wavg/cov) via DA path

Route binary co-moment aggregators through the dense-array (DA) group path
instead of the hash scatter path.  Adds sum_y/sumsq_y/sumxy co-moment slots
to da_accum_t + per-row accumulation + per-worker merge; emit_agg_columns
already finalises PEARSON/COV/WAVG/WSUM from the co-moments.

Fixes poor multi-thread scaling of by-key binary aggregates (was ~2x, DA
path scales ~9-12x like stddev).  Verified vs numpy; diff comparator relaxed
to 1e-9 combined abs+rel (1e-12 absolute tested bit-identical summation).

Includes temporary RAY_GRPPROF phase instrumentation (to remove).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(group): merge binary-agg Sx as double for integer x-columns

wavg/pearson accumulate Sx as double even when the x column is integer
(e.g. wavg(bsize,bid), bsize=I32).  The per-worker merge dispatched on the
x-column type -> read the double bits as int64 -> garbage at >1 worker.
Force float merge for binary aggs at all 3 sum-merge sites.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(group): merge binary-agg co-moments in parallel da_merge_fn path

The parallel slot-range merge (da_merge_fn, taken when n_slots>=1024)
merged sumsq but not the binary-aggregate co-moment arrays
(sum_y/sumsq_y/sumxy).  Multi-key pearson/cov/wavg over >=1024 dense
slots produced wrong results at >1 worker.  Add the DA_NEED_PAIR merge.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* chore(group): remove temporary RAY_NO_V2/RAY_GRPPROF instrumentation

The binary-agg DA fix lands on the default path (v2 declines CHAR-keyed
binary group-bys -> legacy DA), so the debug env overrides are no longer
needed.  3635/3635 tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(if): parallel elementwise OP_IF fill; route trivial-branch if to eager

exec_if always took the 'selected' lazy-branch path, whose scaffolding
(true-count, id-list build, per-branch gather, scatter) is serial over
ALL rows — every if-projection ran at single-core speed regardless of -c
(100M numeric if: 2.2s at any core count).

1. exec_if_eager: one shared fixed-width elementwise fill, dispatched
   across the worker pool for len >= 64K (SYM sides warm their runtime-id
   LUT serially first — sym.c frozen-table rule, mirrors window.c).
   STR keeps the serial append path.
2. exec_if_selected: bail to eager when both branches are trivial (column
   scan / scalar const) and eager fills the type combination correctly —
   the lazy path only pays off when a branch is an expression worth
   restricting to its passing rows.  Mixed numeric/string shapes stay on
   the selected path (its per-value string conversion).

100M rows local c24: numeric if 1883->310ms, sym if 2012->306ms.
dazzle c48 canonical Q22: 2658->1333ms end-to-end.
make test 3635/3635.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(filter): parallel bitmap->index build in exec_filter and sel_compact

exec_filter ran two sequential 0..nrows sweeps (pass-count and
match_idx build) before its parallel gather; sel_compact rebuilt
match_idx from the rowsel serially.  Both now use the classic 3-phase
compaction: parallel per-chunk/per-seg counts, tiny serial prefix,
parallel fill at disjoint offsets.  Lazy/morsel-backed predicates keep
the sequential sweep.

100M rows local c24: 2-col where-select 143->21.7ms (1.4x -> 6.6x
scaling); if+where 1040->324ms.  make test 3635/3635.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf: parallel where builtin, gather_by_idx, and chunk-task dispatch

- ray_where_fn: 3-phase chunk compaction on the pool (was fully serial).
- gather_by_idx: fixed-width value gathers dispatched over disjoint
  output ranges (null-bit propagation stays serial - shared-word bit
  writes would race).
- exec_filter/where chunk phases now use ray_pool_dispatch_n (one task
  per chunk); ray_pool_dispatch morselizes total_elems by 1024, so
  passing chunk counts gave only ~2 tasks for 100M rows.

100M rows local c24: where 88->25ms, at-gather 80->31ms,
2-col where-select 138->20ms (6.8x).  make test 3635/3635.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(review): harden parallel paths per skeptic review

Blockers (DA binary-agg y-column):
- eligibility now requires a plain numeric/temporal y; nullable
  integer/temporal y stays on the HT path (da_accum_row's pair branch
  has no y-side sentinel machinery - nulls would accumulate as values)
- an FP y with HAS_NULLS sets da_any_nullable so nn[] is allocated and
  the emitter divides by the non-null PAIR count, not the group count

Majors:
- all new parallel gates require pool->n_workers > 0 (a -c 1 pool
  exists with 0 workers; ring fill + atomics + rc_sync were pure
  overhead, and the OP_IF eager reroute lost to the selected path
  serially - the Q22/Q25 c1 regression)
- chunked dispatch_n call sites cap chunks at 1024 = the pool's
  initial ring capacity, so the ring never grows (dispatch_n clamps
  and silently DROPS tasks if ring growth fails -> uninitialized
  prefix entries -> OOB writes)
- sel_compact seg fill switched to dispatch_n over seg-chunks
  (ray_pool_dispatch over segs gave 1 task under 8.4M rows)
- gather_by_idx parallel path guarded by ray_parallel_flag == 0
  (leaf utility, 35+ call sites; nested dispatch would corrupt the
  single-producer task ring)

Nits: stray time.h include, restored v2-gate comment,
RAY_PARALLEL_THRESHOLD symbol in pivot.c.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(group): pair-skip y-side nulls in the legacy HT binary-agg path

Unify grouped binary-aggregate (pearson/cov/scov/wsum/wavg) null handling
with the scalar reducers, the v2 engine and the DA path: a null on either
side of the (x,y) pair now voids the whole pair on the legacy HT route too.

- ght_compute_layout: a nullable y-side sets GHT_AF2_Y_NULLABLE and routes
  the layout to the null-aware accumulators.
- accum_from_entry_nullable: pair-skip before nn++/sums.
- Entry packing canonicalizes integer nulls so the accumulator can see
  them: NaN in F64-packed slots (a (double)sentinel cast previously read
  as a huge finite value — this also fixes nullable-int x beside an FP y),
  NULL_I64 in int-by-int slots.
- Both HT emitters (radix + serial) divided pearson/cov/scov moments by
  the group row count instead of the accumulated pair count — wrong
  results whenever a group carried any null; now divide by nn.
- The all-null-group guards wrote v=0.0 after ray_vec_set_null, so the
  common store overwrote the null sentinel — emit NULL_F64 instead.
- DA eligibility now also rejects a y shorter than the scan (OP_CONST
  vector literal would read out of bounds).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JZwH1gpAeLzDX2bxc4jz6s

* test(agg): cross-path null coverage for grouped binary aggregates

46 assertions for wsum/wavg/pearson_corr/cov/scov over nullable inputs on
all three grouped routes — v2 (plain-scan int key), DA (expression int
key), legacy HT (expression key + nullable-int y; F64-packed and
int-packed entry lanes) — against independently computed pair-skip truth,
for all four x/y type combinations, plus an all-pairs-null group
(wsum 0.0, typed nulls for the ratio/moment aggs) on every route.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JZwH1gpAeLzDX2bxc4jz6s

* chore(review): shared dispatch-safety gate; single filter threshold

- ops/internal.h ray_par_dispatch_ok(): workers + RAY_PARALLEL_THRESHOLD +
  ray_parallel_flag reentrancy check in one place; applied at exec_filter,
  sel_compact, exec_if_eager and the where builtin (local copy there —
  builtins.c cannot include ops/internal.h).
- exec_filter: gate and table fallback derive from one row count
  (fidx_rows); note that pass_count from the parallel count phase is
  consumed by exec_filter_vec for vector inputs.
- group.c: drop the never-read da_ctx_t.agg_pair_mask plumbing.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JZwH1gpAeLzDX2bxc4jz6s

* chore(par): shared dispatch predicate, ring-cap constant, parallel-path test

Follow-ups from the audit's non-blocking notes:

- core/pool.h ray_pool_par_dispatch_ok(pool, n, min_elems): the single
  home for the dispatch-safety predicate (workers + element threshold +
  ray_parallel_flag reentrancy).  The three hand-copies in ops/internal.h,
  lang/eval.c and ops/builtins.c are gone; all six gates call the shared
  one.
- RAY_POOL_INIT_TASKS in core/pool.h replaces the hardcoded 1024 at the
  three dispatch_n chunk caps and in ray_pool_create, with a
  _Static_assert tying it to RAY_POOL_MAX_TASKS — lowering the initial
  ring capacity can no longer silently desync from the caps that rely
  on it.
- test/rfl/query/parallel_paths_large.rfl: 200k-row coverage of every
  new pool-parallel branch (where, gather-by-index, exec_filter,
  sel_compact, OP_IF numeric and SYM fill incl. the serial LUT warm-up)
  against closed-form expected values.
- RAY_F32 dropped from if_type_eager_ok's whitelist (if_fill_range has
  no F32 case; unreachable today, kept unreachable deliberately).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JZwH1gpAeLzDX2bxc4jz6s

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
binary_range's OP_IDIV kernels for narrow integer output (I64/I32/I16/U8)
computed `(intN_t)floor(lv/rv)` guarded only by `rv != 0.0`. That guard
does not catch a NaN operand (`NaN != 0.0` is true), so a null float input
yields `lv/rv == NaN`, `floor(NaN) == NaN`, and the subsequent cast to an
integer type is undefined behavior — UBSan: "nan is outside the range of
representable values of type 'long long'" at exec/expr_binary_f64_idiv_mod.

Route the cast through the ray_cast_f64_to_{i64,i32,i16,u8}_null helpers,
which map NaN to the canonical null sentinel (NULL_I64/I32/I16, 0 for the
non-nullable U8) and saturate out-of-range finite results. The null
post-pass (propagate_nulls_binary) already overwrites these positions, so
final values are unchanged — this only removes the UB and yields the
correct sentinel in-buffer. Mirrors the already-safe F64-output IDIV arm
(ray_f64_fin) and the sibling casts fixed in "avoid f64 null casts to
integers"; depends on those helpers.

Co-authored-by: Evgen Byelozorov <[email protected]>
Co-authored-by: Evgen Byelozorov <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
belowzeroff and others added 28 commits August 25, 2026 19:26
* fix(join): compare GUID keys by full cell bytes

* fix(join): reject unsupported asof window eq keys

---------

Co-authored-by: Anton Kundenko <[email protected]>
* fix(agg): keep sum/prod list reductions exact and UB-free for i64

Reducing a boxed (list ...) of integers mishandled large i64 values:

- sum: `isum += elems[i]->i64` (and the mixed-int fallback `isum += v`)
  accumulated with signed arithmetic, which is UB on overflow. Confirmed by
  UBSan on (sum (list 9223372036854775807 1)) at src/ops/agg.c:464.
- prod: read each i64 atom via `(int64_t)as_f64(atom)`, losing precision
  above 2^53 (e.g. (prod (list 9007199254740993 1)) -> ...992) and hitting
  a float->int cast UB when the value rounds to >= 2^63.

Accumulate integers via unsigned math (well-defined wraparound) and read i64
atoms directly, mirroring the unsigned idiom already used in prod's multiply
and the UB-free typed-vector reduction path. Adds regression coverage in
test/rfl/agg/{sum,prod_builtin}.rfl.

* fix(agg): wrap every sibling sum/prod integer accumulator; reject parted TIMESTAMP

Review follow-up: the boxed-list fix left the sibling sum accumulators in the
same dispatch family carrying the identical signed-overflow UB. Extract
wrap_add_i64 / wrap_mul_i64 (core/types.h; codegen-neutral — they inline to a
bare add/mul and don't inhibit autovectorization) and apply them everywhere:

- ray_sum_fn: the narrow/TIME vector arms and the boxed-list loop (collapsing
  the duplicated i64/other branches into one wrap-accumulate); drop the dead
  RAY_TIMESTAMP vector arm, which agg_type_admitted() rejects before dispatch.
- ray_prod_fn and agg_parted_prod: same wrap idiom via the shared helper.
- agg_parted_sum: wrap the segment accumulation and route admission through
  agg_type_admitted, so a parted TIMESTAMP column is rejected exactly like a
  flat one (previously it was silently summed and returned a timestamp).
- group.c scalar_sum_i64_fn / scalar_sum_linear_i64_fn (the hot select-scan
  path, incl. its bias/coeff multiplies) and the lang/eval.c affine-sum fast
  path (sum(v + c) folding).

Adds regression coverage for the select-scan (scalar, linear, by-group) and
affine fast paths in test/rfl/agg/sum.rfl and test/rfl/arith/sum_affine.rfl.

* fix(agg): reject unsupported parted sum inputs

* fix(agg): wrap remaining i64 sum accumulators in group.c against overflow

agg.c already reduces sum/prod through wrap_add_i64/wrap_mul_i64, but the
sibling group.c paths still did signed `+= v` / `bias * cnt`, which is UB
on overflow and can diverge from the serial result. Route every integer
sum accumulator through the wrap helpers: dense and radix phase-3 emit,
the affine bias, the scalar and DA row accumulators (including the linear
term path and cached strlen), the sp-dyn dense/probe emitters, and the
cross-worker merges. prod already used unsigned-cast multiply and is left
as-is.

Now worker-local partial sums and the final cross-worker merge share the
same wrap semantics, so a parallel sum matches its serial counterpart
exactly at the int64 boundary.

Add coverage: parallel-threshold sum (worker partials + merge), the
linear-expression sum path, and a parted i64 sum wrap.
…rse (#435)

fast_date() bounded the day only at d<=31, so a well-formed "YYYY-MM-DD"
naming a day that cannot exist in its month — "2024-02-31", "2024-04-31",
a non-leap "2023-02-29" — passed validation and civil_to_days() then
rolled it into a *different* real day ("2024-02-31" -> 2024.03.02),
silently corrupting the value instead of nulling it. fast_timestamp()
reuses fast_date() for the leading date, so typed [TIMESTAMP] ingest was
affected too.

Validate the day against the actual, leap-aware length of the month. The
month is still range-checked before the days-in-month lookup, so the
table index stays in bounds. This mirrors the strict (as 'DATE str) cast
(#382): well-formed dates — including the leap day 2024-02-29 — still
parse, while impossible ones now become null, matching how the reader
already nulls out-of-range months and days.

Extend test/rfl/io/csv_types.rfl with calendar-validity coverage for
[DATE] and [TIMESTAMP], including leap-year edge cases (2100 not leap,
2000 leap).

Co-authored-by: Anton Kundenko <[email protected]>
* fix(storage): reject unsafe splayed column names

* refactor(storage): drop unreachable in-loop name check, fix stale comment

splay_validate_persisted_names() at the top of splay_save_impl already
rejects every unsafe column name, so the duplicate splay_col_name_safe
check inside the column-write loop was unreachable dead code that
misleadingly read as the live enforcement path. Remove it and note where
enforcement actually happens. Also fix the ".sym" collision comment, which
still said dot-led names are "skipped below" — they are now rejected
up-front.

No behavior change; the splay name-rejection tests are unchanged and green.

---------

Co-authored-by: Anton Kundenko <[email protected]>
* fix(builtins): reject out-of-range numeric string casts

* fix(builtins): reject the null sentinel in i16/i32/i64 string casts

The narrow-range checks admitted the exact minimum (INT16_MIN / INT32_MIN /
INT64_MIN), but those bit patterns are the NULL_* sentinels, so a scalar
string cast of the boundary silently produced a typed null —
(as 'i32 "-2147483648") -> 0Ni, (as 'i16 "-32768") -> 0Nh — while the
vector path kept the value. Reject the sentinel with a domain error
instead.

The string->vector cast (cast_vec_numeric) parses each element through the
same scalar cast, so vectors now reject it consistently too — eliminating
the atom/vector divergence rather than documenting it. This matches the
PR's rule that string ingest is loud, while numeric narrowing still nulls
a produced sentinel (the documented narrow-int rule).

Tests (type/as.rfl): flip the two boundary tests that pinned the old 0Nl
aliasing, add the i64 sentinel plus MIN+1/MAX boundaries, and pin the
vector rejection.

---------

Co-authored-by: Anton Kundenko <[email protected]>
…429)

* fix(format): bound fmt_ensure growth; loud failure past 2GiB output

Formatting more than ~1GiB of text into the shared formatter hung the
process forever at 100% CPU.  fmt_ensure doubled its int32 capacity until
it covered len+extra; once cap reached 2^30 one further doubling
overflowed int32, wrapped through negative to 0, and the loop could never
terminate.  Reproducer: (println (til 120000000)) — UBSan flags
format.c:68 signed overflow, then the process spins indefinitely with
zero output bytes.  Every ray_fmt consumer was exposed: println/show,
IPC message rendering (ipc.c), timer messages, csv error context.

Compute the requirement in int64 and fail loudly instead:

- need > INT32_MAX (or negative extra) -> fatal error message + abort;
  a silent hang is worse than a loud stop, and SIGABRT lets the crash
  handler dump diagnostics.
- clamp the doubling to INT32_MAX so a requirement between 1GiB and
- 2GiB now completes in one right-sized allocation (the old code UB'd
  exactly there).
- check the ray_alloc result in fmt_init/fmt_ensure: a NULL/error block
  used to be dereferenced unchecked deep in OOM.

The fmt_* helpers are all void, so there is no caller to return
ray_error to; abort is the honest terminal path.

Verified empirically on the UBSan build:
- til 120000000 -> 1088888892 bytes printed, exit 0, no sanitizer
  reports (previously an infinite hang);
- til 260000000 (>2GiB) -> "formatted output exceeds the 2GiB buffer
  limit" + fatal SIGABRT diagnostics (previously the same hang).

No unit regression is added deliberately: any repro needs >1GiB of
formatted text (~40s wall, multi-GB RSS), which is out of scale for the
rfl test suite.

* fix(format): recoverable error on >2GiB/OOM growth instead of abort()

fmt_ensure aborted the process on the 2GiB int32 buffer ceiling or a
failed ray_alloc. ray_fmt runs on IPC-server threads formatting
client-supplied values (a client (println <huge vector>), or the
query-log of a raw payload), so that abort() was remotely triggerable —
one client could take down every connected session. Make it recoverable:
fmt_buf_t carries a sticky error flag that fmt_ensure sets, the append
primitives no-op once it is set, and fmt_to_str surfaces it as a
RAY_IS_ERR (every ray_fmt caller already checks that). No abort() remains.

Also from the review:
- Move the negative-length guard ABOVE the fast-path return. `need <= cap`
  returned first for any negative extra, so the wild-memcpy path this
  change targets was still open.
- Widen the length casts (fmt_puts / fmt_putn and the ray_str_len call
  sites, plus fmt_ensure's parameter) to int64, so a >=4GiB or
  [2^31,2^32) argument hits the loud limit instead of wrapping int32 to a
  small positive count and emitting a truncated prefix.
- Drop the dead RAY_IS_ERR(block) alloc checks (ray_alloc only returns
  NULL) and the now-unused <stdlib.h> that was added for abort().

Full ASan+UBSan suite green; normal and moderately large formatting
round-trip unchanged. The >2GiB boundary is verified by inspection (a
suite test would need a multi-GB allocation).

---------

Co-authored-by: Anton Kundenko <[email protected]>
)

* fix(sort): give nulls one place in the order, not five

Where a null sorts was spelled out separately in five places, and they
did not agree.  The comparator derived it from `desc`, sort_indices_ex
and the query builder from `!desc`, the fused top-k hardcoded its own,
and the take path passed `desc` straight through as the flag.  Which one
answered depended on the row count, since a small input takes the
comparison path and a large one the radix path, and on the column type,
since SYM, STR and numeric arms are separate.  So the same query over
the same data changed its answer as the table grew, and `(asc v)` over a
vector disagreed with `select {asc: v}` over that column.

A null is now the smallest value everywhere: ascending puts nulls first,
descending last.  sort_nulls_first in ops/internal.h is the only place
that says so, and the paths take their default from it.  Nothing in the
type system enforces that — a new path can still spell the rule out for
itself, exactly as these five did — so it is a convention held by having
one obvious place to ask, not a guarantee.

That default is what the bare verb, the radix arms and the rotate step
already did, so the answers that change are the query sort, the fused
top-k and take.  A top-k over a null-bearing column now returns the
nulls, since they are the smallest rows; the tests and comments that
recorded the old answers as the rule are updated with it.

The array of per-key defaults the merge fallback used to allocate is
gone: a NULL nulls_first already means "the default for this direction",
which removes an allocation and its out-of-memory path.

The fused top-k still fills its per-key flag from the direction rather
than from the caller's, since no caller can express one yet.  Threading
an explicit NULLS FIRST/LAST clause through the query language would
have to reach it, or it becomes the sixth place with its own opinion.

Fixes #417

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(sort): pin null placement across paths, sizes and types

Asks the same question of every path that can answer it: the comparison
path and the radix path, SYM, STR and numeric columns, the bare verb and
the query sort, and filter+top-k, which runs the fused comparator rather
than a sort.  Asking at one size or of one type is what let the
disagreement live: the paths are chosen by row count and column type, so
a single-size test passes whichever way the policy falls.

A first version of this file passed without the fix.  Empty SYM and STR
values are nulls that are also ordinary in-band values — sym id 0 and a
zero-length descriptor — so they sort smallest on the payload alone and
land first whatever the policy says.  Only an out-of-band null, which
numeric columns have, is placed by the policy and can show it moving.

That leaves a gap this file does not close: the SYM checks here would
pass under either policy, so the case in #417's title — a SYM column
whose nulls change ends with the row count — is documented rather than
pinned.  Pinning it needs a SYM column carrying HAS_NULLS, which no
literal or CSV read produces.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(window): take the null default from the shared rule too

The window sort picks between three paths by row count, and one of them
spelled the placement out for itself: the radix encode above 64 rows
passed the direction as the flag, while the insertion and merge paths
take the shared default.  Before this series all three agreed, because
the shared default was the same thing spelled out; after it they would
not have, which is the row-count-dependent split being removed here in
the first place.

Not user-visible: a window sorts by its partition keys only, and a group
is a run of equal keys, so the null run reads the same from either end.
The tests added with it pin that the paths agree on which rows are null
across the threshold that chooses between them, not the placement, which
this shape cannot show.

Found by the audit on #430, which read the three paths against each
other; the new test file had not covered window sorts at all.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(sort): make top/bot agree with the sort they fall back to

topk_take_vec answers `top`/`bot` over a bare vector two ways: a bounded
heap while k < len, and the full sort once k reaches it.  The heap
spelled the null placement out for itself, so the two disagreed — `(bot
v 3)` over a null-bearing vector returned the smallest non-nulls while
`(bot v 5)` on the same five-element vector led with the nulls, because
the second call fell through to the sort.

That is the contract from #417's discussion: take is a prefix of the
sorted order.  Where the prefix comes from must not change what it
contains, so the heap now takes its placement from sort_nulls_first like
everything else.

The pins are written as differentials — the taken result against the
prefix of the untaken one — for the query path and for top/bot on both
sides of the k < len switch.  Stated that way they hold whatever the
placement is, and they fail on the old code: `(bot v 3)` gave [1 2 3]
against a sorted prefix of [0N 0N 1].

Found by the audit on #430, which noticed the comment there claimed to
match the sort defaults and no longer did.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(sort): stop ray_sort_indices claiming the old null default

The header still told callers that a NULL nulls_first meant nulls last,
which is what the rest of this series stopped being true.  A comment
stating a rule the code no longer follows is how the five separate
placements got written in the first place, so it is worth the one line.

Reported by the audit on #430 as a non-blocking note.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(sort): keep a nullable float key out of the packed multi-key encode

A multi-key sort packs its keys into one 64-bit word when they fit, and
that packing has no null leg: a float null is NaN, whose bits encode
above every real number, so it lands last on ascending whatever
sort_nulls_first says.  The other types hide this — their null is the
type's minimum sentinel, which is already where the rule wants it — so
only a float key shows it.

Before this series every path agreed on nulls-last, so the packing
agreed too by accident.  Changing the comparator's default left the
packed encode behind, and a multi-key sort with a float key then placed
nulls one way below 64 rows and the other way above — the row-count
dependence this series exists to remove, reintroduced by it.

A nullable float key now declines the packing and takes the
rank-then-compose fallback, which ranks through sort_indices_ex and is
null-aware.  Teaching the packing a second placement would be the other
way; it is not worth a second encoding of the rule.  F32 cannot reach
this path at all (multi-key float already declines radix) and its
single-key arm reads the flag.

The tests read the float cases out in full rather than probing the ends,
and carry both signs and zero, since the encode's bit flip is
sign-dependent.  Two spans are covered deliberately: with only
non-negative reals the packing runs, which is the path under test; add a
negative and the span no longer fits, so the key declines for a
different reason and the answer must still match.

Also here, from the same review: five comments still taught the old rule
— sort_indices_ex's header contract, the fused top-k planner gate, the
sort-index builder and its idx_fresh_nonull rationale, and the
radix_encode_ctx_t field doc, which described the flag as float-only
when every typed arm reads it.  Stale policy comments were the mechanism
of the original defect, so they are part of it.

group.c no longer claims the grouped top/bot kernels agree with the
standalone one.  They do not, and did not before: grouped skips nulls
while the standalone orders them, so (bot v 2) over [3 0N 1 0N 2] is
[0N 0N] standalone and [1 2] grouped.  Both are defensible — ordering
places a null, aggregation ignores it — but the comment asserted a
parity that never held.  The behaviour is left alone.

And a DESC top-k test that actually puts a null in the result: every
existing case has more non-nulls than k, so the null leg was only ever
exercised to reject.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
…ct (#437)

The general case was fixed with #414 — an unknown column reference gets
an invalid-scan marker that ray_execute rejects.  Two ways around it
survived, and both reproduced #428 in full: a projection emitted under
the wrong label, and an aggregate answering its neutral element.

`_dist` was exempt from the marker unconditionally.  The exemption is
needed — a rerank produces that column while the query runs, so it is
genuinely absent when the query compiles — but it applied just as well
where no rerank exists to produce it.  It is now conditional on the graph
actually holding one.

`nearest:` was missing from the skip list in the loop that names output
columns.  That walk is positional, so a keyword it fails to skip eats an
output slot and every name after it lands one column early.  It is
counted out where the outputs are counted, which is why only the naming
disagreed.

Both were verified to reproduce the report before the change: the
projection case returned a two-column table whose second column carried
the third column's data under the second column's name.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…ng them (#438)

dl-program wrapped a raw dl_program_t* in a plain -RAY_I64 atom with no tag,
and dl_unwrap_program reinterpreted ANY i64 as that pointer. So a one-line
expression — (dl-free 1), (dl-stratify 1), (dl-query 1 'x), (dl-eval 1),
(dl-add-edb 1 ...) — dereferenced an attacker-chosen address and crashed
with SIGSEGV. On a server that evaluates client input over IPC this is a
remotely-triggerable crash, and a chosen integer is an arbitrary-pointer
free/deref (memory corruption), not merely a DoS.

Tag the handle atom with RAY_ATTR_DLPROG (mirroring the RAY_ATTR_GRAPH /
RAY_ATTR_HNSW handle scheme) and verify it in dl_unwrap_program, so a plain
integer or an arithmetic copy (which does not carry attrs) is rejected with
a type error. dl-free clears the tag and zeroes the pointer on free, keeping
its idempotent-false contract for a genuine double-free while rejecting
forged handles. The bit reuses 0x20 (RAY_ATTR_SORTED / ATTR_QUOTED), which
is vector / -RAY_SYM scoped and never read on a -RAY_I64 atom, and no
free-path touches 0x20 — so there is no finalizer collision.

Also closes the arithmetic-copy double-free (a copy loses the tag, so only
the original frees) and the snapshot/ser-de-restored stale-handle crash (the
restored atom loses the tag and is rejected). Adds forged/copied-handle
coverage to datalog_coverage.rfl.

Co-authored-by: Anton Kundenko <[email protected]>
…gression (#431)

exec_elementwise_unary answers OP_ISNULL for every input type before the
typed dispatch (since bfb5b38), leaving the I64->BOOL ISNULL kernel and
the ISNULL arm of the null-propagation pass unreachable. Delete both so
the early-out is the single ISNULL path.

Add test/rfl/regress/load_select_isnull_mask.rfl pinning the original
load->select symptom: a splayed table with a file .sym domain queried
after a load interned new symbols fell off the fused path and returned
an uninitialized ISNULL WHERE mask (0/539/570 of 1000 rows). Neither
the original fix nor bfb5b38 carried an end-to-end repro.
…re (#436)

* fix(store): let a mapped string column's pool own the region they share

A splayed string column and its pool are written contiguously and mapped
together, and every result gathered from such a column shares the pool by
reference — filter, take, drop, the four joins and the head/tail slices
all reach it through col_propagate_str_pool, which retains it.

That retain was a promise the memory could not keep.  The region belonged
to the COLUMN: freeing the column unmapped the pool along with it, and
every result still holding that pool was left reading unmapped pages.
The refcount and the ownership disagreed, so taking a reference bought
nothing.  Reported as a double free; it is not one — the pool is freed
once, by a mapping teardown that never consulted it.

The pool now owns the region and the column holds an ordinary reference
to it, so the mapping ends when the last block living in it is freed.
mmod grows a third value for this, rather than overloading the existing
"borrowed, free does nothing" — that one has other users, and conflating
them would hand somebody else's mapping to this teardown.  The descriptor
lives on the heap because it must outlive the region it describes.

Two ordering points, both load-bearing.  ray_free reads what the teardown
needs before releasing children, since releasing the pool can unmap the
page the header itself sits on.  And ray_release_owned_refs now returns
after releasing a string pool instead of falling through, exactly as its
symbol-domain arm already did, for the same reason — the checks after it
never applied to a STR vec anyway.

The test drives every shape that shares a pool, each in its own process:
the fault lands at teardown, so a process cannot observe its own.  The
result is bound to a name in every case — a temporary dies before the
column it came from and never reaches the dangling pool, which is why an
inline (print (take …)) passes even unfixed.  Operations that build their
strings afresh — asc, distinct, group-by — were checked and are
unaffected.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(store): stand down the child shapes where no interpreter is built

The sanitiser flavours build only their own test runner, so ./rayforce is
absent there and every child command failed with "not found" rather than
with an answer.  The tsan job runs a name-filtered subset, and this file
matched it.

Each child command is now guarded on the binary existing.  The debug and
release runs build it and carry the coverage; where it is missing the
shapes stand down, which is honest — they test a teardown that only a
separate process can show, and there is no process to start.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(heap): an indexed column still owns its domain or pool

Attaching an index takes aux bytes 0-7 for the index pointer and leaves
bytes 8-15 alone, where a SYM column keeps its resolution domain and a
STR column its pool: attach_finalize preserves them there deliberately,
and ray_index_release_saved is a no-op, so the reference taken when they
were attached stays the column's.  Both refcount hooks returned before
reaching that field.

A copy of an indexed column therefore took no reference.  Shedding the
index restores aux and makes the copy an ordinary owner, so freeing it
released a reference it never held — the domain's count reached zero
while the store's own column was still reading through it, the symbol
file was unmapped, and every symbol in that column came back empty.  The
same skip leaked the reference outright when the column was freed while
still indexed.

Both hooks now go on to the pool or the domain.  A numeric indexed
column is unaffected: bytes 8-15 are NULL there and the type test
already guarded it.

Only reachable through a FILE domain, so the test spawns a second
rayforce to read the store: retain and release are no-ops on the
immortal runtime domain, and a process that has interned the symbols
itself — which writing the store does — reads its own store back on that
one and cannot see it.  A first version of the test missed this and
passed against the unfixed tree.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(store): pin the mapping count across loads of an indexed column

.db.splayed.set attaches a dict index to any string column of 65536 rows
or more, so a mapped large column comes back carrying a passenger index —
and the arm that handles an indexed column returns before it reaches the
pool.  While the column unmapped the region itself that cost one
reference; with the pool owning the region it costs the whole mapping on
every load, which is the shape these tests were too small to reach: three
rows is nowhere near the threshold.

Measured rather than asserted structurally, since the symptom is a count
that does not come back down: five load-and-drop cycles must leave the
mapped-byte total where they found it.  Without the release it grows by
the size of the file each time — just under seven megabytes over five
cycles for this fixture.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(store): give a mapped column its own hold on the region it lives in

The pool owned the shared mapping alone, and the column reached it only
through str_pool — the one pointer a mutation replaces.  str_pool_cow
deep-copies a mapped pool before appending and releases the original, so
that release ended the region while the column was standing in it: the
next write, to the column's own header, hit an unmapped page.

Both blocks now hold a reference.  The pool keeps the descriptor in its
header as before; the column, whose address is what the region was mapped
at, finds its own by that address.  Until a mutation the pool pointer
still leads there, so the ordinary path reads the descriptor straight
from it and takes no lock at all; only a column that had its pool swapped
registers, which is why the table is normally empty.  Bucketing is by the
low bits of the page number because that is what varies between
consecutive mappings — forty mapped string columns landed in forty
distinct buckets, none chained.

The reference alone would not have been enough.  With the descriptor
reachable only through the pool, a swapped column could never drop what
it held, and the crash would simply have become a leak of the whole
mapping.  Finding it by address is what makes the hold releasable.

Freeing a registered mapping now takes its length from the descriptor
instead of re-deriving it from type and length — which also ends the read
of an already-released pool that derivation depended on, and the drift
between the mapped size and the rounded one.

Also from the review: the refcount is atomic, since a column and a
selection sharing its pool can be freed on different threads; the
descriptor is a typed union member rather than a raw offset into aux; the
indexed arms of the retain and release hooks fall through to the string
and symbol arms below instead of repeating them; and col_save_impl
scrubs the pool header's aux, which otherwise wrote a live heap address
into the file and carried it into the next generation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Editor tooling (e.g. the tree-sitter-rayfall grammar in #441) needs
semantic completion of names the engine knows at runtime — functions,
user bindings, tables — which a grammar alone cannot provide. The REPL
already computes this, but the logic lived entirely in the terminal
client and was unreachable over IPC.

Expose `.repl.complete "prefix"` as a read-only (RAY_FN_NONE) verb that
returns a sorted sym vector of builtins, keywords, and user bindings
whose name begins with the prefix. It reuses ray_env_lookup_prefix — the
same primitive the terminal client's tab-completion draws from — so the
two cannot drift. History-word completion is omitted: it is client-local
and meaningless to a remote caller.

Because it runs against the caller's live session, an editor gets the
actual functions and tables bound there, not a static keyword list.

Follow-up: context-aware column completion (`from:`-scoped), which the
terminal already does locally.
…444)

The table decoder set ncols = cols->len but bounded the rebuild loop by
min(cols->len, schema->len), so a crafted frame whose schema-name count and
column count disagree was silently accepted as a truncated table (extra
columns dropped, or extra schema names ignored) instead of being rejected.

Reject up front when schema->len != cols->len with a domain error, before
building the table.

Adds a serde.rfl regression that splices a 2-name i64 schema with a 1-column
list into one table payload and asserts de rejects it.
.ipc.open parsed the port field with atoi(), which stops at the first
non-digit — so "127.0.0.1:1abc" was accepted as port 1 and a connection was
attempted instead of rejecting the malformed field. ("abc" and "70000"
already errored: atoi("abc")==0 fails the <=0 check and 70000 fails >65535, so
only the numeric-prefix case slipped through.)

Parse with strtol and require the whole field to be digits (no trailing
characters), keeping the 1..65535 range check plus ERANGE. Malformed ports now
return a domain error at parse time, before any socket work.

Adds "1abc" / "19876x" coverage to system/system_branch_cov2.rfl.
System commands write directly to stdout, which is block-buffered when
the REPL is driven over a pipe. Flush once at the shared command
boundary so handler output and errors are visible before the REPL waits
for more input.

Co-authored-by: GPT-5 <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
…450)

* fix(query): reject atom predicates before the filter's morsel walk

A scalar where-subject (e.g. (like "keep me" "*keep*")) evaluates to a
BOOL atom; exec_filter walked it with ray_morsel_init before the length
check, and the element-size lookup indexed ray_type_sizes by the negative
atom type — a global out-of-bounds read, fatal under ASan on toolchains
that redzone the neighboring global.  Reject atoms at entry with the same
length error class the late check produced.

Fixes #448.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN

* fix(sort): keep the composite prescan's range math in the unsigned domain

kmin can be the i64 null sentinel, so kmax - kmin overflowed signed
arithmetic, and the bit-width loop evaluated 1<<64 before its bound
check.  Same routing as before (the wrapped difference is the same
value); the UB is gone.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN

* test(aof): don't pass NULL to memcpy for an empty payload

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN

* build(debug): make UBSan errors fatal in the test build

UBSan's default is print-and-continue, so the three latent errors the
suite exercised were reported into CI logs and swallowed; issue #448
only surfaced because a newer linker layout let ASan trap the same read.
With -fno-sanitize-recover=undefined the suite fails on the next one.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN
… capacity (#451)

ray_scratch_arena_push derived the end of its bump window from
BSIZEOF(blk->order).  That is only the block size for buddy blocks.  A
push at or above RAY_HEAP_POOL_ORDER is served by heap_alloc_direct,
which maps the block at its exact page-rounded size and tags the header
with the RAY_ORDER_DIRECT sentinel — an order deliberately above every
real one so the buddy paths skip it.  Read as an order, that sentinel
describes a 512 GB block, so the arena believed it had unbounded room
in a mapping sized to the one request that triggered it.  Every
subsequent push was then handed an address past the end of that
mapping, and the first write to it faulted.

Nothing bounded the fallout to the arena: the caller writes through the
returned pointer, so the failure is a wild store into unmapped address
space, reported as a SIGSEGV in whichever loop happened to run first.

The concrete path was sorting a SYM column whose domain vocabulary runs
into the millions.  build_enum_rank pushes an id array, then a pointer
array, then two more; once one of them crosses the direct threshold the
next push lands outside the mapping and the rank-building loop dies on
its first store.  Small vocabularies keep every push inside a buddy
block, which is why this only ever showed up at scale.

ray_block_data_bytes already answers the capacity question for both
block kinds; use it, and anchor the window at the data pointer rather
than the header so the arithmetic no longer depends on the header size
either.  For buddy blocks the result is byte-identical to before.

The test allocates one backing past RAY_HEAP_POOL_ORDER, asserts the
window stops at the block's real capacity, and checks that the push
after it takes a backing of its own instead of being carved out of a
block with nothing left.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
… pages to the OS (#446)

* fix(mem): hand a cross-thread free back to the heap that owns the block

A block freed by a thread that did not allocate it was pushed onto the
FREEING heap's foreign list and left there.  Only an explicit ray_heap_gc()
ever walked that list and returned the blocks to their owners, and the IPC
server never calls one.  A repeated select with a composite `by:` key
therefore parked its whole per-group allocation volume on the connection
thread; the workers that owned that memory started the next execution short
by exactly that much and called heap_add_pool for a fresh 32 MB pool each
time, growing the server without bound until RAY_MAX_POOLS turned it into an
OOM (issue #439).

ray_free now resolves the owner through the pool header and the heap registry
and pushes the block onto the OWNER's list with a CAS; the owner takes the
whole list back with one atomic exchange on its allocation slow path, before
it is allowed to map another pool.  A pool can no longer be added while the
heap's own memory sits unclaimed, so the growth is impossible rather than
merely collectable, and no collector call is involved.

The unlocked registry lookup on the free path needs every registered heap to
outlive the blocks it owns, so a worker thread that exits now abandons its
heap — still registered, pools and slab caches intact — instead of
unregistering and munmapping it underneath a lookup already in flight.  The
next worker thread to start adopts it.  ray_heap_destroy keeps the real
teardown for process shutdown and single-threaded test teardown.

Because every block on a heap's foreign list is now its own, the drain needs
no owner lookup, no registry access and no idle-worker gate, and three
workarounds for the old accumulate-locally design go with it: the pass that
returned foreign blocks off the local freelists, the registry-wide foreign
scan and purge in the oversized-pool reclaim (a queued block already shows up
as a shortfall in that pool's free-byte sum), and the cross-heap foreign
splice in ray_heap_destroy — along with the list-tearing hazard those walks
carried.

The call to heap_flush_foreign(h, false) in ray_alloc had always returned
immediately; the drain replaces it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(mem): unlink a swap-backed pool's file as soon as it is mapped

The file was unlinked at heap teardown, which a heap no longer reliably
reaches: a worker now abandons its heap for the next thread to adopt
instead of destroying it, and an abandoned heap runs no teardown at all.
A worker that had fallen back to a disk-backed pool therefore stranded its
tempfile until the process exited.

Unlinking right after the mapping succeeds removes the whole question. The
mapping holds the inode, so the blocks stay reserved for as long as the
pool is in use and the kernel reclaims them on munmap or at process exit —
and no path out of the heap, teardown or not, can leave the file behind.
The pool entry keeps a NULL path, which teardown already skips.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(mem): return free pages to the OS after the process goes quiet

Free blocks keep their physical pages so that the next query reuses them
without faulting, and the collector deliberately ages a block before
releasing it for the same reason.  The consequence is that a process which
ran one heavy query holds its peak footprint for the rest of its life.  The
memory is free and reusable — it is simply unavailable to anything else on
the machine.

Add a decay with no background thread, no queue and no task object.  A unit
of work (a statement, an IPC request) stamps a coarse timestamp when it
starts; the two points that already exist at the end of a unit of work —
the statement boundary and the event loop between wakeups — compare that
stamp against a threshold.  Past the threshold, one un-aged sweep drains
every heap's foreign list and slab cache and hands back the pages of every
free block; short of it the check is a relaxed load and a subtraction.

The threshold is what distinguishes a workload that has stopped from the
gap between two iterations of a hot loop, where releasing would drop
exactly the pages the next iteration faults back in.  RAY_HEAP_DECAY_MS
overrides it: negative disables the decay, 0 releases at the first
maintenance point after any work.

The event loop bounds its wait by a pending decay the same way it already
bounds it by the next timer, so an idle server notices without anything
polling it; once the sweep has run nothing is pending and the wait goes
back to indefinite.

Sweeping heaps other than the caller's is sound because the sweep runs only
when ray_parallel_flag is 0: the dispatcher clears the flag after every
worker's pending-- is visible, and a worker between pending-- and sem_wait
claims tasks and waits without allocating or freeing.  A cross-thread free
may still push onto a foreign list concurrently; the drain takes the list
with one atomic exchange and leaves later arrivals to the next sweep.
Draining is what makes the sweep worth doing at all — in a server the main
thread frees the results of a parallel query, so most free bytes sit on the
owning worker's foreign list rather than on any freelist.

Unlike the collector's incremental page-release pass this sweep carries no
visit or release budget: that budget exists because the collector runs
inside a workload and must not become an unpredictable pause, and the decay
by construction only runs when there is no workload to pause.

ray_heap_release_pages keeps its synchronous, un-aged contract for the join
OOM fallback, which needs pages back immediately rather than eventually.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(mem): arm the idle decay when a startup script hands over to the poll loop

A file is evaluated as a single unit and, unlike a REPL line, has no decay
check after it.  Nothing else in that path stamps the activity clock, so a
process that loaded its data from a startup script and then served on the
poll loop never had a pending decay to notice, and the load's temporaries
stayed resident for the life of the process.

Stamp at the END of the file rather than the start.  A script that exits
has nothing to hand back either way; a script that starts a server leaves
the poll loop with a decay due one threshold later.  Stamping at the start
would instead arm a check that the script's own (.sys.gc) calls would
service partway through its own run, which is precisely what the threshold
exists to prevent.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(mem): clamp the decay threshold so the deadline cannot overflow

The threshold is read from the environment and added to a millisecond
timestamp, so a large enough value wrapped the sum and made the deadline
land in the past — a knob meant to postpone the sweep would have brought it
forward instead. Any negative value now disables the decay outright, and a
positive one is capped at a week, which for this purpose is already the
same as never.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(core): let the idle decay bound only an unbounded poll wait

ray_poll_run_for carries the caller's own deadline and runs a single pass
of the loop, so shortening its wait by the decay deadline returned from it
early having done nothing — a timer the caller was waiting on had not come
due yet, and the call reported that it never fired.

The decay only ever needed the indefinite wait, where a process sitting on
the poll loop is a process doing nothing and this is its one chance to
notice. A bounded pass already has a reason to wake and is not idle by any
definition, so it no longer consults the decay at all.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(mem): measure the gap between units of work, not their duration

Three defects in the idle decay, all from the same review.

The activity clock was stamped at the START of a statement and of a request
frame, while the check runs at the END. What that measures is the unit's own
duration, not the quiet before it, so a loop of units longer than the
threshold swept after every one of them — handing back exactly the working
set the next was about to fault in, forever. The clock is now stamped once
the work is done, and the check reads it before the new stamp, so the gap it
sees is the time the process actually sat idle. The script path already did
this and said why; the other two now agree with it.

A fired timer is work, and on a timer-driven server it is the only work
there is. Nothing stamped it, so the decay saw an idle process in the middle
of a workload; worse, having disarmed itself it never looked again, and
everything accumulated afterwards stayed resident for the life of the
process. ray_timers_fire_expired reports how many it ran and the poll loops
stamp when that is non-zero.

The threshold was re-read from the environment on every check — twice per
poll wakeup, for a value that cannot change after exec. It resolves once now,
behind a setter that also gives the tests a way to drive the policy without
re-exec, which is what they were using the environment for.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(mem): keep a block whose owner has left the registry

Two accounting holes the owner-routed free opened, both reachable today
only through the merge path.

ray_heap_merge drains the source heap's foreign list into the destination,
but those blocks are still charged in the source's bytes_allocated, which
the destination inherited a few lines above. Coalescing them without taking
the charge off left it standing for good, so the reported figure climbed by
every merged pending block and never came down.

ray_free dropped a block outright when its owner was not in the registry,
on the reasoning that a torn-down heap took its mapping with it. That is
true of a destroyed heap and false of one waiting to be merged:
ray_heap_push_pending unregisters first and leaves the pools mapped. The
two cases cannot be told apart from the free path, so the block now stays
on the freeing heap's own list and the drain adopts it against its own pool
header — without charging it to a heap that never allocated it. Dropping it
stranded the block and pinned its pool against reclamation for the life of
the process.

The test for this asserted the dropping, so it asserted the defect; it now
asserts that the block is kept and then adopted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(mem): one release walk, one name for the floor, one honest note

The walk that hands a heap's free pages back existed three times over. Two
of them — the explicit release and the idle decay — differed only in which
heaps they visited and what they drained first, so they now share
heap_release_free_pages. The aged incremental pass keeps its own: it ages
blocks and stops on a budget, which is a different job, not a copy.

The order below which a block has no whole page left to give once its first
page is kept was a bare 13 in four places; it has a name now.

The foreign head is a remote CAS target under the owner-routed free, so it
sat in the same cache line as `avail` and the slab heads and bounced them on
every push from another thread. It gets its own line.

The note on the pass that skips worker heaps still claimed a worker may be
inside ray_free between pending-- and sem_wait. The decay sweep walks those
same heaps and justifies itself by the opposite — ray_parallel_end drains
pending with acquire before clearing the flag. The real reason is policy:
folding a worker's slab cache back costs it a pop and a split on its next
allocation of that order, and collection runs far more often than those
caches are worth reclaiming.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(mem): the decay threshold is policy, not an environment knob

The setter covers what the tests needed, which left the environment read
serving operators alone — the ad-hoc knob surface this project does not add.
It is gone; ray_heap_set_decay_ms is the only way in. An operator-facing
override, if one is wanted, belongs on an existing surface and is its own
discussion, not a variable smuggled in with a fix.

Two comments described the code as it was before the stamp moved. The block
above the decay claimed the stamp is taken at the start of a unit of work
and explained why the end would not do — the opposite of what it does now,
and the reasoning is backwards once the check reads the clock before the new
stamp. It also priced the idle check with a getenv that no longer happens.
The header still advertised the environment variable as the threshold's
interface.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
…#453)

ray_vec_from_raw scanned only SYM input for its canonical null, so a raw
numeric payload carrying a sentinel (a binding passing INT64_MIN for an
absent value) produced a vector whose payload said null while HAS_NULLS
said none.  ray_vec_is_null gates numeric types on the attr, so the
sentinel rendered, serialized, and aggregated as ordinary data.

The scan now covers every sentinel-nullable type through the same
predicate ray_vec_is_null uses; the sentinel stays the source of truth.
Two tests that used from_raw as the way to craft unflagged-NaN vectors
now strip the attr explicitly — their subject (tolerance of legacy
flag-dropped vectors) is unchanged.

Fixes #445.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN
…ace (#457)

* perf(query): append insert batches into a named table's columns in place

(insert 't batch) rebuilt the whole table per call — every existing row
recopied cell by cell — so a tickerplant ingest slowed quadratically
with its own uptime: 500k rows in 1000-row batches cost 3s, and the
per-call cost tracked the rows present, not the rows added.

When the binding is the sole owner (table rc, cols list, and every
column unshared; no boxed, parted, mapped, slice, arena, or
narrow/store-domain SYM column), append the batch into the existing
columns and rebind nothing: ray_vec_append grows in place off the buddy
allocator, so the cost is O(rows appended), amortized — the vector
path's profile.  Any gate miss falls through to the rebuild unchanged.
A mid-batch failure rolls the appended lengths back, so the binding
keeps its pre-insert value.

The reproducer from #455: 500k rows in 1000-row batches 3078ms -> 39ms,
batch-size independent; 250k/500k/1M rows 744/3008/12502ms ->
18/37/75ms (linear).

Fixes #455.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN

* perf(query): bulk-blit fixed-width batches; boxed columns append in place too

Two refinements from review of the in-place insert path:

ray_vec_append_raw appends a whole batch with one capacity reserve and
one memcpy — same contract as ray_vec_append (COW, index drop, amortized
growth, original alive on failure) without the per-cell call, type
check, and capacity test.  The fast path uses it for every same-typed
fixed-width payload, including W64 runtime-domain SYM, whose ids copy
verbatim; narrow or store-domain SYM payloads keep the per-cell
translate.  1M rows in 1000-row batches: 75ms -> 7ms.

Boxed LIST columns are pointer cells like any other payload — append in
place through ray_list_append (which retains each cell) instead of
falling back to the rebuild.  Only the typeless-empty column still takes
the rebuild, which adopts its concrete type from the first payload.
The rollback releases boxed cells appended before a failure.

Null-flag propagation now looks through slices (slices carry HAS_NULLS
on the parent).

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN
hash_row_keys handed every null-keyed row a private, row-derived hash and
join_keys_eq returned false the moment either side was null, so a null key
matched nothing — not even the identical null in the same cell of the same
table.  Two visible consequences:

  * `anti-join [cols] X X` was NON-EMPTY whenever a key column held a null.
    Self-anti-join is empty for every X and every key set.  A service that
    interns tuples and uses anti-join to find the not-yet-seen ones therefore
    re-reported every null-keyed tuple on every packet: its dictionary and the
    companion state table grew without bound (58 MB -> 891 MB RSS in 16
    minutes), and the rows it persisted carry an id that can never be linked
    back.
  * left-join filled a null payload for a left row whose null key DID have a
    match on the right, instead of returning that match.

null == null is what the rest of the runtime already does with key columns.
collection.c's hashset folds every null into one bucket, so `distinct` keeps
exactly one null and `in` matches null against null; group.c folds nulls into
one group; atom_eq answers 1 for two nulls.  The join path was the only
holdout, and it was not even self-consistent: the radix single-STR-key
specialization compares raw descriptors, where two zero-length (null) cells
already came out equal via join_str_eq_hashed — so the same join answered
differently above and below RAY_PARALLEL_THRESHOLD.

Nor was the never-match rule ever chosen for symbol keys.  It is original v2
engine code (4a3a0c7), written when a null meant a numeric sentinel; empty
SYM/STR only became canonical nulls in bfb5b38, which never touched join.c and
silently dragged symbol keys under the rule.  The stress oracle it updated in
the same commit had until then read "including the "" null key, which the join
matches like any other (probed)" — that is the behaviour restored here, now
consistent across every key type.

Nulls hash to one canonical payload per key position and compare equal to each
other, unequal to any non-null.  The null branch is no looser than the value
arms it precedes: STR pairs only with STR and GUID only with GUID.  Both
helpers are shared by the radix and chained paths and by inner/left/full/anti,
so all four verbs move together.

test/stress_eval.c's join-cardinality oracle goes back to counting the ""
key (an exact revert of that hunk), and join_branch_cov's two both-sides-null
cases move (single-key 2 -> 3, multi-key 0 -> 1).  Its one-sided-null joins,
its anti-joins and all eight as-of assertions are untouched and still pass:
only null-meets-null moved.

As-of join is untouched.  Its NULLs-never-match rule is documented and its
merge walk carries its own per-row null bitsets — it never routes through
join_keys_eq.  queries/joins.md now states the equi-join rule next to it.

Co-authored-by: Anton Kundenko <[email protected]>
* fix(format): pad table cells by display width, not byte length

A multi-byte UTF-8 cell overstated its own width: a CJK char is 3 bytes
but renders 2 terminal columns, so every pad computed from byte length
came up short and the table borders tore on any row holding such a
symbol.

fmt_utf8_width gives the terminal display width (coarse East-Asian-Width
classification: CJK/Hangul/fullwidth/emoji are 2 columns, zero-width
marks 0, everything else including malformed bytes 1, so a bad sequence
can never desync more than its own cell).  Column measurement, data-row
padding, and header/type centering now use it; the bytes are still
written verbatim.

Fixes #454.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN

* fix(format): zero-width coverage beyond Latin — Cyrillic/Hebrew/Arabic/Thai marks, bidi controls

Combining marks that attach to a preceding letter and the invisible
bidi/joiner controls cost 0 columns, not 1: bare and pointed Hebrew are
the same four letters and must occupy the same four columns.  Ranges
from review; grapheme-cluster segmentation (emoji ZWJ sequences) stays
deliberately out of scope — terminals disagree on those regardless.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN
#460)

Snapshot-then-roll is two renames that are individually but not jointly
atomic.  A crash between them left a fresh .qdb next to the OLD .log
whose entries were already baked into that snapshot; recovery replayed
them all a second time.  Entries are arbitrary expressions, so the
double application corrupted state silently behind a normal-looking
'replayed N entries'.  The failed-roll path had the same window without
a crash: the old log is deliberately reopened and appended to.

The fix is identity, not ordering.  A fresh log starts with a 16-byte
generation preamble; the snapshot records inside the .qdb (under the
reserved key .journal.covered, skipped by the recovery bind loop) which
generation and byte length it covers, captured before the .qdb rename
so the marker can only under-cover.  Recovery replays the live log from
the covered offset when the generations match: nothing in the crash
window, exactly the tail in the failed-roll append case.  A pre-#420
headerless log keeps full-replay behavior, and validate/truncate hints
stay in absolute file offsets.

Fixes #420.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN
…461)

Since #449 every null key cell hashes to one canonical value, so a build
side with more all-null key rows than RADIX_DUP_RUN_MAX was guaranteed
to trip the dup-run abort mid-build and re-run the whole join chained —
hash, partition and HT work discarded on every execution, for a routine
~1%-null key at radix scale.

Massive duplication is the chained HT's job either way (O(dup) build vs
the open table's O(dup2)), so count the build side's all-null rows
before any radix work — only when a key column advertises HAS_NULLS,
with the same null predicate the hash uses, stopping at the threshold —
and go chained directly.  ray_join_null_fallbacks counts the routings.

Fixes #458.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN
…rs (#462)

Every IPC listener bound INADDR_ANY with no way to confine it, so a
process whose restricted port serves its whole in-memory state was
reachable from any interface, firewall or not.

Additive at every layer, per #427: ray_sock_listen_at /
ray_ipc_listen_at / ray_ipc_server_init_at take an IPv4 host (NULL
keeps INADDR_ANY, and every existing call site does); Rayfall gains
(.sys.listen "HOST:PORT") beside the untouched port form (numeric
strings via .sys.cmd still parse); the CLI gains -p HOST:PORT.  An
unparseable host is a loud io/bind failure, never a silent fallback to
all interfaces.

The CLI port parse is now strict digits-only either way, closing the
follow-up from #440: 'rayforce -p 65536x' exits with a clear message
instead of silently listening on a truncated port.

Fixes #427.

Claude-Session: https://claude.ai/code/session_01A8TdSm4JwxHB37kiaKxgTN
* fix(serde): validate table/dict counts and lengths on decode

Follow-up to the schema/column-count guard, hardening the same decode paths
against crafted or truncated frames (review of #444):

- Table: drop the now-dead `&& i < schema->len` loop bound (the count guard
  makes ncols == schema->len), so the guard reads as the single mechanism.
- Table: reject ragged columns — every column must have the same length (the
  row count), else ray_table_nrows reports column 0's length while row-wise
  ops read past the shorter columns.
- Dict: reject a keys/values count mismatch. A probe finds a key index in
  [0, keys->len) and reads the value at that index, so more keys than values
  is an out-of-bounds read/release of the value block. vals may be a LIST of
  columns or a flat value vector, so only the length is checked and no valid
  dict is rejected.

Tests: adds store/serde_container_count_mismatch in test_store.c, which builds
frames from real serialized sub-objects via sizeof(ray_ipc_header_t) — table
count mismatch, ragged columns, dict key/value mismatch — and removes the
brittle wire-layout-hard-coded .rfl case it replaces.

* test(pool): avoid racy zero-worker participation assert

* fix(store): validate decoded containers via shared invariants

* fix(store): consume table on invalid add_col errors

---------

Co-authored-by: Anton Kundenko <[email protected]>
* fix(query): handle guid membership predicates

* fix(query): preserve guid membership null semantics

---------

Co-authored-by: Anton Kundenko <[email protected]>
master's v2.5.15 commit (605723d) is a squash of dev at e5d87cd, so dev
already contains every change on master. Record the merge with -s ours so
the two histories share an ancestor again and PR #463 stops conflicting.

Claude-Session: https://claude.ai/code/session_019SHk8zkZi8PYnQ3bCRMCm3
@singaraiona
singaraiona merged commit b3e9aa1 into master Sep 2, 2026
11 checks passed
singaraiona added a commit that referenced this pull request Sep 7, 2026
master's v2.6.0 commit (b3e9aa1) is a squash of dev at 04dc656, so dev
already contains every change on master. Record the merge with -s ours so
the two histories share an ancestor again and PR #483 stops conflicting.

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants