Skip to content

v2.6.1 - #483

Merged
singaraiona merged 190 commits into
masterfrom
dev
Sep 7, 2026
Merged

v2.6.1#483
singaraiona merged 190 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]>
vbmithr and others added 28 commits August 31, 2026 13:36
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
* fix(ipc): restrict server-state mutators under -U restricted IPC

A -U (restricted) IPC client's evals run with __VM->restricted set, and
fn_is_restricted only blocks builtins that carry RAY_FN_RESTRICTED. Six
builtins that mutate or destroy server-side state were registered
without it, so a restricted client could escalate past read-only:

- rule         register a global Datalog rule              (#44)
- dl-add-edb   add an EDB relation to a program            (#49)
- dl-free      free a Datalog program handle               (#48)
- .graph.free  free a server graph handle                  (#46)
- hnsw-free    free a server HNSW index handle             (#47)
- .log.write   persist WAL work that replays unrestricted  (#41)

Add RAY_FN_RESTRICTED to each (rule keeps SPECIAL_FORM, matching how
`set` is registered). This only gates evaluation while __VM->restricted
is set, so trusted local eval, startup scripts, and WAL replay are
unaffected. The flag was already present on siblings such as hnsw-save/
hnsw-load and the rest of the .log.* family; this closes the gaps.

Test: lang/eval/restricted_server_state_ops asserts each verb returns an
`access` error under restricted eval, and that dl-free still reaches its
body (a non-access failure) in normal mode so the gate is scoped, not a
blanket ban.

* fix(ipc): restrict remaining server-state mutators
Since the empty symbol and empty string became their types' canonical
nulls, the store carries RAY_ATTR_HAS_NULLS for them across a save, so
every mapped partition holding one blank SYM/STR cell arrives at the
parted-insert validator with the bit set. parted_segment_attrs_valid
allowed HAS_NULLS only for the numeric, temporal and GUID bases, so a
live insert into any such day was refused as `corrupt` — the day's
second batch after a first batch with a blank, or the first insert
into a reopened day saved with a blank.

SYM/STR nulls are in-band (the payload is unchanged by the bit), so
the validator now admits HAS_NULLS for RAY_SYM and RAY_STR too.

Fixes #465

Claude-Session: https://claude.ai/code/session_01XbNM4pZe3wCS7V1m5zUUSW
A multi-key `select ... by:` whose keys include a null STR (or GUID) key
stopped folding equal rows after the hash table's first growth: every
phase-1 key builder stores a null key as a zeroed slot plus a null-mask
bit and hashes it as ray_hash_i64(0), but hash_keys_inline (rehash,
lookup, partial-table merge) read the stored slot back by type — a
zeroed inline-STR descriptor hashed as the empty string, a zeroed wide
GUID slot as source row 0. After the rehash the group sat under a hash
no probe computes, so each later equal row opened a fresh group.

hash_keys_inline now consults the null-mask word first and hashes a
null key as ray_hash_i64(0) whatever its type, in both the inline-STR
and the generic layout. The packed layout already hashed the whole
region (values + mask) on both sides and is unchanged.

Fixes #466

Claude-Session: https://claude.ai/code/session_01XbNM4pZe3wCS7V1m5zUUSW
* feat(ipc): add multicast fan-out

* docs(ipc): neutralize multicast migration wording

* fix(mcast): address pr review feedback

* fix(mcast): defer failed subscriber close

* test(mcast): cover failed send close ordering

* fix(ipc): queue nonblocking multicast writes

* fix(ipc): drain queued multicast frame before a direct write

The nonblocking multicast path parks a half-sent frame on sel->tx.buf and
finishes it from the poll layer's write-readiness handler. But every other
writer on that fd — the sync RESP reply (send_response), sync_send, and
ray_ipc_send_async — wrote straight through ray_sock_send without consulting
the queue. A subscriber whose large upd frame was still queued could issue any
sync request; the server spliced the RESP into the middle of the pending frame
and the peer parsed the two framings into each other, corrupting the stream for
that connection.

Add conn_tx_drain_blocking() and call it before each direct write: it flushes
the queued remainder to the wire (blocking on write-readiness the way
ray_sock_send already does) so the following write starts on a frame boundary.
It fast-paths to a no-op when nothing is queued, so non-subscriber connections
are unaffected.

Test: mcast/sync_reply_after_queued issues a sync ping from a subscriber while
its ~800 KB frame is still parked on tx.buf (4 KB SO_SNDBUF) and asserts the
reply is a clean 42 and the payload arrives whole -- the existing large-payload
test drained the queue before pinging, so it never exercised the interleave.
…es (#476)

* perf(query): upsert writes matched rows in place and applies a batch in one pass

ray_upsert found the target row with a linear key scan and rebuilt the
whole table to write one cell, per payload row: a named-table upsert
cost O(rows present) per row, a 1000-row batch was 1000 scans and 1000
rebuilds, and an attached .idx.hash on the key column was never
consulted.  Maintaining last-value-per-key state (a current book, a
current quote) therefore paid the size of the state on every update.

Upsert now runs one pass per call.  When the binding is the sole owner
the live columns are mutated: a matched row has its cells overwritten in
place (boxed pointer swap, ray_str_vec_set, or append_atom_to_col plus a
tail move so coercion and null encoding stay in one place), and a new
key appends amortized like insert's #455 path.  A batch resolves its
keys through one hash over the target built once per call, entering
appended rows as they land so a key repeated inside the batch updates
the row its first occurrence created.  A single-row call consults a
fresh hash index on a lone key column and otherwise runs one typed
scan.  A value target, or a shared table or column, gets one copy of the
columns and the same pass on the copy.  Every cell is type-checked
before anything is written; a mistyped payload leaves the table
untouched, and a vector-row whose columns differ in length is now a
`length` error instead of an out-of-bounds read.  Any gate miss falls
through to the previous arms.

Boxed LIST columns, which the rebuild arm rejected on update, are
handled.  The table-payload gather no longer caps at 64 columns.

Release build, the issue's reproducer: 1000 upserts into a 40k-row
table 432 ms -> 1 ms, the same rows as one batch 428 ms -> 1 ms.

Fixes #475

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

* perf(query): update with where writes matched rows of a named table in place

The WHERE arm of ray_update evaluated the predicate and every update
expression over the whole table, then rebuilt each updated column cell
by cell through ray_vec_append, so a keyed update into a named table
cost O(rows present) per call with a large constant, and a hash index
on the key column was never consulted: 1000 single-row updates into a
40k-row table took 1.4 s, indexed or not.

When the binding is the sole owner, update now resolves the matched
rows first — through a fresh .idx.hash on the column when the predicate
is a plain `(== col value)`, otherwise through the same mask the legacy
arm computes — gathers those rows into a sub-table, evaluates the
update expressions there, and scatters the results into the live
columns in place, dropping any index on a written column.  Expressions
containing an aggregate, or a call whose head is not a plain symbol,
keep the legacy arm so the aggregate still ranges over the whole table.
Every value is type-checked before anything is written; a wrong-length
vector is now a `length` error instead of an out-of-bounds read, and a
symbol atom can be written into a boxed column through a where clause.

Release build, 1000 single-row keyed updates into 40k rows:
1447 ms -> 113 ms unindexed, 1482 ms -> 33 ms with .idx.hash on the
key column (flat from 40k to 160k rows).

Part of #475

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

* fix(query): cast update scatter writes from the payload pointer

cppcheck (portability, invalidPointerCast) flagged the numeric
promotion branch of update_scatter for casting a uint8_t* byte pointer
to double*.  Take the typed pointers from ray_data() directly.

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

* fix(query): keep whole-table semantics for non-elementwise where-updates

The in-place where-update evaluated any expression without an
aggregate over the sub-table of matched rows, which changed the meaning
of order-dependent functions (deltas, sums, ...) and of free variables
holding table-length vectors, and only for the named-target spelling.
The gate now admits only elementwise expressions: a head that resolves
to a builtin flagged RAY_FN_ATOMIC over columns, literals, quoted
symbols and such calls.  Everything else, and a predicate matching no
row, keeps the legacy arm, so both spellings of `from:` agree; the
tests pin deltas, sums, a global vector, `if` and an aggregate.

Also release the extra reference when ray_cow fails on upsert's copy
path.

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
…l kernel (#469)

* fix(query): count a null as one distinct value in the grouped parallel kernel

`select {d: (count (distinct v)) by: k}` answered differently depending on the
core count: the parallel per-group kernel skipped null cells outright, while the
serial fallback — and the ungrouped builtin, and the rule pinned in
test/rfl/null/distinct.rfl — keep at most one null and count it. The kernel runs
when there are at least two workers and four groups, so the default multi-core
run was the one giving the wrong answer, silently and with no error.

The kernel already had the shape this needed. Its hash table encodes an empty
slot as 0, so the literal 0 cannot live in the table and rides a side flag
instead. A null has the same problem for the same reason, so it now rides its
own flag beside it: seen once, counted once, however many rows carry it. The
loops that run when a column has no nulls are untouched, and on a null-bearing
column the work replaces a `continue` — so nothing is added to the hot path.

This also settles an inconsistency between types. A SYM null is id 0, so it was
already being counted, by accident, through the zero flag; numeric and temporal
nulls were being dropped. Both now follow the same rule.

The comment above the kernel claimed null-bearing columns fall through to the
serial path. No such gate exists — the kernel handles them itself, which is how
this arose. Corrected to describe what the code does.

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

* test(null): pin the null rule through a grouped count, not only the builtin

The file already stated that distinct keeps at most one null, and the builtin
obeyed it — but the grouped parallel kernel is a separate implementation of the
same rule and had drifted, which is how it shipped dropping nulls.

The four shapes here reach that kernel: it is selected only with at least two
workers and four groups, and the suite runs with TEST_CORES=2, so four groups
is what each one has. They cover the integer arm, a group that is entirely
null, the F64 arm, and the SYM arm — the last because a SYM null is the empty
symbol, which the table already handled through the flag it keeps for the
literal 0, so the two need pinning together or they drift apart again.

On the parent commit the first case fails with [1 1 2 1] against [2 2 3 2] —
one null lost per group.

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

* fix(group): count a null once on the large-group route too, and drop the flag

Review found the first commit closed one of three kernels. Above 50000 groups
the query leaves query.c entirely for ray_count_distinct_per_group in group.c,
whose serial and partitioned loops still skipped nulls — so the answer stopped
depending on the core count and started depending on the group count instead.
Measured on dev: the same data gives 2 per group below the boundary and 1
above it, and a column that is entirely null gives 1 below and 0 above.

Both group.c loops simply stop skipping. Nothing else was needed: cdpg_read
already folds every NaN payload to one canonical NaN, the integer sentinels
are INT_MIN and hash as ordinary keys, a SYM null is id 0, and the dedup table
marks an empty slot in its gid field — offset by one — so a null value cannot
collide with it. cdpg_is_null had no callers left and is gone.

The same reasoning removes the flag the first commit added to query.c. For the
integer widths the sentinel was always an ordinary key, so the plain insert
loop counts a null once by itself; only F64 needed anything, and canonicalising
the NaN there — exactly what cdpg_read does — is enough. That deletes
saw_null, CDPG_BUF_NULL, the three has-nulls loop bodies and the has_nulls
local, leaving the kernel shorter than before this branch started.

count_distinct_extras.rfl pinned the old behaviour as intentional, calling it
a per-group-vs-scalar difference. It was not deliberate enough to survive: the
three kernels did not agree with each other, so the difference was really three
differences. The block now states the single rule and its arithmetic is
recomputed — three groups holding a null go from 1 to 2, so the total goes
from 59996 to 59999, for the integer and the float layout alike.

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

* fix(group): cover the partitioned kernel and drop what the change left behind

The partitioned loops in group.c lost their null skip in the previous commit,
and nothing tested them: that path needs 200000 rows as well as 50000 groups,
and every case added so far stopped at the serial loop. Four cases now cross
both boundaries, one per arm — integer, all-null, F64 and SYM — since the
partitioned kernel handles those separately. On the parent they answer 1 and
0 where they should answer 2 and 1.

Removed as dead: the has_nulls field in both contexts, written and never read;
the esz in cdpg_hist_fn, computed only to be discarded; the doc comment of the
deleted cdpg_is_null, left stranded above cdpg_read.

The has-nulls arm of ray_count_distinct_per_group computed the same keys as
the typed loops beside it, through a per-row read_col_i64 dispatch. The typed
loops run unconditionally now.

The NaN and -0.0 fold moves to canon_f64_key in internal.h. Three kernels
decide a count-distinct depending on the row and group counts, and they have
to key a value identically or the answer follows the shape of the data — that
now holds because they call one function rather than because four copies were
kept in step by hand.

Two comments corrected: the one above the parallel context claimed a null
rides the zero flag, which is true of SYM only and contradicted the arms
below it, and a test still cited line numbers that no longer point anywhere.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

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

Same race 069c27a removed from workers_participate: the test asserted
bit 0 of saw_worker ("main thread always = worker 0") while conceding
that worker 1's participation depends on scheduling.  With one worker
and three tasks the worker can drain all three before main enters its
claim loop, leaving bit 0 unset — observed on the macOS debug job of
#477, a change that does not touch the pool.  Completion is asserted
exactly; assert only that some participant recorded itself.

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
…lback's message (#479)

A forever timer was re-pushed with exp_ms += tic_ms and the firing loop
ran while heap[0]->exp_ms <= now, refreshing now after each callback.  A
callback that overran its period by T therefore left the timer T/tic
deadlines in the past, and the loop fired it that many times back to
back — each a full callback — before the poll loop reached epoll_wait
again, so the process served no accept, handshake or request for the
whole storm.

The timer now re-arms at its next scheduled deadline, or one period
from now when that deadline has already passed: exact cadence while
callbacks are cheap, at most one fire per period when they are not, and
missed intervals are skipped rather than replayed.  A one-shot timer is
unaffected.

The error arm printed ray_fmt(err), which renders an error as its code
alone (`timer 0: error: io`).  It now prints the code and the message
from the runtime's last-error slot, the same line the REPL prints.

Fixes #474

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
…t a listener (#478)

When ray_ipc_listen_at failed, main printed `failed to listen on
HOST:PORT: ...` and carried on: it loaded the script, ran it, and either
exited 0 (no selector registered, so the poll loop was never entered) or
kept running the script's timers with no listener.  A supervisor that
asked for a server got a process that was not one, with a zero exit
code, and learned of it from the first client's ECONNREFUSED.

A -p that cannot bind is now fatal: the diagnostic is printed, the
script is not run, and the process exits 1 through the normal teardown.

Fixes #473

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
…ed" (#477)

ray_ipc_connect budgets the TCP connect and the two-byte wire handshake
together: ray_sock_connect installs the budget as SO_RCVTIMEO/SO_SNDTIMEO
once the connect completes.  A connect that timed out returned -5, but a
handshake send or recv that hit the budget returned the generic -1, and
.ipc.open printed that as "connection refused" — byte-identical to a
dead port, which fails instantly.  A server that is alive and listening
but inside a long evaluation (a timer callback, a large query) hits
exactly this: the kernel completes the TCP handshake into the backlog
and nobody answers the wire handshake within the budget.

Failed steps are now classified by errno: ETIMEDOUT / EAGAIN /
EWOULDBLOCK -> "connection timed out", ECONNREFUSED -> "connection
refused", anything else -> "connect failed: HOST:PORT: <strerror>", and
a wire-version mismatch names itself instead of reading as refused.  A
peer that closes mid-handshake sets ECONNRESET so an EOF cannot inherit
a stale EAGAIN, and an unresolvable host sets EHOSTUNREACH rather than
whatever errno was left behind.  The default budget is unchanged.

Fixes #472

Claude-Session: https://claude.ai/code/session_01J4QKJW3RbRP8TQoquJtARg
…#471)

* fix(pivot): keep a temporal type when both branches of an if share it

`(if x ts ts2)` over two TIMESTAMP columns answered TIMESTAMP when the pool
had workers and I64 when it had none — and DATE and TIME degraded to I32 the
same way. Nothing about the values changed; only the type the result claimed.

An `if` selects a value, it does not compute one, so two branches of one
temporal type yield that type. The graph says as much: promote_if_type puts
that case ahead of the general numeric widening, which folds a temporal down
to its integer storage because that is right for arithmetic — a difference of
two timestamps is a span, not an instant.

exec_if has two arms. The eager one runs when workers exist and takes the
node's type as given. The selected one runs otherwise, and re-derives the
type from the values it actually materialised — its ladder had no case for
two matching temporals, so it read them as storage. That re-derivation is
not redundant and is left alone: it narrows F64 to I64 when the float branch
supplied no rows, which the static type cannot know. Only the temporal case
is brought into line, so the two arms agree where they must and the narrowing
survives where it earns its keep.

Branches of different temporal types are untouched — there is no shared
meaning to keep, so widening remains correct.

The predicate is a third copy of one that is file-local in graph.c and
duplicated again in query.c, where it also unwraps parted types. Noted rather
than unified: sharing it is a change of a different shape.

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

* fix(pivot): let the selected arm of an if answer as the eager one would

Review found the first attempt fixed too little and tested nothing.

Too little: aligning the ladder's temporal case left the answer worker-
dependent whenever a branch supplies no rows. `if_eval_branch` returns NULL
for an empty branch, and the shortcut that adopts the other side ran ahead of
the new rule, so with an all-true condition `(if x ts 5)` was TIMESTAMP
serially and I64 under workers; `(if x ts 5.5)` TIMESTAMP against F64;
`(if x d ts)` DATE against I64 — which also flipped the boundary case the
first attempt had just pinned.

Tested nothing: both branches in those cases were bare column reads, so under
the harness default the eager arm answered and the code being fixed was never
reached. The file passed unchanged on the parent commit.

The rule is not about which types to promote. It is that where the eager arm
could have handled the node, the selected arm has to give its answer — and
where it could not, the selected arm is the only one there is and may report
what the rows actually hold. That condition already existed in the dispatch
gate: a non-STR output whose branches are both trivial and elementwise-
fillable. It is now a named value, used to decide the type as well as the
dispatch.

So the second promotion ladder goes, and the temporal predicate that came
with it — which was a fourth hand-maintained copy of a set that graph.c,
query.c and lang/internal.h already carry in versions that are not identical.
What remains is: trust the graph, except for a branch that produced no rows
in a node the eager arm was never going to take, where the surviving type
stands. That is what keeps `(if (> v 0) v (sqrt s))` summing to 15 rather
than 15.0, and what keeps a numeric value in a STR-typed if from rendering as
an empty string.

The tests use a nested if as the branch, so the eager arm is out of the
picture at any core count and the case fails on the parent under workers, not
only serially. The empty-branch cases keep their trivial branches on purpose:
there the eager arm is a candidate, so its answer is the required one.

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

* fix(pivot,graph): three more ways an if reported the wrong type

All in the same type derivation as the previous commit, and found because the
review asked whether other types were affected — I had answered no on the
strength of a sweep that only ever used in-memory tables.

**A column of a parted table.** Its type is carried in a wrapper, and the
promotion ladder in graph.c has no notion of one: a wrapped type matches none
of its cases and falls out the bottom as RAY_BOOL. `(if true ts ts)` over a
parted table claimed B8 and truncated every value to a byte, and printing the
column aborted under UBSan. Not only temporal — a plain I64 column did the
same. promote_if_type now unwraps to the base type, as query.c's
dag_type_is_temporal already does; the result of an if is a materialised
vector, never a parted column, so the base type is what it should carry.

A side effect worth knowing: `(+ (if true ts ts) 1)` now raises a type error
instead of returning truncated numbers. Timestamp arithmetic over a parted
table was already an error — the B8 collapse was hiding it.

**A null branch value.** An atom null is the sentinel and carries no attribute
of its own, so nothing marked the output as null-bearing and the formatter,
which reads the attribute rather than the value, rendered the sentinel as an
ordinary date. Both arms set the attribute now.

**A string literal against a SYM column** answered SYM at runtime against a
static STR. Closed by the previous commit rather than here: with both branches
producing values the declared type is returned, so runtime and static can no
longer differ.

On the tests: the first drafts of two of these passed on the parent commit.
`nil?` reads the value, so it says true with or without the attribute — only
rendering the whole vector shows the difference. And a parted case needs a
literal condition and two partitions, or the branch types arrive unwrapped
anyway. Both requirements are written down beside the cases, so they are not
quietly relaxed later.

Verified against an in-memory table of the same rows: the parted table now
answers identically, type and values, at both core counts. 242 type-pair
combinations with an all-true and an all-false condition agree between modes —
either branch can be the empty one, and the narrowing looks at whichever
survived.

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

* fix(pivot,graph): stop the declared type from narrowing a widened value

Trusting op->out_type outright truncated data. The graph promotes the
declared types of the branch expressions, but arithmetic widens past them:
(* a a) over an I32 column is computed and stored as I64, so calling the
result I32 rewrote 10000000000 as 1410065408, and I16 60000 as -5536. The
declared type is a floor now — whichever of it and the materialised values
is wider wins.

Narrowing survives only where the declared type came from the branch that
supplied no rows: a float branch that never ran, leaving integers that keep
their width, or a string branch that never ran, leaving a number that would
otherwise be written into a string column and read back as empty. Two
temporal branches promote to I64 because of the pair rather than either one,
so handing the answer to the survivor made a nested-if branch report DATE
where the same expression with a bare column reported I64.

The parted wrapper is stripped at the scan node instead of inside
promote_if_type. Nothing that reads a node's out_type knows about wrappers,
so the narrow unwrap left two holes: promote() for + - * % still saw a
wrapped operand and yielded RAY_BOOL, and the SYM override in ray_if
compares against a bare RAY_SYM, so a parted SYM column came back as
dictionary ids. The executor decides how to read a parted column from the
column, never from the node, so the wrapper has no reader here.

Also in this path: a null atom now stays null across widths, so (if c f 0N)
over an F64 column writes the F64 null rather than the I64 sentinel read as
-9.22e18; if_val_has_null asks RAY_ATOM_IS_NULL about the atom's own type
rather than the promoted one; and a scalar condition is expanded once,
because the eager fill indexed its single cell per row and returned a
mixture of both branches.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(pivot): drop the dead out_type argument of if_val_has_null

Since the null test became RAY_ATOM_IS_NULL, which answers for the atom's
own type, out_type is unread. Pin the SYM case while here: SYM has no typed
null and no 0Ns literal, the empty symbol ' is the null and is in-band, so
it survives the branch as a SYM with no width handling of its own.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(pivot): do not cast a NaN or an out-of-range double to int64

The eager arm pre-resolves both representations of a scalar branch before it
knows which one the output needs, so an F64 null branch reached the integer
conversion and cast a NaN. The cast is undefined; where it does not trap the
result differs per target, so a null would narrow into a different arbitrary
number on each platform. Route the three float-to-integer conversions through
one guard that answers with the integer null instead, for a NaN and for a
magnitude past the int64 range alike. In-range values convert as before.

Only a sanitizer shows this, so there is no separate case for it: the
existing 0Nf test walks the path and a float-cast-overflow build is what
catches a regression.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
* fix(serde): round-trip builtins by full registered name

Builtin function objects inline only the first 13 bytes of their name (fn_set_name copies into aux[2..15]), and serialization read that inline copy via ray_fn_name. A builtin whose registered name is longer, such as .db.parted.tables or .sys.querylog.enable, was serialized truncated, so (de (ser fn)) interned a name that does not exist and failed with a name error instead of round-tripping. The serde-side nlen > 15 clamp was dead code: names from ray_fn_name are already capped at 13.

Recover the full name from the environment instead. Every builtin, dotted reserved names included, is bound flat in the global env (reg_bind), so a pointer scan maps the object back to its sym_id and ray_sym_str yields the full name; the decoder already reads a NUL-terminated name of any length.

Tests: store/serde_builtin_name_roundtrip asserts long-named builtins round-trip to the same env object; serde.rfl covers the (de (ser ...)) repro plus a behavioural identity check. Full suite: 3747/3748 pass (1 pre-existing skip).

* test(serde): prove builtin round-trip by call, not a truncated golden

The two `-- .db.parted.tables` goldens in serde.rfl compared the formatter's
output on both sides, and the formatter renders a builtin through ray_fn_name's
13-byte inline copy -- so both sides read `.db.parted.ta` and the lines would
pass on dev too, proving nothing about the fix. Replace them with behavioural
calls that reach each builtin's own argument check (type / domain), which only
resolve when the full name survived the round-trip. Pointer identity stays
covered by store/serde_builtin_name_roundtrip in the C suite.
* fix(csv): infer Rayfall temporal forms

* docs(csv): note the dotted-date + T/t/space timestamp form is accepted

fast_timestamp accepts the ISO separators after either date form, so a dotted date with a T/t/space ("2024.01.02T01:02:03") also infers TIMESTAMP even though no writer emits that mixed shape; only 'D' is tied to the dotted date. Document the leniency so the grammar stays describable. Comment only.
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
@singaraiona
singaraiona merged commit a99a019 into master Sep 7, 2026
11 checks passed
singaraiona added a commit that referenced this pull request Sep 9, 2026
master's v2.6.1 commit (a99a019) is a squash of dev at 30712c9, so dev
already contains every change on master. Record the merge with -s ours so
the two histories share an ancestor again and PR #502 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