Skip to content

v2.11.0 - #711

Merged
singaraiona merged 98 commits into
masterfrom
dev
Oct 4, 2026
Merged

singaraiona merged 98 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

ser-vasilich and others added 30 commits September 19, 2026 19:55
The native top-N of the radix path kept every group at or beyond the
threshold.  Groups strictly beyond it number fewer than N, but the
groups AT the threshold can be nearly all of them: a count-per-group
top-10 over a near-unique key has a threshold of 1, every group ties
it, and the "kept superset" is the whole grouping, heap-sorted by
first row — a comparison sort over 100M pairs for a query whose answer
is ten rows.

The emitted prefix is the tied groups' first-seen order, so only the N
tied groups with the smallest first row can ever be taken.  The
selection now keeps the strictly-better groups plus exactly those N,
through a bounded max-heap, and sorts at most 2N entries.  The rows
emitted are the ones the full kept set produced.

Tests: the pinned kept count of the radix native top-N case becomes N;
a near-unique two-key grouping whose threshold every group ties, in
both directions and under a row selection, against the full grouping.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Rayfall had no way to stop iterating before the end of a sequence.  Every
iteration primitive — map, pmap, fold, fold-left/right, scan, scan-left/right,
prior — consumes its whole input, and there was no loop construct, so a
"repeat until done" loop had to be written as a fold over a fixed range whose
full length was paid on every call however early the work finished.  `return`
did not help: it exits the lambda, not the iteration, so the fold kept calling
the lambda for every remaining element.  Recursion was not an alternative
either, since there is no TCE and the stack tops out around 1-2k frames.

(while cond body...) evaluates cond, and while it is truthy evaluates each
body expression in order, then tests again.  It always returns null — a
statement form run for effect, and a never-taken loop has no last value to
report.  Zero body expressions is legal, so a condition with side effects can
be the whole loop; that is the shape a drain wants, where there is no sequence
to iterate over and the range was only ever scaffolding.

Implemented on both evaluators, which must agree:

  - ray_while_fn (eval.c), registered beside `if` and `do`.
  - an sf_while case in the bytecode compiler emitting JMPF over a backward
    JMP — the first backward branch the compiler produces.  The VM's op_jmp
    already checked for a pending interrupt when the displacement is negative
    (dormant until now), so a runaway loop is Ctrl-C-able for free.

Compiling the body inline, rather than letting it fall through to the generic
special-form path, is what keeps `return` working inside a loop: it reaches
the sf_return case and unwinds the lambda instead of degrading to the tree
walker's identity `return`.

Neither path pushes a scope around the body.  `let` binds only in the top
frame (env_bind_local), so a per-iteration frame would discard loop-carried
`let` state on the tree-walking path while the compiled path — whose `let`
writes a function-level slot — kept it, and the two evaluators would disagree
on the same source.  A caller wanting a fresh frame per pass writes
(while cond (do ...)), which composes.

patch_jump and emit_jump_back now share write_jump_offset; an out-of-range
displacement still sets c->error, dropping the lambda to the interpreter.

Measured on the drain shape from the issue (4-step drain under a 4096 safety
bound, release build, driver baseline subtracted): fold-left over (til 4096)
1420 us/batch, the nested 64x64 workaround 45.8 us/batch, `while` 3.8
us/batch — 374x over the original and 12x over the workaround.

Closes #588
The two remaining early-termination forms requested in #588, alongside the
`while` that landed in #590.  Neither is an unblock — `while` already covers
the reporter's case — but both complete the vocabulary he asked for.

`times`
-------
(times n body...) runs the body exactly n times and returns null.  `do` is
already progn in this language, so the bounded loop could not reuse that name;
overloading `do` on an integer head was rejected as genuinely ambiguous —
(do 5) would have to mean either "loop five times over nothing" or "return 5",
and a computed first expression that happened to be an integer would silently
change meaning.

The count is evaluated ONCE on entry, so a body mutating whatever produced it
cannot change how many passes remain.  A count of zero or less runs zero times
rather than trapping; a non-integer is a type error.

Compiled as a counted loop over a hidden local slot, reusing the backward
branch added for `while`.  ray_times_norm_fn type-checks the count and clamps
a negative bound to zero on entry, which lets the per-pass test be a bare
truthiness check on the counter — 0 is falsy, so no comparison call is needed
per pass and a negative bound cannot run away.  That helper and the decrement
are pushed as constant-pool objects rather than resolved by name, so the
loop's own arithmetic is unnamable from source and cannot be swapped out by a
`(set - ...)` override.  The counter's slot is addressed by index and its sym
carries a space, so no source token can collide with it and nested `times`
counters stay apart.  As with `while`, the body compiles inline, so `return`
unwinds the enclosing lambda from inside the loop.

fold-while
----------
(fold-while pred f init xs) offers the accumulator to `pred` before each step
and stops on a falsy answer, yielding the accumulator as it stands.  The test
precedes the first element, so a predicate false at the start returns `init`
untouched.  The predicate takes the accumulator rather than the element: that
is the form that expresses "iterate until the running result says stop", which
is the early termination actually being asked for.

One deliberate divergence from ray_fold_fn: that routes its collection through
unbox_vec_arg -> to_boxed_list, boxing every element up front.  For a
primitive whose purpose is to stop early, paying for the tail it never reaches
is the cost being removed, so elements are pulled one at a time via
collection_elem.  A plain variadic builtin — no compiler work, since it
dispatches through the normal call path.

Measured, release builds: `times` 100 ns/pass against 180 ns for `while` plus
a manual counter over 1e6 passes.  `fold-while` stopping after three elements
of a 1e6-element vector costs 3.9 us against 369 ms for the `fold-left`
equivalent, which had to box and walk all million to discover it was done.

Tests: test/rfl/lang/times.rfl and test/rfl/collection/fold_while.rfl, each
behaviour asserted on both evaluator paths where applicable — including the
count validation and negative clamp on the compiled path, which runs through
entirely different code from the tree walker's check.
feat(lang): add a `while` special form
fix(group): bound the tied groups the radix top-N selection keeps
feat(lang): add `times` and `fold-while`
ray_vec_is_null is out-of-line (no LTO) and the join called it once per key
column per row in hash_row_keys — on the build side, the probe side, and the
prefetch lookahead — plus twice per key column per hash-chain step in
join_keys_eq, across both the count and the fill pass.  A reported profile
put 13.28% of a service's samples there, on a join keyed by two SYM columns
that structurally never hold a null.

Prove once per join that no key column can hold a null and drop the call.
SYM/STR nulls are canonical empty payloads (id 0 / length 0) that HAS_NULLS
does not track, so text columns are proven by the chunked zero-scan from
#533 rather than by the flag; everything else reads the flag through slices
and takes a set bit at face value, so the proof stays O(n) and never
degrades into ray_vec_has_nulls' per-element walk.  Flag-readable columns
are settled first, so a nullable numeric key short-circuits before any text
column is scanned.  OP_CONST (atom) key slots are refused as unprovable.

Also skip the #458 null-run pre-scan under the proof.  It gates on
ray_vec_may_have_nulls, which is unconditionally true for SYM/STR, so a
SYM-keyed join ran a full per-key-per-build-row ray_vec_is_null scan before
the join proper on every execution; a null-free key set cannot contain an
all-null row, so the scan is dead.

Measured with bench/join_nullfree (release, 1:1 book join, 4M probe x 500K
build): two SYM keys 275 -> 249 ms (-9.5% median, -7.8% min); single I64 key
106 -> 99 ms (-6.3% median, -7.9% min).  A proof that fails on a text key
costs a partial scan (~8ms on a 4M-row SYM column) and gains nothing — only
nullable SYM/STR key columns pay it.

ray_join_force_null_checks forces the null-aware loops so the differential
tests and the perf gate can compare both paths in one binary;
ray_join_nullfree_keys counts the joins that took the fast path.

Closes #597
perf(join): skip per-cell key null tests on provably null-free columns
fix(system): validate launcher and timeit integer arguments
Every value-taking startup flag was gated on `i + 1 < argc` and then
consumed argv[++i] blindly, so one flag silently ate the next.  The shape
that was reported is the worst one for a service:

  rayforce -Q -p 5099 svc.rfl

`-Q` took `-p` as its value, the port was never bound, and nothing on
stdout or stderr said so.  Under a supervisor the process starts, the
script runs, the unit looks healthy, and every client gets connection
refused.  `-c` and `-t` had the identical hole.

Two neighbouring cases came out of the same code.  A trailing flag with
no value fell through to the positional-file arm and reported the
misleading `cannot open '-Q'`.  And that arm took ANY unrecognized token
as the script name, which the real positional then overwrote, so a
typo'd option was not merely ignored — it was silently swallowed:
`rayforce -x svc.rfl` ran the script as if `-x` had never been typed.

Every value-taking flag now goes through flag_value(), which refuses a
missing value and a value that is EXACTLY one of this program's flag
tokens (including the `--` app-args terminator), with a diagnostic and
exit 2 before the script is loaded.  A value that merely STARTS with '-'
stays legal: a password or a negative number is a legitimate value, and
refusing those would break working command lines for no gain.  An
unrecognized `-`-prefixed token is now an error too; a lone `-` is still
a positional, and tokens after `--` belong to the app and are never
validated.

`-Q, --querylog N` was a real flag, referenced twice in the docs, that
--help never listed beside its sibling `-t, --timeit N` — added, along
with `[-Q 0|1]` in the synopsis.

The suggestion to fail when `-p` was requested but nothing bound is
already in (#473, listen_fatal.rfl), and cannot catch this: the parser
never saw the eaten `-p`, so there was no request to check against.  The
guard on the value is what closes the class.

Also: the two pre-existing `-p` validation bail-outs now release the
runtime like every other error path, since these paths are exercised
under ASan by the new test.

Closes #600
…ionally

Every node the executor evaluates returns an owned reference — the
constant table node included, it retains its literal.  The OP_WINDOW,
OP_SORT and OP_HEAD cases released their input only when it differed
from the graph's table, taking an equal pointer for a borrowed one.  A
query's root is a constant node over that very table, so the reference
was never released: one input table per windowed, sorted or limited
query.  Invisible while a global kept the table alive; a whole table per
call when the input was built for that call, as a service that windowed
a freshly concatenated buffer on a timer found (#602).

The four cases now release the input on every path, as the join and
the plain head/tail cases already did.

Test: window, sorted and limited selects over a table built per call,
measured with the two-window bytes-allocated method of the other memory
probes, plus a shared input reused across fifty calls.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… queries

Twenty calls of each shape over one global table; the table's refcount
must be exactly what it was before, and the table still whole after.
Fails on the unfixed executor at the first window shape.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The same borrowed-query-table guard sat under the reductions; no child
evaluates to the query table there today, so nothing leaked, but the
premise is the one the sort, window and limit cases just dropped.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
fix(exec): release the input table of window, sort and limit queries
fix(cli): reject a flag as another flag's value, and unknown options
ray_pool_dispatch and ray_pool_dispatch_n signalled the whole pool on
every dispatch, however narrow the window.  The main thread participates
as worker 0, so at most n_tasks-1 helpers can ever claim anything; the
surplus threads woke, raced to an already-drained window, and went
straight back to the semaphore.  On a dispatch narrower than the machine
that is pure overhead — a partition-parallel step over three partitions
woke every core on the box to run two tasks.

Signal min(n_tasks-1, n_workers) instead.  Signalling FEWER is safe:
completion is governed by the `pending` spin-wait, never by the signal
count, so an unsignalled worker simply stays asleep, and under-signalling
cannot produce the surplus-signal problem between consecutive dispatches
that the spin-wait exists to avoid.

Measured (10M-row ClickBench, 43 queries x 3, splayed): sum of per-query
hot times 5690.7 ms -> 5667.3 ms (-0.4%, within noise), user CPU 55.1 s
-> 54.8 s.  So this is waste removal rather than a speedup on workloads
whose dispatches are already wider than the pool.

Not a fix for #599.  That report's shape — a 130k-row join probe, which
splits into 16 tasks against 8 workers — is unaffected, because the clamp
lands on the same worker count it already used (measured: 5.19 s -> 5.18 s
of CPU, unchanged).  The investigation there points at the pool defaulting
to logical rather than physical cores; that is a separate change with its
own benchmark trade and is filed on its own.

test_pool.c gains pool/dispatch_narrow, which is the case the existing
coverage missed: dispatch_n_small uses 4 tasks on a 2-worker pool, so the
clamp never binds.  The new test drives windows of 1..4 tasks on a
4-worker pool, then alternates narrow and wide windows 25 times over the
same pool, asserting exact task and element counts throughout — the two
risks the change introduces are a task nobody claims and signal
accounting that drifts across dispatches and starves a later wide window.
perf(pool): wake only the workers a dispatch can keep busy
Detect Windows via $(OS) or uname (MSYS2's make hides $(OS)), link
Winsock and a statically linked winpthreads, build with 64-bit off_t
(_FILE_OFFSET_BITS=64) and an 8 MiB stack like a Linux main thread.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Replace the IOCP stub with a readiness-based loop that mirrors the epoll
backend's dispatch order, so the selector state machine is identical on
every platform.  stdin (console or pipe) is not a socket, so RAY_SEL_STDIN
selectors are probed directly and the socket wait is sliced while one is
registered.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- mirror WSAGetLastError()/SO_ERROR into errno for send/recv/connect/
  accept/bind/listen: callers branch on EAGAIN/ECONNREFUSED;
- ipc_send_fn always overwrites errno, so a stale EAGAIN can no longer
  park a frame on a dead socket;
- SO_EXCLUSIVEADDRUSE instead of SO_REUSEADDR (which lets a bind steal
  a port that is in use);
- WSAStartup at load time; sock.h pulls in platform.h;
- verbose IPC capture uses a temp file that works without admin rights;
- the SIGURG out-of-band cancel stays POSIX-only.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- ray_vm_unmap_file only unmaps at a view's own base: UnmapViewOfFile
  drops the whole view for an interior pointer, which freed columns that
  carry a passenger index (munmap is a no-op there);
- ray_vm_alloc_aligned returns its own allocation base, so pools are
  really released by ray_vm_free;
- ray_vm_map_fd_ro maps for real (CSV reads always failed with io);
- crash report via SetUnhandledExceptionFilter;
- heap: file-backed spill stays POSIX-only (docs/architecture/memory.md);
- domain: realpath substitute; symfile paths compare case/separator-
  insensitively so one file never gets two domains;
- aof/csr/hnsw: platform handle for fsync, portable ray_mkdir.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- term.h/profile.h include platform.h and a lean <windows.h>;
- term_write for the Windows console, errno.h and core count in the REPL;
- .sys.info reports page-size and total-mem on Windows too;
- KEY_READ no longer collides with <winreg.h>.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- runner: ';; @requires: posix' marks .rfl files whose fixtures or checks
  need a POSIX shell/filesystem; on Windows they are reported as SKIP;
- shell-free ray_test_rm_rf / ray_test_mkdir_p replace system("rm -rf")
  and "mkdir -p" in C tests; test.h maps the few POSIX helpers tests use;
- tests of POSIX-only behaviour (setrlimit, ENOTDIR, read-only dirs,
  AF_UNIX, file spill, Winsock send buffering) skip with the reason;
- fixture fixes that were latent on any platform: binary-mode CSV
  fixtures, a per-test AOF dir, journal closed before the crash rename.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
No console font Windows ships has U+2023 (checked Consolas, Cascadia Mono,
Lucida Console, Courier New) and the classic console does no font fallback,
so the prompt rendered as '?'.  Use the nearest filled triangle they all do
have, U+25BA, which is also three UTF-8 bytes.

The banner's CPU line said 'unknown': read ProcessorNameString instead.

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

alloc and agg_v2 read peak RSS through getrusage; use
GetProcessMemoryInfo there.  windows_vs_linux.md records the numbers the
port was checked against.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
singaraiona and others added 29 commits October 1, 2026 00:19
…piry (#589) (#658)

(.ipc.send h msg ms) bounds the whole round trip, the request write
included.  On expiry the connection is closed (.ipc.on.close fires)
and io "ipc send timed out after N ms; connection closed" is returned.
Closing is required, not a policy choice: a RESP carries no request id,
so a late reply would be taken as the answer to the next send on the
handle, and a write cut off mid-frame leaves the stream unusable.
Before closing, the peer gets the same urgent-data cancel as Ctrl-C so
a server still evaluating the request stops.

0N means no deadline; 0 and negatives are domain errors.  The C API
gains ray_ipc_send_timeout; ray_ipc_send is unchanged.  The write side
uses the new ray_sock_send_until, so a peer that never reads cannot
hold the caller past its deadline in the send buffer either.

Verified in a network namespace with the flow dropped: a 3000 ms send
fails at 3.0 s and on.close fires.  Against a live server stuck in a
long loop, a 500 ms send expires and the server answers a second
client immediately afterwards, i.e. the loop was cancelled.
* feat(io): add native Parquet queries and native imports

* test(io): add Parquet oracles, benchmarks and fuzzing

* docs(io): document Parquet support and measured limits

* fix(io): preserve nulls in Parquet predicate pushdown

Retain nulls for upper-bound predicates in row filters, residual aggregate filters, and worker readers. Avoid statistics, page-index, and Bloom pruning when the predicate accepts nulls. Cover scan/read parity, indexed all-null pages, native sentinels, and reversed and mixed-column predicates. Preserve the global aggregate row for empty standalone LIKE matches.

* fix(bench): configure the external Parquet reference oracle

Use --oracle and --oracle-queries instead of product-specific flags and paths. Update docs and descriptive evidence labels while preserving measured values, versions, and checksums. Document null-preserving filters and streamed LIKE aggregates.

* fix(io): move Parquet symbol scratch off worker stacks

Reuse heap-backed scratch per column cursor for dictionary interning, plain symbol decoding, and filtered text conversion. Release scratch with its cursor and propagate allocation failures. Verify dictionary and plain strings across batches on a 256 KiB POSIX thread stack under sanitizers.

* fix(io): clarify atomic pointer declarations for cppcheck

Use the equivalent C11 atomic qualifier spelling for the Parquet direct writer null flags. Cppcheck 2.13.0 misparses the parenthesized atomic type in the allocation declaration as an integer; the qualifier spelling preserves the type and passes without a suppression.

* fix(csv): streaming imports sample the same rows as .csv.read

.csv.splayed and .csv.parted inferred column types from the first 4096
rows, while .csv.read samples 4096 rows spread over the whole file.  SYM
vs STR is a sample-cardinality decision, so a column whose leading rows
are near-unique streamed as STR where .csv.read (and dev, which fell back
to a full in-memory read in that case) made it SYM; symbol queries on it
then failed with a type error.

Count the rows, then pick exactly the rows .csv.read would sample, using
the same chunk scanner the import loop uses.  Costs two row-boundary
passes, keeps the import streaming.

* fix(csv): a failed .csv.parted no longer blocks the root silently

A new root is staged in <root>.csv-partial, which a failed import keeps
for diagnosis and which then makes every later import into that root
fail.  The staging directory was claimed before the input was opened,
so a mistyped source path blocked the root, and the retry failed with a
bare io error.

Open the input before claiming the staging directory, and name the
leftover directory in the error (ray_csv_parted_paths shares the path
derivation with the builtin).

* refactor(core): share one CRC-32 between AOF and Parquet

Move the AOF's compile-time CRC-32 table into core/crc32 and add a
slicing-by-8 path (tables derived once in a load-time constructor, so
there is no first-use race).  Parquet page checksums use it next.

* fix(parquet): read RLE booleans, empty row groups and long strings

Files written by common writers with default settings were rejected:

- v2 BOOLEAN columns use the RLE value encoding (3): a 4-byte length
  and a width-1 hybrid stream.  Decoded through the existing RLE reader
  under its own flag, since a nonzero encoding means dictionary
  elsewhere in the decoder.
- A zero-row group carries a dictionary page and data_page_offset 0,
  which failed the 'dictionary follows data' check and the whole file.
  Zero-row groups are now skipped before chunk validation.
- A 4 MB file of 11 KB documents failed 'batch string pool exceeds
  64 MiB': one 65,536-row batch held all 86 MB of strings.  Each row
  group's batch size is now lowered from its STR columns' uncompressed
  bytes per value to keep a pool near 64 MiB (deterministic from
  metadata, so partitioned output counts partitions with the same
  function); the hard limit is the pool's real 4 GiB capacity.

Page CRCs use the shared slicing-by-8 CRC-32: on a 66 MB checksummed
file the read overhead drops from +75% to +15% on one core.

Fixtures come from the stdlib-only generator (new: bool-rle-v1/v2,
empty-group; --long-strings writes a 72 MB file on demand), each
checked against pyarrow 25.0.1.

* docs(parquet): RLE booleans, empty row groups, per-group STR batches

* fix(store): a failed index append leaves the column loadable

Index builds after a splayed import (Parquet and CSV alike) are
best-effort: failures are ignored and the table is published.  That is
only safe if a failed append leaves the column as it was, and it did
not: padding or part of the region could be written before the error,
and without the index marker the loader requires the exact payload
length, so the column then failed to load.

Truncate back to the payload length on any failure, and flush the
region before stamping the marker.  Tested with RLIMIT_FSIZE making the
append fail mid-region: the file was left 40 bytes long and unloadable
before, and is restored now.

* fix(parquet): trim trailing separators from import destinations

"out/" staged in "out/.parquet-partial" and failed because out/ did
not exist; trim the separators as .csv.parted does.  A staging directory
left by an earlier failed import is now named in the error.

* fix(store): no-replace rename falls back to portable primitives

ray_file_rename_new returned an error wherever renameat2/renamex_np
could not be used: EINVAL on Linux filesystems without RENAME_NOREPLACE
(some network and FUSE mounts), NYI on other POSIX hosts.  New-root
.csv.parted and Parquet imports publish through it, so they failed
where a plain rename had worked.

Fall back to an emulation that is still never check-then-rename: for a
directory, mkdir claims the name and rename replaces only that empty
placeholder; for a file, link then unlink.

* fix(parquet): out-of-range timestamps read as null unless strict

A millisecond or microsecond timestamp outside the native nanosecond
range (about 1677-2262) failed the whole read, even in non-strict mode,
so a file using a 9999-12-31 'end of time' sentinel was unreadable.
Read such values as null, as the native null semantics already do for
other unrepresentable values; strict mode still rejects them.

* fix(parquet): clamp out-of-range timestamps instead of nulling them

Review follow-up: reading a 9999-12-31 sentinel as null made it sort
below every timestamp, so (< valid_to 2100.01.01) selected open-ended
rows as expired.  Clamp to the nearest representable instant instead,
which keeps comparisons meaningful.  Strict mode still rejects such
values, now with its own message, and decode errors name the column.

* fix(parquet): size STR batches by the longest dictionary entry

Review follow-up: the batch cap used the chunk's uncompressed bytes per
value, which for a dictionary chunk is the dictionary plus indices, so it
never triggered while every row still copied an entry into the pool.
200k rows of 20 distinct ~8 KB strings (pyarrow's default dictionary
encoding) peaked at 1.06 GB in 4 batches; with ~66 KB strings a batch
would pass 4 GiB.  Read the dictionary page header (and decompress it)
when sizing a group's batches and bound bytes per row by the longest
entry: the same file now reads in 24 batches, 160 MB peak.

* fix(csv): drop .csv.parted staging that holds no partition

Review follow-up: the input check covered only a missing file, so a type
vector that does not match, an empty source or a directory given as the
source still left an empty <root>.csv-partial blocking the root.  When
an import fails before writing its first partition there is nothing to
diagnose: remove the staging directory.  Staging that holds a partition
is still retained.
A grouped select with take: N and no sort aggregated every group and
then kept N. It now finds the first N distinct keys in row order, which
are the groups the engine emits first, and aggregates only their rows:
a parallel pass rejects other rows with a bloom bitmap, and the matching
rows go through the normal aggregation. Taken for N <= 1024 over at
least 64k rows, integer/temporal/SYM keys, and count or integer
sum/avg/min/max; it falls back when the chosen groups hold a large share
of the rows. A range take [start n] now pushes the head limit as an
atom take does.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
* fix(serde): reject graph handles

* fix(serde): reject graph handles during serialization

* test(serde): expect ipc handle rejection type errors

* test(serde): preserve graph handle in table case

---------

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

pq_save_partition's non-durable branch writes the splayed spool batches
and the parted partitions: private leaves under the import's staging
root, published by renaming the whole tree.  Write them with
ray_splay_save_staged_bulk instead of ray_splay_save_bulk.

On dev the two are the same here (the branch runs only without an import
domain, i.e. with no SYM column, so the skipped vocabulary flush has
nothing to write).  It keeps the spool independent of the live-table
writer protocol: with atomic generations (#649) ray_splay_save_bulk
takes a .write.lock in every directory it writes, the spool's cleanup
(which removes exactly the files it wrote, then the directory) failed
on it, and every .parquet.splayed import aborted.
* feat(store): publish splayed replacements atomically

* fix(store): complete atomic splay publication

* fix(store): bound atomic splay generation retention

* test(store): include dirent for generation scan

* fix(store): protect published splay generations during cleanup

---------

Co-authored-by: Anton Kundenko <[email protected]>
Past the anonymous-memory watermark a large allocation is backed by a
raydirect_* file, which was unlinked only when the block was freed. A
process that exited or was killed while holding the block left the
whole preallocated file on disk.

The file is now unlinked right after the mmap succeeds, as a pool's
spill file already is: the mapping keeps the inode, and the kernel
reclaims the blocks on munmap or at process exit. The free path already
handles a block without a path.

Closes #663

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
The library exported only its version, which is the nearest release tag:
a patched build of a tag, a dev checkout and a shallow clone could not
be told apart from the release, while the build already embedded the
commit for the REPL and crash banners. ray_git_commit() returns that
commit ("unknown" outside a git checkout), beside ray_version_string().

The objects that embed the commit now depend on a stamp in build/ that
is rewritten only when the commit changes, so an incremental build
after a new commit no longer keeps the previous hash.

Closes #664

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
#668)

* fix(if): broadcast a one-element condition over vector branches

A reduction in an `if` condition, such as `(> (count x) 3)`, reaches the
eager fill as a one-element BOOL vector rather than an atom. The fill
indexed it per row, so only the first row followed the condition and
the remaining rows read past the vector's single cell:
`(select {k: (if (> (count x) 3) s "") from: t})` returned the first
symbol followed by empty strings.

A one-element BOOL condition against longer branches is now expanded to
a full-length mask, the same way an atom condition already was. The mask
takes the length of the longest branch.

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

* fix(if): read non-BOOL conditions by truthiness, not by byte

The eager `if` fill reads its condition as one BOOL byte per row. A
condition of another type was used as is: an atom through its low byte,
so `(if (count x) x 0)` over 256 rows and `(if (max f) x 0)` with
f = 11.0 took the else-branch everywhere; a one-element I64 vector was
indexed per row past its cell; an I64 column was read byte by byte, so
`(if x x 100)` followed x only on rows 0 and 8.

Every condition that is not a full-length BOOL vector is now turned into
a BOOL mask with the interpreter's truthiness per cell: null, false and
a zero I64 or F64 are false, anything else is true.

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

* fix(select, update): broadcast one-element scalars like atoms

A scalar that reaches a projection as a one-element vector rather than
an atom, such as `(+ (sum x) 0)` or an `if` whose parts are all scalar,
was not broadcast. A select took its row count from the first column,
so `(select {k: (+ (sum x) 0) y: x from: t})` had one row and columns of
different lengths. An update replaced the column with one row, and under
`where:` wrote zeros into the matched rows.

A select now broadcasts one-element columns when another column has the
input's rows; when every column is a scalar the one-row result stays.
An update turns a one-element result into its atom when the target has
another length, so the existing atom broadcast applies, nulls included.

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

* fix(if): reject a numeric branch in a text result

An `if` with a STR or SYM branch has a text result type, and the fills
read the other branch's numbers as string descriptors or symbol ids:
`(if (< x 3) s x)` returned the symbols, then a stray symbol and nulls,
and `(if cond n s)` over two rows lost the number. A text result with a
non-text branch is now a type error naming both types.

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

* fix(if): a zero of any numeric type is false; refuse text conditions

Truthiness treated only BOOL, I64 and F64 zeros as false, so an I32,
I16, U8 or temporal zero took the then-branch of a scalar `if` and read
as true in the scalar `not`, `and` and `or`. The vector `if` copied
that rule cell by cell, so a zero I32, I16 or U8 condition column
selected the then-branch on every row.

Null and the zero of every numeric and temporal type are now false, in
the interpreter and per cell in the vector `if`. A text, GUID or list
condition vector has no truth value per cell and is a type error.

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

* fix(if, update): null literals in text ifs; finish the scalar broadcast

A null literal such as `0N` next to a text branch was refused as a
numeric branch, so `(if c s 0N)`, `cond` with an `0N` default and such
keys in by: and where: stopped working. A null literal now stands for the
text null.

`update ... where:` handed a failed compiled expression to the
interpreter, whose `if` tests one truth value: a mixed-type `if` or a
text condition wrote the then-branch to every matched row with no error.
An expression holding `if` or `cond` now keeps the compiled error; other
expressions keep the fallback.

The scalar broadcast had three gaps. An F32 atom keeps its value widened,
and the update broadcast copied the low half of the double, writing
zeros; one helper now writes every atom cell. `update ... by:` still
rejected a one-element result on groups of two or more rows. A select
over a parted table did not count a parted column's rows, so a scalar
next to it was not broadcast.

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

* fix(if, update): text null for null literals; keep the update fallback

A null literal beside a text branch reached the fills as a number, and
its payload was written as a symbol id: `0N` gave a symbol that is not
null, `0Nf` crashed the symbol lookup on its NaN bits, and `0Nh` named
whichever symbol had that id. The `if` node now swaps such a literal for
the text null of its result type.

Only an `if` that refuses its operands (a text result with a numeric
branch, a condition with no truth value) now marks its graph, and only
that error stands in update. Any other DAG failure inside an `if`, such
as a global list or a cast of a null literal, falls back to the
interpreter as before.

An update by group wrote a STR scalar per group through
store_typed_elem, which has no STR arm, so every cell came out "". STR
cells now go through the string pool.

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

* fix(update): per-group sub-tables share the STR column's string pool

update ... by: gathered each group's STR cells by raw descriptor copy
and never attached the source column's string pool. Every string past
the inline size read as "" inside the group, and a string op on it
aborted on the missing pool.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
* fix(show): print every column and row of a table

`show` formatted its arguments in the REPL display mode, which cuts a
table to 10 columns and 20 rows. It now uses the formatter's unlimited
mode, so a script or client that shows a result gets all of it; the REPL
display keeps its limits.

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

* fix(show): stream the full output instead of building it in memory

The unlimited format pre-formatted every cell of a table into heap
buffers it never checked, and any output was capped at the 2 GiB string
limit, so show on a large value could crash, run out of memory, or fall
back to a truncated print. The format buffer can now drain into a FILE
as it passes 1 MiB, and show writes every value through it: tables in
two passes (column widths over every cell, then the rows), so memory is
O(columns) whatever the row count, with no output ceiling. The REPL
display and print keep their limits. The pre-formatted table path now
checks its allocations.

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

* fix(show): write table cells whole; no repeat after a partial write

The streamed table path kept the 63-byte cap of the REPL's fixed cell
grid, so long text cells lost their tail and closing quote, and a cut
inside a multi-byte character left invalid UTF-8 and a misaligned
border. Streamed cells are now written whole.

If memory ran out after part of the output was flushed, show fell back
to the REPL display and printed the value again. The partial output now
ends with an out-of-memory marker and is not repeated.

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

* fix(show): initialise the flushed flag of the output buffer

fmt_init set every field but the new flushed flag, so ray_fmt_write read
an uninitialised value when memory ran out before any output reached
the sink, and could print a stray marker instead of falling back.

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

* fix(show): pad a streamed column to at most 256 display columns

A column was padded to its widest cell, so one long value padded every
other row of its column: one 10 KB value in a 10k-row table wrote 100 MB,
almost all of it spaces. A column is now padded to at most 256 display
columns; a longer cell is written whole, unpadded, past the border of
its own row, and the output stays proportional to the data.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Anton Kundenko <[email protected]>
Unset RAYFORCE_HOME in the case that expects no home fallback, so an
exported setting cannot change the error matched by grep. Document the
environment isolation in the test comment.

Co-authored-by: GPT-6 <[email protected]>
…) (#670)

The DAG lowers (xbar x b) to x - (x % b), and its promotion turns a
TIMESTAMP operand into I64 and DATE / TIME into I32. Since #657 by-dict
keys compile to the DAG too, so every DAG path (projection, bare by:,
by-dict and parted by-dict keys) returned raw integers where the
interpreter's xbar returns the column's type.

The xbar branch now casts the bucketed result back to the column's type.
The fused compiler types only a CAST from its node, so the cast is the
root: TIMESTAMP is an I64 lane and DATE / TIME are I32 lanes in the cast
kernels, the null-capability table and the fallback executor. A TIME
bucket on a TIMESTAMP column is scaled to nanoseconds as the interpreter
does; a float bucket is declined so the interpreter raises its type error.

The interpreter's vectorised xbar multiplied the null sentinel before the
null post-pass rewrote it; the product now wraps instead of overflowing.
…where: new columns (#676)

* fix(group): a group key with one value is one group

A by: key that evaluates to one value — a literal such as `by: "const"`,
or a let whose body is one — came back as an atom or a one-element
vector and was read as a full column, past its end: random groups on one
core and a crash on the workers.

Such a key is now broadcast to every row, so it forms one group. A key
of any other length than the table's is a length error.

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

* fix(temporal): extract and truncate a date literal as one value

A date or time literal reaches the compiled extract and truncate as an
atom, whose len field aliases its value: (year 2020.01.01) became a
vector of 7305 rows, and an update with it turned a 4-row table into a
7305-row one. An atom input now goes through the builtin's atom path.

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

* fix(string): compiled string ops take a literal as one value

A string literal reaches the compiled strlen, upper, lower, trim, substr
and replace as an atom, whose len field aliases its payload, and the ops
read that many rows past it: an update with (strlen "abc") or (trim " ab")
crashed, (upper (first s)) beside a column returned hundreds of garbage
rows, and substr / replace asked for petabytes. An atom input now goes
through the builtin, which answers it as one value.

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

* fix(update): where: adds a new column instead of dropping it

Under where:, both the copy path and the in-place path walked the
table's existing columns only, so a dict entry naming a new column was
dropped without an error. A new column now holds the expression's value
on the matched rows and null on the rest (zero for BOOL and U8, which
have no null); the in-place path hands such an update to the copy path.

Writing those nulls into a narrow SYM column exposed store_typed_elem's
null write, which cleared 8 bytes per cell whatever the column's width:
on a FILE-domain column of 1, 2 or 4 bytes per cell it wiped the next
cells and wrote past the end. The null write now uses the cell width.

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

* fix(filter): a where: predicate with one value keeps all rows or none

A predicate that reduces to one value — (== (count x) 5), or a scalar
conjunct of an `and` — reached the table filter as an atom or a
one-element vector. It failed the row-count check and the refine's NULL
read as "all pass", so a false scalar kept every row; alone it failed
with a selection mismatch. A constant false was rewritten to a take of
zero rows, which installs no selection, so under a grouping or an
aggregate it grouped every row.

A scalar predicate over a table is now spread over its rows: true leaves
the selection as it is, false makes it empty. A constant false over a
table stays a filter so it reaches that path.

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

* fix(group): a STR atom as an aggregate input is broadcast

materialize_broadcast_input had no case for a STR atom, so (first
(upper "a")) by a key failed with "oom". It is now broadcast like other
atoms; a one-element STR vector also keeps its source's string pool.

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

* fix(string): compiled concat reads a symbol scalar's text

The compiled concat read text from SYM vectors only, so a symbol literal
or a scalar such as (first s) contributed nothing: (concat 'ab 'cd) in a
query came back null and (concat (first s) "x") dropped the symbol.

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

* fix(filter): a scalar where: of any type, on any row count

The scalar-predicate spread only took BOOL values and skipped one-row
tables, so with constant-false filters now reaching it, `where: 0` and a
false conjunct on a one-row table failed with a length error. An atom
predicate of any type is now read with the scalar truth rule (zero and
null are false) whatever the row count; a one-element BOOL on a one-row
table is already a row mask.

A scalar `like` subject in where: used to be a length error; it now
keeps every row or none like any other scalar predicate, and the test
that pinned the error checks both outcomes instead.

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

* fix(filter): scalar where: predicates with take:, in update, and typed

The early-termination filter under take: passed an atom predicate
through as "keep the whole table" and read a one-element BOOL as a
one-row mask: `where: false take: 3` returned every row, and
`where: (== (count x) 10) take: 5` returned one. It now spreads a scalar
predicate over the rows like the plain filter, and a take of 0 keeps the
table's columns.

update ... where: and the select-count fast path rejected a scalar
predicate as a mask of the wrong length; they now spread it the same
way. A symbol or string scalar has no truth value and is a type error.

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

* test(update): BOOL and U8 new columns under where: fill false / 0x00

BOOL and U8 have no null, so a new column of either type under where:
holds false / 0x00 on the unmatched rows. The comment said "null"; it
now names the fill, and tests pin it on the copy and in-place paths.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…ing keys, parallel STR if (#682)

* perf(group): radix grouping scatters into exact offsets

The parallel radix group-by gave every worker its own buffer per
partition, so memory and the serial free loop grew with
workers x partitions, and each group's summation order depended on
which worker claimed which task.

The input is now cut into fixed chunks. A count pass stores each row's
partition id and counts rows per chunk and partition, a parallel prefix
step turns the counts into exact offsets, and a scatter pass writes each
record into one shared payload array. Phase 2 walks each partition's
slots contiguously in input order. Five allocations replace the
per-worker buffers, and they are released right after phase 2.

F64 aggregates are now deterministic and equal the single-worker
result at any worker count. A cancelled run now returns a cancel error
instead of continuing with partial buffers.

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

* perf(select): run derived string keys as a per-value program

A group key computed from one SYM column is evaluated once per distinct
value. That evaluation ran as a chunk DAG of about one full pass per
operator, then deduplicated and interned the keys serially, ordered the
values by position with a per-value popcount, and the outer select
filtered all rows once more before the vocabulary rewrite filtered them
again.

Keys built from let, if, cond, and/or/not, comparisons, + - *,
str-find, substr, strlen, within and nil? now compile into a
straight-line program over string-view, I64 and BOOL registers. It runs
on the workers in batches of 64 values without intermediate vectors.
Other keys keep the chunk DAG. Deduplication runs in 64 hash partitions
and interns keys in first-row order. Ordering by position uses a word
rank prefix, and the vocabulary rewrite runs before the outer where
filter.

The where: selection the outer select built for this path was retained
and never released, about 256 KB per call on a 70k-row table; with the
rewrite ahead of the filter that selection is no longer built.

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

* perf(if): build a STR if with a SYM branch on the worker pool

An `if` whose result is STR and whose branches are SYM (or SYM and STR)
columns or literals interned nothing but still ran serially, row by
row. For tables of at least RAY_PARALLEL_THRESHOLD rows, with no
selection or one keeping at least 90% of the rows (the build writes a
pool for every row, which a filtered result would keep), it now builds
the result on the worker pool in two passes:
row lengths, then a serial prefix over one string pool in row order,
then descriptors and bytes. Symbol text is read from snapshots taken
before any worker runs (runtime-domain strings, or the raw FILE-domain
vocabulary); a cell a snapshot cannot read (a symbol appended to its
domain later) sends the `if` to the selected arm, as before.

exec_if hands the condition it already evaluated to the eager arm, which
used to evaluate it a second time.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…ond branch evaluation in STR if) (#683)

* perf(group): split mid-size radix inputs across every worker

The 16384-row minimum chunk capped phase 1 at ceil(rows / 16384)
chunks, so an input of fewer than 16384 rows per worker counted and
scattered on only part of the pool. An input with at least 4096 rows
per worker now gets one chunk per worker.

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

* perf(if): route a SYM branch past its mapped symbols to the selected arm up front

A SYM column whose FILE domain gained positions past its mapped file (new
symbols of a live insert) makes the pooled text build decline. That was
found only after both branches had been materialised for the eager arm,
and the selected arm then evaluated them again. The domain counts are now
compared before choosing the arm, segment by segment for a partitioned
column, and such an `if` takes the selected arm directly.

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

* perf(if): resolve unreadable SYM cells row by row, without a domain gate

The check added before the eager arm compared a FILE domain's count with
its mapped snapshot, so after one new symbol was interned anywhere in the
domain (a live insert into a sibling table) every `if` over every column
of that domain lost the pooled text build for the rest of the process,
although only a cell past the snapshot makes the build decline.

The check is gone: the build is attempted as before and declines only on
an unreadable cell. When it does, the branches it already materialised are
resolved row by row in place, instead of the selected arm evaluating both
branches again.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…llback for update new columns and update by: (#690)

* fix(query): keep a SYM column's type through the eval-fallback projection (#689)

A select that projects a SYM column beside a projection the DAG declines
(temporal + - *) lands in the eval-level projection fallback.  That path
evaluated a bare column name per row and collected the cells, and the
cell collector never collapses SYM / STR / GUID atoms into a typed
vector, so `name: name` came back as a LIST of boxed sym atoms and an
inner-join on it matched nothing (rayforce-py#24).

A bare, unquoted column name in a fallback projection now takes the
column itself, as the DAG path does for the same expression.  Parted,
mapcommon and slice columns keep the per-row read.

* fix(query): collect sym-valued fallback projections as a SYM vector

The eval fallback's per-row and per-group cell collectors collapsed every
scalar kind but SYM / STR / GUID into a typed vector, so a sym-valued
projection — `(if (> i 1) 'hi 'lo)`, or a quoted column name `'name` —
beside a projection the DAG declines came back as a LIST of boxed sym
atoms, where the DAG path returns SYM for the same expression.

store_typed_elem writes SYM cells (runtime-domain id, or a domain lookup
for a file-domain target), so SYM atoms now collapse like the other
scalars; a mixed-type projection still demotes to LIST.  STR and GUID
stay excluded: STR has no typed-store arm.

* fix(query): eval fallback for update of a new column and update by:

An `update` adding a NEW column, and `update by:`, failed with "failed
to compile ... expression" whenever the DAG declined the expression
(temporal + - *), while the same expression worked as a select and as an
update of an EXISTING column, which already falls back to eval-level
evaluation with the columns bound.

Both sites now go through update_eval_on, the DAG-then-eval sequence the
existing-column sites use.

* fix(query): collect STR and GUID fallback projections as typed vectors

The eval fallback's per-row and per-group cell collectors collapsed
scalars into a typed vector except STR and GUID, so a STR-valued
projection — `(if (> i 2) str "zz")` — was STR on its own but became a
LIST of boxed atoms as soon as a projection the DAG declines (temporal
+ - *) sat beside it: a column's type depended on its neighbour.  GUID
behaved the same way.

STR cells are now appended through the string pool (ray_str_vec_append,
one cell per row, so the vector's length is the rows collected so far),
and GUID atoms go through store_typed_elem's existing GUID arm.  A
mixed-type projection still demotes to LIST.

* fix(query): flatten a parted table before the select eval fallback

The fallback evaluated projections straight over the parted table, and
its per-row reader has no arm for segmented columns, so any projection
the DAG declines (temporal + - *) over a .db.parted.get table raised
`type` — on its own, not only beside a SYM column.  The table is now
flattened once before the projection loop (query_materialize_parted_table,
the per-column flatten update already does), after the where:
materialization so a filtered table goes through unchanged.

parted_f64_agg.rfl asserted that `((fn [c] (sum c)) 'ts)` in a select
projection over a parted table raises `type`.  That per-row lambda sums
one cell at a time and is no aggregation gate: over a flat table it
returns the cells, and it only raised here because of the reader gap
above.  The test now exercises the whole-column gate it describes,
`(sum (at Pts 'ts))`, and checks the projection matches the flat result.

Also moves select_fallback_passthrough_col above
is_whole_column_projection's doc comment, which it had split from its
definition.

* fix(query): row semantics, length check and by: promotion for the update fallback

Second-pass review of the update fallback (3e47c0e):

- A vector result of another length was added as-is at both no-where:
  sites (new column, existing column), leaving the table ragged.  Both
  now raise the where: arm's `length` error.
- The interpreter pass evaluated the expression once with whole columns
  bound, and the interpreter's `if` tests one truth value, so
  `(if (> i 2) 1 (- ts ts))` wrote the then-branch to every row.  An
  `if` that reads a column in row position is now evaluated per row
  (eval_expr_per_row); everything else keeps the whole-column pass,
  which the vector builtins, aggregates and whole-column verbs need.
  The existing-column and where: sites go through the same helper, so
  the same wrong result on an existing column is fixed with it, and
  update by: gets it inside each group.
- update by: took the column type from the first group and cast later
  results into it (2.5 stored as 2, a TIMESTAMP as a TIME).  A group
  result of another type now promotes the column to the wider numeric
  type; a non-numeric mismatch is a `type` error.
- When the planner compiled the expression and its execution failed (a
  scan of a misspelt column: `schema: column 'x' not found`), that error
  is reported again rather than the interpreter's `name` error.
- The per-group SYM collapse is now covered on a plain grouped select.

* fix(query): reject an if over a column that also aggregates in the update fallback

Per row, an aggregate over a column sees one cell, so
`(if (> i (avg i)) (+ ts 1) ts)` compared each row with itself and gave
wrong data where the update used to fail to compile.  Such an `if` is
now an `nyi` error on every form (plain, where:, by:) until the
fallback can reduce aggregates first (#692).

The guard is narrower than "contains any aggregate": an aggregate over
a global or a literal is the same value on every row and goes through,
which query_update_coverage.rfl relies on (`(if true (count GL) x)`).

* fix(query): free the kept planner error; passthrough honours a lexical local; LIST length

Audit of 475af9c:

- update_eval_on kept the planner's error to report if the interpreter
  failed too, and discarded it with ray_release, which returns early on
  an error object: the block leaked on every fallback (once per group
  under by:).  Error objects go through ray_error_free.
- select_fallback_passthrough_col returned the table column for a bare
  name even when a lexical local (a lambda formal) of that name was in
  scope; the DAG and the per-row pass let the local shadow the column.
  Same guard now.  A LIST column (type 0) is taken as-is like any other.
- The update length checks tested `type > 0`, which skipped a LIST
  result (type 0), so `(list 1 2)` still left a 5-row table ragged.
…es, cgroup RAM budget (#695)

* fix: int-vs-float compare, compiled not/if kernels, fallback aggregates, cgroup RAM budget

Closes #694, #693, #692, #691, #688.

- #694: the integer-column comparison fast path in binary_range checked only
  the column type, so a computed F64 scalar (an aggregate such as (avg i), or
  arithmetic on one) left r_i64 at 0 and every row compared against 0.  Float
  scalars now take the generic double path.  Affected all six comparison ops,
  I32/I16/BOOL/TIMESTAMP columns, where: and update.
- #693: a REG_SCAN of a BOOL column is widened to 8-byte lanes, but the
  BOOL-output NOT kernel read the source as bytes.  NOT and (as 'BOOL ...)
  now dispatch on the source lane width.
- #691: promote() fell through to BOOL for GUID branches of a compiled `if`
  and the fill read the 16-byte cells as bytes.  Two GUID branches keep GUID
  with a 16-byte copy fill; a GUID beside another type, or a LIST-column
  branch, is declined so the projection falls back.
- #692: the select eval fallback scattered every projection per row, so an
  aggregate beside a projection the DAG declines saw one cell.  A projection
  with an aggregate and no row column outside it is evaluated once and
  broadcast as the DAG path does: to nrows beside a row projection, to one
  row when every projection is an aggregate.
- #688: the default anon watermark is now min(physical RAM, cgroup memory
  limit).  ray_os_cgroup_mem_limit walks cgroup v2 memory.max and v1
  memory.limit_in_bytes up the ancestor chain; -m still wins and
  .sys.info total-mem stays host RAM.

* fix(query): pre-reduce aggregates on the eval fallback, GUID collapse, temporal-vs-float compare error

Follow-ups surfaced while fixing #691, #692 and #694.

- A projection mixing a row column with an aggregate in one expression
  ((+ i (max i)), (if (> i (avg i)) 1 0)) was scattered per row by the
  eval fallback, where the aggregate folded one cell.  Every maximal
  aggregate call is now evaluated once over the whole table and spliced
  into a rewritten copy of the expression before the per-row pass.
- The per-row and per-group collapse excluded GUID atoms out of caution,
  so a fallback projection yielding GUIDs came back as a LIST of atoms.
  store_typed_elem has handled GUID (and GUID nulls) all along; uniform
  GUID rows now collapse to a GUID column, mixed rows stay LIST.
- Comparing a temporal column with a float (the F64 avg of the column, or
  a float literal) compiled in the DAG and compared as doubles, where a
  TIMESTAMP near 2024 has a 128 ns ULP, so (> ts (avg ts)) was all false.
  The compiler now raises the interpreter's "cannot compare timestamp and
  f64" error, and a projection the compiler rejects outright is returned
  as an error instead of falling back.  Integer scalars and same-typed
  temporal compares stay on the exact int64 kernel.
…BOOL where: predicates (#696)

* fix(query): temporal if null, scalar selects under where:/take:, non-BOOL where: predicates

Closes #673, closes #674, closes #675, closes #678, closes #679.

- #673: `(if c d 0N)` with a temporal branch promoted to I64.  A temporal
  branch beside a bare null literal (0N, 0Nf, 0Ni) now keeps the temporal
  type and the literal is swapped for the typed null, the rule #668 set
  for text branches.  A non-null number beside a temporal still promotes.
- #674: `(as 'STR ...)` in a projection already returns STR since the STR
  collapse of #690; pinned with a regression test.
- #675: a select whose every output is a scalar expression over aggregates
  left the where: selection installed on its one-row result, and the final
  gather failed with "sel_compact: selection nrows mismatch".  OP_SELECT
  drops the selection once no column carries the input's rows.
- #679: HEAD(GROUP) compacted a no-match where: into an empty table before
  a keyless group, which then emitted no row.  A keyless group keeps the
  selection lazy, as the plain OP_GROUP path does, so take: applies to its
  one output row.
- #678: where: predicates that are not BOOL vectors gave shape-dependent
  answers.  An I64 column reached the filter kernels, which read a mask as
  one byte per row; the count/aggregate shapes ignored it; the take: path
  passed the whole table through; `'abc` was constant-folded to keep every
  row.  One rule now applies at every site (ray_where_mask_coerce): a BOOL
  vector of row length is the mask, a scalar with a truth value holds for
  every row or none, any other vector is a type error.  exec_filter refuses
  a non-BOOL mask outright.

* fix(query): review follow-ups for #673, #675, #678, #679

- #675 on a one-row table: a scalar and a row column have the same length,
  so OP_SELECT reads the column ops (op_tree_is_scalar) instead; a
  scalar-only select under a failing where: is one row at any row count.
- #679 for an aggregate of an expression: the plain OP_GROUP sparse
  pre-compaction no longer fires for a keyless group, the same exemption
  the HEAD arm got, so a no-match where: still yields the one row.
- #673: a null literal of another temporal type (`(if c ts 0Nd)`) is now
  swapped for the branch's own typed null instead of folding both widths
  to I64 with foreign sentinels.
- #678: `and` / `or` over a non-boolean column is a type error at compile
  time (dag_bool_operand_ok), and every where: site returns that error
  instead of retrying the interpreter, whose scalar `and` kept every row:
  update's two mask paths, the count-only path and compile_where_predicate.
  A truthy scalar where: no longer allocates and discards a mask.
- Comments that still described a numeric-column mask corrected; the
  fallback where path, the count-only path and update are now exercised by
  where_pred_shape_678.rfl.
…ount literals (#697)

* fix: mixed temporal compares, narrow-lane casts, fallback not/cast, count literals

- The eval path compares DATE, TIME and TIMESTAMP on one nanosecond scale
  (temporal_as_ns); the compiled comparison compared raw lane values, so
  `where: (> ts 2024.01.02)` kept every row of a TIMESTAMP column and a
  DATE column against a TIMESTAMP literal kept none.  make_cmp now rewrites
  a literal of the other temporal type in the column's units: exactly for
  a TIMESTAMP column, rounded as the operator needs for a DATE or TIME one,
  clamped to the lane.  The column keeps its fast paths and partition
  pruning (a date-partitioned `date` key is recognised), and no cell is
  scaled.  An equality the column's units cannot express is written as a
  comparison with the same constant answer; two non-literal sides are left
  to the eval path.  temporal_as_ns saturates instead of overflowing for
  dates outside the TIMESTAMP range.
- The count-over-where fast path compared the column with the literal's
  raw integer: a float literal decoded to 0 and a DATE or TIME literal was
  compared in its own units.  A float literal takes the general path; a
  DATE / TIME literal against a TIMESTAMP column is compared in saturating
  nanoseconds, any other temporal mix takes the general path.
- A narrowing cast leaves an I32, I16 or one-byte lane, and the next
  compiled conversion read it as int64: (+ (as 'I32 i) 1.5) gave
  [8.59e+09 ...].  The F64 / I64 / I32 / I16 / U8 targets read narrow
  sources at their own width.
- In the element-wise fallback for nullable columns, `not` over a non-BOOL
  column was caught by the I64->BOOL cast arm or had no arm, and left the
  result unwritten; it now covers every numeric width (zero and null being
  "not true") and is a type error for other input.  A narrow-to-narrow cast
  wrote 8-byte doubles into the narrower result (a heap overrun); it now
  converts per target width.
- `not` in the eval path answered one value for a numeric vector; it is
  element-wise over numeric and temporal vectors, as the compiled `not` is.

fused_group_parity.rfl pinned the raw-unit answer of a TIMESTAMP-vs-DATE
filter (3 rows); the normalised answer is 2.

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

* docs: `not` is element-wise over numeric vectors; pin its `if` interaction

`(not vec)` now returns a BOOL vector for a numeric or temporal vector,
as it already did for a BOOL one, so `(if (not [1 2]) 'a 'b)` takes the
then-branch (a vector is truthy). The function table says so and a test
pins the `if` case.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Anton <[email protected]>
…ion column, renameat2, narrow nil? (#699)

* fix(store): call renameat2 through syscall() so the engine links against glibc < 2.28

ray_file_rename_new called the renameat2 wrapper with RENAME_NOREPLACE;
both arrived in glibc 2.28, so the engine no longer linked against the
glibc 2.17 baseline it supports. The same syscall is now reached through
syscall(SYS_renameat2, ...) with the flag value spelled out; a kernel
without it still answers ENOSYS and the emulated rename runs.

Closes #681.

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

* fix(expr): nil? over a narrow lane reads it at its own width

A narrowing cast leaves an I32, I16 or one-byte lane, and the compiled
ISNULL kernel read every non-F64 lane as int64 against NULL_I64, so
(nil? (as 'I32 v)) in a select was false on every row. The I32 and I16
lanes are checked against their own null sentinels; a byte lane has no
null.

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

* fix(store): one writer per journal base

The journal is single-writer: an entry is two writes, a roll renames the
live log, a snapshot writes a fixed temp name, and a purge unlinks files
another process may still write. Nothing stopped a second process from
opening the same base, which broke the framing (replay stopped at the first
interleaved entry) and stranded entries in a renamed archive.

Opening a journal (.log.open, -l, -L) now takes an exclusive lock on
<base>.lk, held until .log.close, .log.purge or exit; -l / -L take it
before replaying. A second opener fails with `io` and logs that the journal
is open in another process. .log.purge takes the lock too, and removes the
lock file last while still holding it; an opener whose lock landed on a
removed file retries on the new one. ray_file_trylock_ex is the non-blocking
exclusive lock (flock LOCK_NB, LockFileEx FAIL_IMMEDIATELY).

Closes #687.

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

* fix(store): a failed first write removes the directories it created

The first write of a table directory writes in place, and on failure only
staged generations were cleaned up.  The table directory stayed behind
with its .write.lock and any partial columns but no .d schema, and every
.db.parted.get of the database then failed with "cannot read .d schema".

ray_splay_write_begin now records the shallowest component of the table
path that did not exist, and when a first write fails
ray_splay_write_finish removes the table directory and the parents it
created while they are empty.  On POSIX the removal happens under the
write lock.  A failed rewrite of a published table is unchanged.

Closes #684

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

* fix(query): keep the partition column on a no-match where: and under take:

A select over a parted table lost the partition column (date, part, ...)
when its where: matched nothing, and always when it had take:.  The empty
result of sel_compact built each column with ray_vec_new of the column
type, which fails for MAPCOMMON, and exec_filter_head skipped MAPCOMMON
columns outright.

The empty result now takes the column through materialize_mapcommon_head
with zero rows, and exec_filter_head gathers it for the matched rows with
the new materialize_mapcommon_gather.

Closes #677

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

* fix(expr): nil? over a narrow lane of a null-free source is all false

A narrowing cast of a column without nulls truncates, so a value such as
-32768 lands on the I16 sentinel without being null.  The narrow ISNULL
arms read the sentinel unconditionally; they now apply only when the
source lane is nullable.

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

* fix(store): journal lock follows its base, is close-on-exec, purge stays best-effort

- A roll that could not reopen its log left the lock of its base held,
  and opening another base then reused it instead of locking the new
  base.  The lock now remembers its path; a lock of another base is
  dropped and the new one taken.
- The lock fd was inherited by programs started with .sys.exec, which
  kept the journal locked after the process exited.  It is now
  close-on-exec.
- .log.purge failed with io when the lock file could not be created (the
  directory is gone).  Purge now refuses only while another process
  holds the lock and is best-effort otherwise; a lock failure other than
  a held lock is reported with its cause.

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

* fix(store): first-write cleanup stays inside what the write created

Follow-up to the cleanup of a failed first write:

- A table path that climbs out of a new directory with ".." (new/../db)
  named an existing directory, and the cleanup removed it.  No cleanup
  is recorded when a ".." follows the first missing component.
- The cleanup unlinks .write.lock while writers wait on it.  A waiter
  then held a lock nobody else could find, recreated the directory and
  wrote in place next to a writer that had locked the new lock file.
  After taking the lock a writer now checks that it still names
  root/.write.lock and starts over otherwise.
- Without the lock (begin failed before taking it) the table directory
  is only removed while empty.
- Failures after the directories were created but before the lock was
  opened now go through the cleanup too, and a lock path that does not
  fit is rejected before anything is created.
- On Windows "\" separates components as well.

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

* fix(query): take: 0 over a parted table keeps its columns

exec_filter_head answered take: 0 with take over the table, which a
parted table rejects, and fell back to a table without columns.  It now
gathers zero rows through the general path, which keeps every column,
the partition column included.

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

* fix(store): remove the write lock last; purge goes unlocked only when the directory is gone

- The failed-first-write cleanup unlinked entries in directory order, so
  .write.lock could go while columns were still being removed; a new
  writer then created and locked a fresh lock file, wrote in place, and
  lost files the cleanup removed by name.  The cleanup now empties the
  directory except its lock file, unlinks the lock file, and removes the
  directory only while empty: a writer that created a new lock file
  keeps it.  On Windows the contents go while the lock is held.
- .log.purge went on without the lock whenever <base>.lk could not be
  opened, also when it exists but is not writable by this process while
  another one holds it.  The lock file is opened read-only (flock needs
  no write access) and purge goes on unlocked only when the directory is
  gone.
- The sibling-parent retry relies on errno, which the Windows
  ray_mkdir_p does not set; it is POSIX-only.

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

* fix(store): open the journal lock file for writing, read-only only when it is not ours

flock emulated over byte-range locks (NFS, SMB) takes an exclusive lock
only on a writable fd, so the read-only open failed there.  The lock file
is opened read-write, and read-only only when that is refused (EACCES,
EROFS), which still serialises with another user's process.

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

* fix(store): journal lock reports why its file cannot be opened

A lock file that cannot be created (the journal directory is not
writable) failed .log.open with a bare io; the cause is now printed.
Purge goes on without the lock only when the first open finds the
directory gone; a read-only fallback that finds no file retries instead,
so a lock file removed between the two opens is never taken for a
missing directory.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…ere before it (#702)

The first-write cleanup of #699 ran only when the writer had created the
table directory itself.  One that existed without .d and .current, pre-made
by an operator or left by a killed first write, kept its .write.lock and
partial columns after a failed write, and every .db.parted.get of the
database then failed with "cannot read .d schema".

A directory without a schema is not always a dead table (the database root
has none either), so the writer removes only what it produced: begin takes a
snapshot of the directory's inodes right after the lock, and on failure
finish removes the entries the snapshot does not know; column files are
renamed into place, so a leftover the write rewrote goes too.  The lock
file and the directory go once nothing else is left, and directories above
it only when begin created them.  The .d/.current check is repeated under
the lock before clearing, so a stat error in begin cannot clear a table
another writer published meanwhile.

Two smaller gaps from the same review: a lock wait cut short is retried
without waiting, and when that fails for any reason but another holder the
bare lock file in a new directory goes with it; ray_journal_open releases
its lock when the append step rejects the base length.

Closes #700
#704)

* feat(idx): incremental chunk-zone accumulator for streamed columns

* feat(idx): incremental STR dictionary accumulator with a cardinality cap

* refactor(store): share the inline index region writer and marker stamp

* feat(store): stream writer builds the column index inline and publishes it with the column

* feat(store): build a hash index for one streamed column from its file

* perf(csv): splayed conversion publishes inline indexes instead of re-reading the columns

* perf(parquet): splayed conversion publishes inline indexes; direct path merges per-group zones

* docs: streamed splayed indexes

* fix(store): empty-string dict accumulator UB, 64-bit index region offset, release symbol domain before hash re-read, mmap the hash re-read

* docs: streamed splay index contracts and rationale comments

* test(store): include sys/stat.h unconditionally; the stream zone test uses stat on every platform

* fix(store): streamed zone decides nulls by sentinel and publishes HAS_NULLS when the payload holds one

* fix(store): an index region that cannot be written is dropped, the column still publishes

* feat(idx): drop the streamed dictionary cardinality cap

* perf(store): write the index region straight from the index children

ray_col_write_index_region allocated a staging buffer the size of the
region, copied the inline layout into it and wrote it out; for an
8-byte hash column of 100M rows that is a 4.5 GB allocation, copy and
write on one thread.  ray_index_inline_write_file now writes the same
bytes block by block from the index children through one fwrite per
block.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* perf(io): finish streamed columns in parallel; hash candidates in RAM-budgeted waves

The converters closed every column in a serial loop, and with the
indexes built during streaming that loop did the dictionary assembly
and the region write of each column on the main thread; the hash
candidates were then re-read one after another.  On a 100M-row,
105-column CSV on a 2-socket machine the hash phase alone ran 74 s
after the columns were published, against 48 s for the whole index
pass of the previous design.

ray_col_stream_close is split into finish (pool merge, index finish,
region, header, fclose, fsync) and publish (rename, directory sync).
ray_col_stream_close_all runs one finish task per column on the pool
and publishes serially in column order; any failure aborts every
column and publishes nothing.  ray_col_stream_hash_all builds the hash
candidates as pool tasks in waves of W columns with the serial builder,
W = clamp(ram_limit / 4 / (58 B * rows), 1, candidates), from the
runtime's RAM limit (what -m overrides); a single candidate keeps the
parallel builder.  Both converters use the two helpers; the publication
order (symfile flush, finish, publish, domain release, hash, .d) is
unchanged, as is every output byte.

RAY_CSV_TRACE now also covers the splayed path: per-chunk scan/parse/
append, the longest append tasks, symfile flush, finish/publish, domain
release, per-column hash build/write with key and group counts.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* perf(store): build a lone hash candidate on the calling thread so its builder stays parallel

A hash wave of one column was still dispatched to the pool, which raises
ray_parallel_flag and sends the builder down its serial path while the
other workers idle.  A lone candidate now builds on the calling thread.
The wave width moves to the pure ray_col_stream_hash_wave.

* fix(idx): align the streamed index head; neutral hash trace label

* test(store): streamed region bytes match the buffered writer; a failed finish publishes nothing

---------

Co-authored-by: Serhii Savchuk <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
…ts the base (#701)

* fix(store): ray_journal_open releases the lock when open_append rejects the base

ray_journal_open takes the journal lock before recovery, and
ray_journal_open_append rejects a base that leaves no room for the file
suffixes before it reaches its own lock handling.  The lock stayed held
with no base recorded until another base was opened or the process
exited.  The failed open now releases it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* test(journal): size the long base after resolving the temp dir

On macOS /tmp is a symlink to /private/tmp; a 1019-character base
built from the unresolved prefix exceeds PATH_MAX after expansion and
the lock open fails with ENAMETOOLONG before open_append rejects the
base.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
* fix(hnsw): preserve layer topology during build and load

* fix(hnsw): repair legacy layer links on load

* test(hnsw): cover legacy links across upper layers

* fix(hnsw): report repaired legacy links

---------

Co-authored-by: Anton Kundenko <[email protected]>
…ived keys, table-stack grouping (#705)

* perf(pool): contiguous per-worker ticket ranges with tail stealing

Every thread claimed the next ticket of a dispatch window from one
shared cursor, so the slices a worker ran were scattered over the
vector, differed from run to run, and 48 threads contended on one cache
line every 8192 rows.

A window is now split into contiguous ticket ranges, one per worker
(main included), claimed in order from the head; a worker out of
tickets steals half of a victim's remaining tail.  Each range is one
64-bit head|tail word on its own cache line, holding absolute ticket
numbers; a window parity orders the publication of the ranges against
installs of stolen chunks.  The victim order is a hook for a NUMA-aware
policy.  pool.h states the order contract: the tasks of a window run in
any order on any worker.

RAY_POOL_STEAL=0 keeps the shared cursor; RAY_POOL_TRACE=1 prints the
own/stolen histogram per worker when the pool is destroyed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(select): fused take: early stop no longer assumes tasks run in row order

ftk_task_fn returned as soon as its worker held k passing rows and only
appended to its list, which is right only when later tasks always cover
later rows.  Each worker now keeps a sorted bounded list of the k rows
nearest the scanned end and drops a chunk only through the global
cutoff, so the first k matches by position are returned whatever the
order the tasks ran in.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* perf(query): derived string keys intern into a private domain; key domains cached; selection-bounded spread

Derived by: keys no longer grow the runtime symbol table: they are
interned into a domain owned by the key vector and released with it;
the domain of a by: expression is kept in a small LRU across executions
(cleared by .sys.gc), so a repeated query only probes.  The spread route
computes keys only for the rows the where: selected, in-memory tables
take the chunked program path instead of per-row interning, and the
vocab route restores dictionary order explicitly.

ray_sym_domain_intern_batch uses one table block and one arena region
per batch, assigns positions serially and inserts atoms by position
range per task, instead of one table and region per partition with
atoms written in batch order from every partition at once.  The
representatives list is built in parallel.  .sys.mem reports sym-count
and sym-bytes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* perf(group): table-stack pre-aggregation for low-cardinality int and sym keys

A grouping whose key has few distinct values went through the radix
scatter like any other.  Each task now aggregates into an
open-addressing table with top-bit slot placement, pushes a full table
onto a stack and starts a new one, and switches to raw scatter once its
keys are at least half distinct.  The radix emit phase is shared by both
strategies.

Admission: a serial pre-check of 512 scattered rows rejects a key with
at most one repeat among them without any dispatch; otherwise a parallel
sample of 8192 single rows (the selected rows under where:) feeds a
Chao1 estimate, and the strategy is taken only when the estimate is at
most 24576 groups, repeats per task are sufficient, at most two thirds
of the sampled rows carry a singleton, and the tables of all workers fit
three quarters of the last-level cache.  Keys that repeat in runs and
composite keys with a near-unique component stay on the radix path.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs: RAYFORCE_CORES, RAY_POOL_STEAL and RAY_POOL_TRACE

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* perf(query): drop the key-domain cache; a fresh key domain per execution

The domain of a derived by: key is built anew for every execution and
released with the result; its positions follow the first appearance of
each key in row order whatever the thread count, so unsorted group
order is a function of the query alone, not of what ran earlier.  The
cross-execution cache and its hooks are gone.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
…706)

* fix(query): a select of aggregates and scalars over them is one row

A select whose outputs were a bare aggregate and a scalar expression over
aggregates (`{s: (sum x) k: (+ (sum x) 1)}`) came back with one row per
input row.  The mixed outputs route through OP_SELECT, which broadcast the
aggregate's atom to the input's rows as soon as it was computed; the
broadcast column then counted as one carrying the input's rows and the
one-element `k` was widened beside it.

OP_SELECT now enlists an atom as a one-element column and widens it only
once another column is found to carry the input's rows.  A select of
literals alone keeps the input's rows; beside an aggregate a literal is
one more scalar, as in a keyless group.  The eval fallback takes the same
rule: a literal, or an expression over earlier one-value outputs
(`{m: (max i) y: (+ m 1)}`), is one value; a call over literals
(`(til 8)`) stays a row projection.

Enlisting also covers atom types the old broadcast rejected with a type
error (date, i32, guid; f32 widens as a one-element list).

Closes #698.

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

* fix(query): an output over a one-value alias reads it at row 0

In an all-scalar select the eval fallback binds each one-value output as
a one-row column, and a later output with no aggregate of its own was
evaluated over that whole column: `(type m)` saw `[I64]` and `(til m)`
failed on a vector argument.  It is now evaluated at row 0, so it reads
the value as the row path reads a cell.

Pins the one-element vector literal: alone it keeps the input's rows, as
it already did beside an atom literal.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…w expressions (#708)

* fix(query): group by a computed key when an output needs the eval-level pass

A select grouped by a computed key (`by: (% v 3)`, `by: (substr s 0 2)`)
failed with "nyi: eval-level groupby requires scalar key" whenever an
output was not a plain aggregate: a `distinct` aggregate or a row
expression routes the select to the eval-level grouping, which read its
key only from a named column.

The key is now evaluated over the selected rows into a hidden column and
grouped on.  The evaluation is the by-dict value's, moved into a shared
group_key_eval(): compiled as a projection (row-wise `if`), partitioned
columns flattened.  The source columns stay intact for the outputs, the
input table is not modified, and the result's key column is named as the
DAG path names a computed key (`key` when an output spells the same).  A
literal key (`by: 1`) is one group.

Closes #707.

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

* perf(query): plan a bare computed by: key as a one-key by-dict

A computed key beside an output the DAG group cannot serve (a `distinct`
aggregate, a row expression) took the eval-level grouping, 10-20% slower
at 10M rows than the same query with the key written as a by-dict
`{k: expr}`, which materializes the key once and stays on the DAG path.

select_plan_computed_key rewrites that shape to the by-dict form under a
hidden key name, with from: the table already evaluated and a sort key
naming the derived key column redirected to it, and the result's key
column is renamed to the name the DAG path gives a computed key.  It
applies the routing's own test for an output that needs the eval pass,
so plain-aggregate shapes are untouched.  The eval-level materialization
remains for a literal key.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
… the workers (#709)

* perf(group): build the per-group slices of a sparse where: from the selection

The eval group path builds per-group row slices for count(distinct) and
the other slice consumers from row_gid, which spans the whole table with
-1 for a filtered row.  Under a where: that kept a few thousand rows of
100M it still read all of row_gid twice, sized a histogram per task of
the table (tasks × groups int64s) and ran the serial prefix over it.
When the selection keeps at most 1M rows and at most an eighth of the
table, two serial passes over the rows it lists build the same slices,
rows ascending within a group.

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

* perf(group): size the per-group slice histograms by the workers, walk any selection

The parallel build of the per-group row slices (count(distinct) beside
other aggregates) kept one histogram row per 8192-row task, n_tasks ×
n_groups int64s for the counts and as many again for the cursors, and
ran the prefix over all of them serially with a stride of a histogram
row — at 100M rows and a few thousand groups hundreds of MB and tens of
millions of strided cells, whatever the worker count or the rows a
where: kept.

Tasks are now contiguous runs of morsels, one per worker (fewer when
n_tasks × n_groups would pass 8M cells), cut so each visits about the
same number of rows; the counts become each task's cursors in place
through a row-wise prefix.  Under a where: every pass walks only the
rows the selection keeps, at any size, so the 1M-row cap of the serial
selection walk is gone and below 128K visited rows the same code runs as
one task.

Closes #710.

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

* test(group): a neutral token in the sparse-where slice fixture

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@singaraiona
singaraiona merged commit dc9b12a into master Oct 4, 2026
12 checks passed
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.

4 participants