Repository navigation
chore(release): reconcile master ancestry for v3.0.1 - #985
Merged
Merged
Conversation
* fix(group): bound the tied groups the radix top-N selection keeps 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]> * feat(lang): add a `while` special form 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 * feat(lang): add `times` and `fold-while` 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. * perf(join): skip per-cell key null tests on provably null-free columns 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 * fix(system): validate launcher and timeit integer arguments * fix(cli): reject a flag as another flag's value, and unknown options 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 * fix(exec): release the input table of window, sort and limit unconditionally 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]> * test(lang): pin the refcount of a table across window, sort and limit 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]> * fix(exec): the reduction case owns its input too 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]> * perf(pool): wake only the workers a dispatch can keep busy 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. * build: Windows (MSYS2 CLANG64/MINGW64) toolchain in the Makefile 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]> * feat(core): WSAPoll event loop for Windows 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]> * fix(net): Winsock errno mapping, exclusive bind and IPC on Windows - 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]> * fix: Windows platform layer (file mapping, pools, crash report, paths) - 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]> * fix: REPL, profiler and system builtins build and work on Windows - 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]> * test: run the suite on Windows - 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]> * docs: Windows build instructions and platform status Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix: readable REPL prompt and CPU name in the banner on Windows 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]> * bench: build the micro-benchmarks on Windows, record a Windows/Linux 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]> * bench: record the recent perf benches on Windows vs Linux Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(format): render i64 at full width, not through 32-bit long Interpolation (format/println), print and the pivot / column-name helpers formatted an i64 with "%ld" and a (long) cast. long is 64-bit on LP64 and 32-bit on Windows, so there 10^18 printed as -1486618624 and a pivot keyed on values above 2^31 produced truncated column NAMES — a data defect, not only a display one. Use PRId64 throughout; regression test included. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(crash): format the banner with snprintf instead of macro string splicing The banner was spliced from string literals and the RAYFORCE_VERSION / RAYFORCE_GIT_COMMIT macros inside #ifdef arms; without the -D values a static analyser reads the literal followed by the bare macro name as two adjacent tokens and reports a syntax error. Format it with one snprintf at install time (the handler itself still never formats), with the macros defaulting to empty strings. Output unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> * test(regress): drop the 24 GB til from the i64 width probe `til` is eager, so counting a three-billion-element range built a 24 GB vector for no extra coverage — the neighbouring literals already cross 2^31, 2^32 and 2^63. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix(mem): hand workers their freed blocks back at the end of every dispatch (#621) * fix(mem): hand workers their freed blocks back at the end of every dispatch A parallel operator's workers allocate per-task buffers from their own heaps and the main thread frees them once the dispatch has completed, so each block lands on the owning worker's foreign list. The owner drained that list only when an allocation found its freelists empty, which a warm worker with a partly cut pool rarely does: it kept splitting fresh pool space instead, touching new pages every round while its own freed blocks waited. Under a steady stream of such operators (a join against a large table per incoming batch) the process grew by a full 32 MB pool per worker before any block was reused, and only the idle decay, which needs the process to sit quiet, drained it earlier. The dispatcher now drains every registered heap's foreign list at the end of each parallel region (ray_heap_reclaim_workers), under the same conditions the idle decay already relies on: the flag is clear, so every worker has finished its last task and neither allocates nor frees until the next dispatch. The blocks go back to freelists only, no pages are released, so the next round reuses them without faulting. Tests: heap/reclaim_workers_drains_owner (a block owned by one heap and freed from another leaves the owner's list on reclaim and is handed out again at the same address, no new pool) and pool/dispatch_reclaims_worker_blocks (blocks allocated by real workers and freed by the main thread are back with their owners by the end of the next dispatch). Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix(mem): reclaim only the pool's own worker heaps after a dispatch The heap registry holds every thread that ever allocated, not only pool workers: a server's poll thread or an embedding's own threads are there too, and they may be allocating while a dispatch on another thread ends. Draining such a heap's foreign list from the dispatcher coalesces into freelists their owner is using at that moment. Only a pool worker parked on its semaphore is known to touch nothing of its own until the next dispatch, so each worker now publishes its heap in the pool (worker_heaps, set after ray_heap_init, cleared before it exits) and the dispatcher reclaims exactly those, plus its own list on its own thread. ray_heap_reclaim_worker takes one heap; the registry walk is gone, which also removes its per-dispatch scan of every registry slot. The heap test now checks the block's bytes leave the owner's books only on reclaim, instead of expecting the next allocation at the same address; the pool test reads the worker heaps the pool publishes. Co-Authored-By: Claude Fable 5.1 <[email protected]> * test(pool,heap): make the reclaim tests independent of worker start-up and adopted heaps The pool test read a worker's heap slot right after ray_pool_create, which returns before the workers have started, and passed vacuously when the main thread took every task. It now waits for each worker to publish its heap, records which worker allocated each block and repeats the round until a worker really allocated something, then checks that the next dispatch left no worker with a foreign list. The heap test drains whatever an adopted heap already held before taking its baseline. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix(pool): allocate the worker heap slots without an _Atomic cast cppcheck cannot build an AST for a cast to `_Atomic(void*)*` and fails the static-analysis run on it. The cast is not needed in C: ray_sys_alloc returns void*, which converts to the slot pointer type on its own, and sizeof(*pool->worker_heaps) names the element size without spelling the type. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Fable 5.1 <[email protected]> * fix(serde): reject trailing payload bytes (#622) * fix(select): a projection sees the projections before it (#620) * perf(like): one column kernel for the direct builtin and the executor, one row pass (#623) * fix(system): report arity errors for extra arguments (#616) * fix(in): admit the typed kernel for text columns, which it never reached (#607) * perf: shared-node memo, STR descriptor views, fused top-k on nullable like, bulk derived key, parallel dense grouping (#626) * v2.9.1 (#625) (#629) * docs(release): merge master back into dev after each release A merged release PR leaves a commit on master that dev lacks, so the next release PR is blocked as out of date with the base, and after a squash it also shows conflicts that aren't real. Add the back-merge as step 5. * perf(select): whole-table count/min/max/sum/avg from chunk-zone metadata A select of whole-table aggregates with no other clause scanned every row, although a stored column already carries per-chunk min/max in its chunk-zone index. - The chunk-zone index of an integer or temporal column also records, per chunk, the sum of its non-null values (int64 with wraparound, as the engine sums) and their count, in a fourth child vector. Indexes written before hold zero in that slot and load without it. - `sum` of an integer column reads the per-chunk sums; `avg` does too when no partial sum can leave double's integer range, so the value is exactly the row-wise one (otherwise it scans as before). - `(select {from: T a: (sum c) b: (min d) …})` with no where/by/take/ sort, every output a count / min / max / sum / avg of a plain column the metadata answers, is built from the metadata in O(chunks). Any other output leaves the query to the planner. Test: store/splayed_zone_aggs (each answer, nulls and types equal to the same query over an in-memory copy; float sums, a filter and an avg past 2^53 take the usual path and still agree; scalar sum/avg). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(index): mapped index regions — bounds-checked children, never released on drop - A column's inline index region is mapped with the column file, and its child vectors are addressed by region-relative offsets. The offsets were trusted as written. A region re-saved by a binary that knows fewer child slots keeps a stale offset in the slot it did not write (the new chunk-zone aggregates slot), pointing at or past the end of the file; the free path then sized its munmap from it and unmapped a page it did not own. ray_index_inline_map now takes the region size and admits only children that lie inside it; an out-of-bounds or malformed aggregates child is dropped, any other one leaves the column unindexed. - Copies of a mapped column borrow its index without a reference. Dropping the index from such a copy (a delete or an in-place write on it) released the index anyway, freeing the loaded column's children in place: its min/max then read NULL and crashed. A mapped index is now only detached from the vector; the mapping's owner unmaps it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(agg): zone min/max tell all-null from the non-null counts; empty tables keep the planner - The zone min/max treated INT64_MAX / INT64_MIN as "no non-null value", so a column of int64 maxima answered null. When the zone carries non-null counts they decide; min/max also require the zone's extrema to be present. - The metadata select no longer answers an empty table (its count differed from the planner's there). Tests: store/splayed_zone_aggs (edit through a copy of a loaded column then aggregate the original; an all-INT64_MAX column; an empty filter). Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(store): portable in-place sed in splayed_zone_aggs BSD sed takes the argument after -i as the backup suffix, so the null injection failed on macOS; use -i.bak and remove the backup. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(system): reject arguments to gc (#615) * fix(system): reject arguments to gc * docs(memory): use zero-argument gc form * fix(system): report gc arity errors * fix(string): a STR view keeps only the bytes it points at (#631) * fix(string): a STR view keeps only the bytes it points at The descriptor views introduced for substr and `if` over STR columns pinned more than they used. An `if` whose two sides came from different pools — including two columns of one table under a where: that kept a few rows — copied BOTH whole parent pools into the result (the compacted branch inputs share the full column pool, so a 10k-row result out of 500k rows carried the two columns' 43 MB); the eager arm did the same for an unfiltered `if`. A substr with a per-row start or length retained the parent pool even when every result fitted inline and nothing pointed into it. `if` now builds a pool of exactly the chosen rows' bytes whenever the sides come from different pools, a pooled scalar is involved, or the rows keep a small share (under an eighth) of one shared pool; one shared pool whose rows keep most of it is still pointed into as before, so a derived-key expression over one column stays copy-free. A substr view whose descriptors are all inline drops its pool reference; one that points into the pool stays a view (the column is alive anyway, and a sibling `if` over two such views can then pick either side without a copy). test/rfl/strop/str_view_pool_compact.rfl pins the retained bytes through direct-bytes: an `if` under a where over two columns, over two substring views, with a pooled scalar side, the eager `if` against the two-pool sum, and an inline substr view outliving its table. * test(string): cover the eager `if` over two STR pools The case labelled eager in str_view_pool_compact went through the selected path (a per-row condition column is always a row mask there), so the eager arm's two-pool offset/copy had no regression coverage. A scalar condition (a variable) is not a row mask: the selected path declines and the eager fill runs over two different pools. New cases take it at 500k rows (parallel fill) and 1000 rows (below the parallel threshold, serial fill), for both sides, check every row after all the sources are released, and bound the retained bytes to one side's pool. On the pre-fix tree the retention checks fail. The old case is relabelled as the per-row selected path it is. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Anton Kundenko <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> * fix(log): reject arguments to purge (#638) * perf(vec): avoid rewriting copied text nulls during concat (#641) Co-authored-by: singaraiona <[email protected]> * fix(hnsw): reject invalid persisted graph ids (#642) * fix(log): reject arguments to roll (#639) * perf(expr): 32 registers per fused expression; nulls produced mid-program, narrow scratch (#636) * perf(expr): 32 registers / 96 instructions per fused expression A filter of four conditions, one of them a `within`, needs more than 16 expression registers; the compiler then bailed and the whole predicate was evaluated column at a time over every row, without the chunk-zone morsel decisions. A grouping under `(and (== CounterID 62) (within EventDate [..]) (== IsRefresh 0) (== DontCountHits 0))` on a 100M-row table took 71 ms warm / 540 ms cold, against 24 ms for the same filter with three conditions. The limits are now 32 registers and 96 instructions; the per-task scratch is sized to the registers the expression uses instead of the maximum. The same query: 24 ms warm, 130 ms cold, same answer. Test: expr/wide_predicate (four and six conditions with arithmetic and `within`, a grouping under the four-condition filter, a wide computed column — each against the conditions applied one at a time; these shapes bailed on the register limit before). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(expr): nulls produced mid-program survive; narrow scratch widened Two wrong answers in the fused expression compiler, both reachable with more registers (the wider programs that now compile are exactly the shapes that chain a null-producing op into further arithmetic): - A null produced by an instruction — x/0, overflow to Inf, sqrt(<0), |INT64_MIN| — was only flagged when that instruction was the LAST one. `(abs (/ h b))`, `(as 'I64 (/ h b))`, `(+ (div h b) 1)` and any wider chain came back with the sentinel lanes but without HAS_NULLS, so sums and averages were poisoned (0Nf) or, after a non-null-aware i64 kernel, garbage. Registers now carry the origin of their nullability: a column-derived flag keeps the conservative HAS_NULLS attr; an op-generated one makes every downstream kernel null-aware and the output is scanned for sentinels, whatever position the producer had. A pure-finite result still leaves HAS_NULLS unset. - An I32/I16 narrowing cast or a comparison result used as an operand of an i64 op, a comparison or AND/OR was read as 8-byte lanes: `(- a (as 'I32 -1))` gave [15 -4294967275 30], `(+ (> a 15) 1)` gave [65793 3 3]. Such sources are widened to the lane type the kernel reads (the widening casts map the narrow null sentinels); a promotion that cannot be placed bails to the planner instead of running the mismatched kernel. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Anton Kundenko <[email protected]> * perf(select): filtered positional take stops early; sort by an unprojected column (#634) * perf(select): filtered positional take stops once the answer is known `(select {… from: T where: <pred> take: K})` with no ordering evaluated the predicate over the whole table, gathered every passing row and cut K afterwards; `take: -K` did the same for the last rows. The fused path now answers it: the table is walked in 64k-row chunks from the end the answer comes from, one pool task per chunk in that order, each worker keeping at most |K| passing row ids. A worker that holds |K| publishes the row beyond which nothing can be part of the answer, and every later chunk returns at once. The lists are merged by row id and only the |K| rows are gathered. `asc: key take: K` on a column marked sorted (no nulls) takes the same path: its first K passing rows are the K smallest, ties in table order. Test: fused/fused_take_early_stop (first and last K over many chunks, AND predicates, fewer matches than K, none, all columns, aliases, K larger than one worker's share, the sorted-key form). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(select): sort by a source column the projection does not output `(select {a: a from: T asc: c})` failed with `nyi` whenever the sort did not go through the fused top-k: the sort runs over the projected table and looked the key up there. A sort key that names a source column no output carries is now projected too and dropped from the result after the sort (an output with the same name is used as before). Test: query/sort_key_not_projected (no filter, a filter the fused path does not take, with and without take, two keys, computed outputs, a key that is also an output). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(select): hidden sort key vs a renamed output; alter set clears sorted - An output that renames the key column (`{b: a … asc: a}`) is a bare scan the projection names by its source column; the key was added as a hidden column under the same name and the drop took the output with it. Such a scan now counts as the key being present, and hidden keys are dropped by position (they are projected last). - `alter … set` wrote into a vector marked sorted and kept the marker; the ascending take on a sorted key trusts it. The marker is cleared on write. - Without a sort, the positional take path admits only a literal K, so a `take:` expression is evaluated once, by the general path. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(select): fused take/top-k leave alias-chained projections to the planner Projections resolve left to right: in `{b: a z: b …}` the output z reads the alias b (column a), not the source column b. The fused positional take and the fused top-k gather source columns by name, so z came back as column b — `take: 2` gave [30 10] instead of [3 1], and the sorted top-k had the same wrong answer before this branch. When an output names an alias bound by an earlier output (other than itself), the fused paths now decline and the planner resolves the projections. Tests: fused/fused_take_early_stop (positive and negative take, sorted take with and without a filter, an identity alias that stays fused). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(select): sort keys bind to projected columns by position, name source columns The sort of a projection resolved its keys by NAME over the projected table, whose columns are named by source column for scans and `_e<c>` for expressions. Three wrong outcomes followed: - a hidden key whose source column is called `_e0` collided with the first computed output: `{z: (+ a 10) asc: _e0}` sorted by z; - `{b: a asc: b}` treated the output alias b as the key, found no column b in the projection (that scan is named a) and failed with `nyi`; - hidden keys were capped at 16, so a 17-key sort failed with `nyi`. A sort key now names a SOURCE column, like where: and by:. In the planner it binds to the projected column that scans it — an output, or the hidden key appended for it — and exec_sort reads a key that is one of the SELECT's columns by position, so no name lookup can pick another column. Output aliases are not consulted. The hidden-key capacity is one slot per sort key name. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Anton Kundenko <[email protected]> * perf(group): partitioned dense accumulate; derived-key grouping over the column's distinct values (#633) * perf(group): partition the slots when the dense accumulate cannot afford one set per worker; pin the SYM vocabulary once per accumulate The direct-array group path keeps one accumulator set per worker and bounds that state by the row count. Past the bound it ran ranged tasks over as many sets as the budget allowed — one set, i.e. a serial scan of every row, whenever the slots times the per-group state exceeded the rows, which a wide key with a nullable min and a strlen average over a large table does at once (5M slots, three aggregates: budget 1 out of 24 workers). Instead the slots are partitioned: one parallel pass computes each row's group and buckets its row id by slot span per worker (no shared writes), then one task per span drains every worker's bucket for it into the single accumulator set. No two tasks touch a slot, nothing is merged, and the state is one set however many workers run; the buckets cost four bytes a row. Row-range tasks stay for the small-slot case and as the fallback when the buckets cannot be allocated. Inside the accumulate, strlen over a SYM column pinned the FILE-domain vocabulary snapshot and ran ray_vec_is_null per row, and the lexical min/max compare pinned it per compare. The snapshot is pinned once per SYM aggregate column for the whole accumulate; null is the id-0 check. test/rfl/group/dense_slot_split.rfl: 200k rows over 130k slots with a nullable min/max/sum/avg/first/last, strlen over a SYM column with empty cells, a two-key composite and a where: selection — each against the same grouping forced onto the hash path by one far-away key. * perf(group): decide a derived-key grouping over the column's distinct values when every aggregate reads that column A grouping keyed by an expression over one SYM column C whose aggregates are count(C), min(C), max(C), sum(strlen C) or avg(strlen C) is decided by the distinct values of C: a group's count is the sum of its values' row counts, its min the smallest of its values, its strlen sum the length-weighted count. It used to be evaluated per row — a spread key over every row and an accumulate of every row's length and lexical compare — while the key expression itself already ran once per distinct value. derived_key_vocab_aggs now groups the rows by C once (a column key and a count, the engine's cheapest grouping, under the select's where:), runs the key once per distinct value (derived_key_str_chunks) and rewrites the aggregates over the per-value table: count → sum of counts (null rows count, as before), avg(strlen) → weighted length sum over the non-null count, min/max → over the values (null skipped). Sort and take clauses on output aliases pass through; the outputs come back in the written order under the computed key's usual name. Any other aggregate, a runtime-domain column or a small table keeps the row path. Interning the key strings cached dotted segments for every new value — a host or URL interned every one of its dot-separated parts as a symbol too, which was most of the cold-run cost. ray_sym_intern_batch_no_split interns them as values; a value that later appears as an identifier gets its segments on that intern. The per-value length pass runs on the workers. An `if` whose two STR branches are cheap and total (scans, constants, substrings, case/trim/length, add/sub/mul, comparisons, and/or/not) takes the eager descriptor arm instead of compacting the rows for each branch. test/rfl/group/derived_key_vocab_aggs.rfl: the five aggregates with and without where:, against the row path (forced by one aggregate over another column), the same table in memory, the null group's avg and min, sort/take on an alias, and the key name yielding to an alias. * fix(group): keep FIRST/LAST groupings past the slot budget on the serial row-order scan Several FIRST/LAST aggregates share one first_row/last_row per slot (a documented limitation of da_accum_row), so the answer for a null-mixed pair depends on the order the rows arrive in; the slot-partitioned drain walks the workers' buckets, not the rows, and made `last` differ by worker count. Past the budget such a grouping stays on the single accumulator in row order. * fix(group): partitioned accumulate and vocabulary rewrite independent of core count The slot-partitioned accumulate scattered rows by pool morsel into per-worker buckets, so a slot received its rows in scheduler order and float sums (and var/stddev) rounded differently from run to run. The scatter now runs nw tasks over contiguous row ranges in order, bucket row = task, and the drain walks them in order: each slot gets its rows in table order, the serial scan's accumulation. The vocabulary rewrite took its group order from the per-value count grouping, whose order depends on the core count. The counts are now put in domain-position order first (bitmap rank + scatter), so the output order is the same at every core count. Tests: dense_slot_split (1e16 + 1 - 1e16 + 1 per group sums to 1.0 in table order), derived_key_vocab_aggs (unsorted output order pinned). Both fail with their fix disabled. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> * perf(csv): parallel splayed load, batched symfile interning, parallel hash index build (#632) * perf(csv): scan, append and index the splayed load in parallel Streaming a CSV into a splayed table ran its per-chunk row scan, the per-column writes and the index build on the calling thread; only the field parse used the pool. - Row offsets for a chunk come from the parallel quote-parity scanner over a byte window sized from the running average row length, widened until it holds the chunk (falls back to the serial limited scan). - The chunk's columns are appended by one task per column; SYM cells go through a direct-mapped runtime-id to position cache in the writer, so only a value's first occurrence probes the symfile domain. - ray_splay_build_indexes builds one column per task. Co-Authored-By: Claude Fable 5.1 <[email protected]> * perf(csv): intern chunk dictionaries straight into the symfile domain Every distinct string of a splayed load was interned twice, serially: once into the runtime symbol table by the chunk materialisation, then again into the table's symfile domain by the column writer, one cell at a time under the global domain spinlock — the two together were more than half of the load time, and the runtime table grew by the whole vocabulary for nothing. - csv_materialize_rows takes a target domain: SYM chunk columns are built over the symfile domain, and the writer copies their positions. - ray_sym_domain_intern_batch (domain.c): one batch per chunk over all SYM columns. The existing vocabulary is probed in parallel against a snapshot of the reverse index (replaced bucket tables are retired, never freed), misses are deduplicated per hash partition, and the new atoms are built in parallel into per-partition arena regions (ray_arena_alloc_raw / ray_arena_str_at) before the count is published. Index growth re-slots the old table instead of rehashing every atom; the symfile flush packs records into a 1 MB buffer. - SYM fields are hashed by the parse tasks; with a domain target each SYM column's dedupe is split by hash partition across tasks. - The window scan is preceded by a readahead hint and finished chunks are dropped from the mapping, so a long file does not stay resident. Co-Authored-By: Claude Fable 5.1 <[email protected]> * perf(index): build hash indexes partition-parallel ray_index_attach_hash grouped the rows in one serial open-addressing pass; on a high-cardinality numeric column of a large table it was the longest single stretch of a splayed load, and running the columns as pool tasks left the build itself single-threaded. Numeric and SYM keys above 64k rows now build in partition-parallel passes: key words and hash-partition buckets over row ranges, a per-partition dedupe that marks each group's first row in a bitmap, then keys, counts, the row scatter and the key table (CAS on the empty slot) per partition. A group's number is the rank of its first row among the marked rows, so the layout is the serial walk's: groups in first-occurrence order, rows ascending inside a group. Every array a pass writes is faulted in beforehand from all workers in slices — a fresh mapping faulted at random from every worker serialised on the page-table locks. STR keys and small columns keep the serial walk. ray_splay_build_indexes defers the columns that qualify for a hash index out of the per-column tasks, builds them one after another with the parallel path and writes all deferred columns together. Co-Authored-By: Claude Fable 5.1 <[email protected]> * chore(index,domain): cast the CAS targets in place cppcheck cannot parse a declaration of `_Atomic(T)*` type (AST broken on the `=`), which failed static analysis; the two batch inserts now cast at the compare-exchange, the form the rest of domain.c uses. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix(domain): retire the reverse index on external extend; batch intern tests The batch intern probes a snapshot of a domain's reverse index outside the lock, relying on replaced tables being retired rather than freed. The external-growth path (a reader catching up with a symfile another process appended to) still freed the table, so a probe running at that moment could read freed memory. It now retires it like the rebuild does. A probe that meets an entry it cannot compare (no atom and no raw bytes, possible only if publishing the raw snapshot failed) no longer counts it as a miss: the whole batch then resolves under the lock, so no string is appended twice. The splayed writer's per-column dispatch goes through ray_pool_par_dispatch_ok like the other sites. The batch-intern header comment no longer claims appends in batch order: new strings get positions grouped by hash partition. Tests: domain/intern_batch (repeats across partitions, pre-interned hits keep their positions, repeat batch appends nothing, "" is 0, flush/reopen); csv_splayed_dedupe_overflow (140k distinct strings in one SYM column overflow a partition's dictionary in debug builds and take the row-by-row fallback); index/hash_large_parallel now creates the pool so the parallel build is the one tested. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(csv): split every window as the whole file; symfile and index bytes independent of cores A chunk's byte window chose the scanner's quote mode from its own bytes. In a file with quotes elsewhere, a window without any took the quote-free fast path, where a lone '\r' does not end a row: two rows merged and a value was lost (the serial walk and .csv.read split them). The window now scans in the file's quote mode. The symfile no longer depends on the worker count. The chunk batch is laid out the way the cell-by-cell writer meets the strings — columns in order, each column's strings by first occurrence (partition runs merged by the first row, recorded in the dictionary entry) — and the batch intern appends new strings in batch order. The hash index key table is filled in group order on the calling thread, as the serial build does, so the persisted index is the same bytes on any core count. A replaced reverse-index table is freed at once unless a batch intern is probing a snapshot outside the lock (counted under the lock), so a long-lived reader of a growing symfile keeps no extra tables. Tests: splay/csv_symfile_order (positions follow the writer order over three chunks, parallel batch and partitioned dedupe), and splay/csv_quote_mode_per_file (quotes only in chunk 0, a lone '\r' in chunk 2: same rows and values as .csv.read). Both fail with their fix disabled. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Anton Kundenko <[email protected]> * perf(select): fused top-k prunes chunks by zone extrema and visits the best chunks first (#643) * perf(select): fused top-k skips chunks whose zone cannot beat the K-th key The fused top-k evaluated the predicate over every row even when the first sort key is a stored integer/temporal column whose chunk-zone index shows most chunks cannot hold a top-K row (a table clustered by another key, sorted within it, puts a time column's early values in a few chunks). Each worker whose heap is full publishes its worst first-key value; the best of those bounds the final K-th key. A chunk whose zone minimum (asc) is above the bound, or maximum (desc) below it, is skipped before the predicate runs — its pages are never read. Chunks with nulls are kept when nulls sort first. On a 100M-row table ordering by a time column clustered under a counter (52 of 1526 chunks can hold the top 10): cold 1205 ms -> 157 ms, warm 30 ms -> 9 ms; with a second sort key 24 ms -> 5.5 ms. Test: fused/topk_zone_prune (asc, desc, two keys, K near the match count, all equal to an unindexed in-memory copy). Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(select): publish the top-k pruning bound once per morsel Publishing on every heap replacement made the bound a contended cache line when rows arrive in the order being sought (a descending top-k over a column stored ascending replaces the root on nearly every row, and nothing is pruned there): 25-70% slower than without pruning. The bound is now published once per morsel, on its own cache line. Those shapes are back to the unpruned time; the prunable ones keep their gain. Test: topk_zone_prune gains a nullable key with an all-null chunk, asc/desc and two keys. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(select): fused top-k visits the most promising chunks first With a chunk-zone index on the first sort key the K-th key only tightens as fast as the physical order lets it: an `asc` over a descending column scans everything before the bound becomes useful, and a key whose best values sit in the middle prunes nothing until the workers get there. Order the chunks by their zone extremum (smallest minimum for asc, largest maximum for desc, null chunks first when nulls sort ahead) and dispatch the workers over that virtual row space, mapping each slot back to its chunk. The K-heaps then fill from the best chunks, the bound is tight after the first few, and the rest are skipped whatever the layout. Results are unchanged: the heap keeps the K best rows with a source-row tie break, so the visiting order cannot alter them. Local A/B on a 4M-row splayed table (release, 8 cores): asc over a descending key K=100 43 -> 2.7 ms, K=8000 212 -> 104 ms, with a filter 22 -> 0.2-1.7 ms; already-favourable and unindexed shapes unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix(select): `if` over two STR columns under a sparse filter stays on the selected path Two cheap STR branches route `if` to the eager arm, which picks descriptors for every row of the table in one pass. Under a `where:` that keeps few rows that is a bad trade: the filtered result keeps the whole intermediate — both parents' bytes — alive for its few rows (`select {x: (if c S S2) where: (== st 1)}` over 500k rows held 20 MB for 10k rows; the selected path holds nothing beyond them). Take the eager arm only when the outer selection keeps more than a quarter of the rows (the projection's pre-compaction threshold); a sparse selection evaluates the branches over the selected rows only. No filter and a filter keeping most rows are unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> * perf(select): fused top-k re-tests the pruning bound before every morsel The chunk test ran once at chunk entry, so a bound that tightened while the chunk was being scanned (another worker's heap filled, or this one's) only took effect from the next chunk. Re-test it before every morsel — one relaxed load and a compare, no writes — and abandon the rest of the chunk once it cannot beat the bound. Local A/B on the 4M-row table (release, 8 cores): asc over a descending key K=100 2.6-3.0 -> 0.4 ms, the same with a filter 0.8-1.4 -> 0.25 ms; the other shapes unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> * fix(collection): hash int cells through f64 when a set meets a float probe (#646) * fix(collection): hash int cells through f64 when a set meets a float probe The row hashset behind find/except/union/sect/in hashed int cells with ray_hash_i64 and float cells with ray_hash_f64. Numeric equality crosses the two (atom_eq compares any two numerics through f64, and hs_eq_rows already defers to it), but equal values landed in different buckets, so the probe never reached the compare. A correct answer was a collision: (find [1.0 2.0 3.0] [3 1]) [0Nl 0] -> [2 0] (except [1 2 3] [1.0 3.0]) [1 2 3] -> [2] (sect [1 2 3] [2.0 3.0]) [] -> [2 3] (union [1 2] [2.0 3.0]) [1 2 2 3] -> [1 2 3] (in [1 0Nl 3] [1.0 0Nf]) [false true false] -> [true true false] The set gains a num_f64 mode in which int-family cells hash through f64. The first probe of a new type goes to a cold helper; if it is the other numeric class (or a list, whose numeric atoms already hash through f64), the set rehashes once and keeps the mode. A cached last-probe type keeps the per-probe cost to one compare, so same-type callers are unchanged. hs_eq_rows compares mixed numeric typed cells as f64 directly instead of boxing two atoms per probe. If the one-off rehash hits OOM, that probe is answered by a full scan and the next probe retries. 1M x 500k, -c 8, release, 3 alternating runs: except/sect i64-i64, f64-f64 within ~1% of dev except i64-f64 153 ms -> 80 ms (and now correct) sect i64-f64 155 ms -> 80 ms (and now correct) find i64 hay / f64 needles 34.5 ms -> 0.1 ms (and now correct) collection_branch_cov.rfl pinned the old miss -- its comment says the probe "may miss" because the hashes differ -- and now expects 2. New mixed_numeric.rfl covers find/except/union/sect/in in both directions, narrow ints, fractional misses, both-sides-null in, and sizes that grow the table before and after the switch. Closes #645 * fix(collection): skip the no-op rehash of a float-built set; pin ints past 2^53 Review follow-ups on #646. Only int cells change hash in num_f64 mode, so a float- or list-built set is already in the f64 layout: set the mode and skip hashset_rehash unless the source is int-class (except with an i64 probe against a 500k f64 set, 79 -> 73 ms). mixed_numeric.rfl gains the float-set/int-probe order and a note, with cases, that ints past 2^53 compare through f64 -- consistent with == -- while same-type ints sharing a double image stay distinct. * test(agg): pin the LLC in dense_cache_bound so the route is runner-independent (#647) agg_contract/dense_cache_bound failed intermittently on the macOS debug CI job (got strategy 2, expected 1) across unrelated PRs. The group route bounds replicated task-local slabs by the probed last-level cache, and switches to partition ownership when fewer than three slabs fit. A macOS CI VM reports a few MB of L2, which fits fewer than three of the test's 2.5 MB slabs, so the route correctly chose partitioning while the test asserted the task-local strategy. ray_cache_llc_bytes gains a DEBUG-only pin, ray_cache_llc_set_for_test, following ray_ipc_set_auto_journal_eval_for_test. The three platform probes become static cache_llc_probe and one wrapper honours the pin. The test pins 32 MB (the size the route assumes when none is reported) around the routed query and restores it before any assert can return. It also asserts the pinned bound actually bites (3..19 slabs). Pinning 4 MB instead reproduces the CI failure exactly: test_agg_contract.c:1759 got 2, expected 1. make test 3953/3953. * fix(in): admit the typed kernel unless both sides carry a null (#644) * fix(in): admit the typed kernel unless both sides carry a null #607 opened the typed membership kernel to text columns but kept it behind "both operands exactly null-free". That is stricter than the semantics require: the kernel (null matches nothing) and the hashset fallback (null equals null) disagree only on a null row against a null set element, which needs a null on each side. One null row in the column therefore sent the whole column to the per-row hashset probe. 351,393-row column, -c 8, one null row, null-free needles: SYM (in col one) 4,820 us -> 60 us I64 (in icol [0 1]) 5,730 us -> 80 us SYM null-free (in col one) 145 us -> 55 us (set tested first: a null-free set skips the column's null scan) It also fixes wrong answers: the hashset hashes i64 and f64 cells with different functions, so mixed int/float membership with a null on one side missed matches -- (in [1.0 0Nf 3.0] [1 3]) was [true false false]. Those shapes now take the kernel's double promotion. The both-sides-null mixed-type case still reaches the hashset and is still wrong; it is a hashset bug, not a gate one, and is left for a separate fix. A 23-case null edge matrix is byte-identical before and after apart from that corrected row. The in.rfl comment claiming a needle-only null "must still reject" is corrected, and one-sided nulls across every null-bearing width are pinned. * fix(in): temporal equals only its own type; hash large needle sets in the kernel Review follow-ups on widening the `in` kernel gate. Temporal types. The typed kernel classified DATE/TIME/TIMESTAMP as plain int-family and compared raw payloads, so (in [2000.01.01 0Nd] [0]) was [true false] while find, except and the hashset `in` -- all atom_eq, which never matches a DATE to an int or to a TIMESTAMP -- said no. It also compared a DATE's day count to a TIMESTAMP's nanoseconds: (in [2000.01.02] [2000.01.01D00:00:00.000000001]) was [true]. A temporal operand against a different type is now an empty probe, as SYM vs non-SYM already was. Bare `in`, the fused where: and the hashset agree whichever side carries a null. Large needle sets. Past the SIMD small-set size the kernel scanned every needle per row, O(rows x needles). The widened gate sent nullable int/float columns there, and null-free ones already went: a 351k-row column against 100k needles took ~1.2 s. Sets larger than IN_SIMD_SET (8) now get an open-addressing table over the live needles -- int64 values, or f64 bit patterns with -0.0 folded to +0.0 and NaN never inserted -- built once per call and shared by all workers. An allocation failure keeps the scan. 351,393 rows, -c 8, release, dev before #644 -> this commit: I64 with a null x 3 needles 6,500 us -> 50 us I64 with a null x 1k 10,600 us -> 1,400 us I64 with a null x 100k 10,000 us -> 2,500 us I64 null-free x 100k 1,155,000 us -> 1,500 us F64 with a null x 100k 10,500 us -> 2,500 us select where: in, null-free x 100k 1,155,500 us -> 2,000 us in.rfl pins temporal vs int and distinct temporal types with nulls on neither, either and both sides, the fused where:, and the 8/9-needle boundary, -0.0, NaN, duplicates and narrow ints on the hash path. make test 3952/3952; reverting exec.c fails in.rfl:169. * fix(agg): integer mean divides the exact 128-bit sum; mapped index tail unmapped after drop (#648) * fix(agg): integer mean divides the exact 128-bit sum The mean of an integer column depended on where it was computed. The group engines divided a WRAPPED int64 sum — a whole-table `select {a: (avg id)}` over signed 64-bit ids answered -5.59e10 for a true mean of 2.53e18, and any per-group total past 2^63 was garbage — while the vector path accumulated in double and lost low bits past 2^53, so its last bits moved with the accumulation order. The chunk-zone metadata could only answer a mean when every partial sum stayed below 2^53. Every integer mean now divides the exact 128-bit sum of its rows, converted to double by one formula, so the vector reduction, the parted column path, the columnar, hash-row, scatter and slice group engines, the streaming engine, pivot and the metadata agree bit for bit: - the chunk-zone aggregates keep the high word of each chunk's sum in a third block (older two-block indexes still load; without high words the metadata answers only when the extrema prove the total fits); - the keyless reduction and the group accumulators carry a high word beside the wrapped sum, allocated only when an integer avg over an I64 / TIMESTAMP column (or a table of 2^31 rows or more) is present — narrower inputs cannot leave int64 and keep their plain sum; - the streaming engine keeps its 16-byte state: a signed running sum plus the wrap count packed with the row count, exact while a group has fewer than 2^32 rows (larger tables stay on the legacy engines); narrow inputs use an exact int64 state; - a bare I64 column sums in blocks whose mode (values below 2^53, below 2^53 in magnitude, or general) is escalated once. `sum` keeps its int64 wraparound contract. The grouped combine over a parted table (per-partition sums joined afterwards) is not changed here and still divides the wrapped total. Tests: group/avg_exact_i128 (exact means over values that overflow int64 within every group, across the keyless, columnar, hash, scatter, slice, streaming and pivot paths, nulls, narrow types, a splayed copy), test_agg_engine avg_exact_i128_engines (v2 on and off), store/splayed_zone_aggs (metadata means past 2^53 and past 2^63). Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix(store): a mapped column that drops its index still unmaps the index tail A column loaded by mmap with an inline index is longer than its payload, and ray_free sized the unmap from the attached index. Once the loaded column itself dropped that index — an in-place edit of its only reference detaches a mapped index without releasing it — or when ray_index_inline_map had discarded a child that is still in the file, the unmap covered the payload only and the index tail stayed mapped for the life of the process. A mapped column that carries an index now registers its region in the file-map registry under its own address with the true mapped length, the way a string column's pool already does, and ray_free consults the registry for every mapped column before falling back to the size …
* fix(store): a replaced splayed table keeps one copy of itself (#713) A table replaced twice or more held about three copies on disk: the first write's root column files, never read again after the first publish, and the previous generation, kept for a reader that resolved .current before the swap. - The first publish removes the columns the retired root schema names, with their .link sidecars, then .legacy.d. Only those names go: the root also holds the symfile, the lock, and for a table written into a database root, the partitions. A cleanup cut short is finished by the next publish, which also cleans stores written by earlier versions. - Publication keeps only the selected generation. Instead of the writer keeping the previous one, a reader whose generation is removed before it opened every file resolves again and reads the selected one (splay_load_impl, ray_read_splayed_dom, and ray_splay_has_schema for the partition checks, where a false "no table" would let .db.parted.fill write an empty table over a real one). Mapped files stay readable. No setting: the previous generation protected nothing the retry does not. * fix(query): exclude null symbols from not-in (#739) * perf(index): store hash slot table and group offsets as 32-bit A hash index over a column below 2^32 rows keeps its slot table (group id + 1) and its CSR group offsets as unsigned 32-bit values instead of 64-bit. Both are bounded by the row count, so nothing is lost; the two arrays take half the memory and half the bytes on disk. Readers go through one width-aware accessor; the append carry widens the source arrays and re-narrows the result. An index with a narrow array is persisted as layout generation 2. The mapper accepts generation 1 (all 64-bit, as written so far) and generation 2, and rejects a generation-1 region that carries a narrow array, so the column loads unindexed rather than misreading it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(heap): count off-heap allocations toward the spill watermark (#712) The anonymous watermark that routes new memory to spill files saw only the heap's pools and direct blocks. Everything allocated with ray_sys_alloc stayed outside it: the string arenas of the symbol table and of the column domains, their hash tables, and index-build scratch. During a load of a wide table with many distinct strings that is most of the footprint. Sampled in a container limited to 15 GB with -m 9G, the watermark counter stayed at 1.9 GB while sys allocations grew to 15 GB, and the process was OOM-killed. ray_sys_alloc now goes through ray_heap_sys_map: every block counts toward the watermark, and a block of 1 MiB or more that would cross it is mapped over an unlinked spill file instead, like a direct block. The file's descriptor is closed at once, so spilled blocks hold no fds. Past the watermark, a pool or direct block that could not get a spill file (no writable spill directory, disk full) failed the allocation. With more counted and a lower default that point came much earlier; such a block, like a sys block, now comes from RAM instead. The default watermark was the whole RAM the process may use (physical RAM, or a cgroup limit when that is smaller), so spilling began only once nothing was left. The page cache needs room from the same memory: the mapped inputs, the dirty pages of the files being written and those of the spill files, all charged to the limit under a cgroup. The default now stops a quarter below it, at least 3 GiB and at most half. The budgets a query sizes its strategies by (the direct-block cache, the dense and mode grouping gates, the fused cumulative-distribution gate) keep the whole limit: ray_heap_mem_budget is the -m value when one is set, else the RAM the process may use. Sized by the lowered watermark they picked slower plans on a 32 GB machine. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(index): store hash index row ids as 32-bit The CSR row-id array of a hash index (one entry per indexed row, the largest of its arrays) is stored as unsigned 32-bit values below 2^32 rows, like the slot table and offsets. Over a column of unique keys an index now takes 16 bytes per row (row id, offset, key) plus 4 per slot, instead of 24 plus 8. Row slices leave the index as ray_idx_rows_t, a pointer with its width, read through ray_idx_rows_at: - ray_index_hash_group and ray_idx_slice_t carry it; the rowsel builder is specialised per width, and ray_index_rowsel_from_rows builds a selection straight from an index slice. - The filter-plus-group kernel widens a narrow task chunk once into a per-worker buffer, so its accumulation loops are unchanged. - The as-of join verify takes the slices directly instead of packing pointers into an int64 array. Indexes mapped from generation-1 files keep their 64-bit rows and are read through the same accessors. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(arena): grow chunks so a large arena can spill (#712) An arena allocated every chunk at its initial size: 64 KiB for a column domain's string atoms. A domain with millions of distinct strings was then hundreds of thousands of small ray_sys_alloc blocks, and blocks below 1 MiB are never mapped over a spill file, so the atoms of a large load stayed in RAM past the watermark. In a 15 GB container with -m 9G the counted footprint reached 16.5 GB and the load stalled at the cgroup limit. Chunks now double from the initial size up to 16 MiB. A large arena is a few big chunks that spill past the watermark; a small one keeps its small first chunk. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(index): keep the wide arrays when narrowing is interrupted Narrowing a just-built hash index's arrays runs as a pool dispatch, and an interrupt (Ctrl-C, a client's cancel) makes a dispatch skip its tasks. Landing after the build's last interrupt check, it left the 32-bit copies unfilled and installed them; a load could then save that index, and lookups returned wrong rows. The narrowing now keeps the 64-bit array it was copying when the dispatch was cancelled. The append carry built 64-bit arrays and narrowed them again on every append; it now builds them in the width they end in and copies a narrow source as it is. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(heap): hand memory back between statements when it is short A free block keeps its pages and a standard pool stays mapped after a statement, so a repeated query reuses them without faulting; a server gave them back only after ten idle seconds. Where memory is short this turned against the next query. What the previous one left resident starved the page cache, and a kept pool still counts toward the spill watermark, so the next query's new memory went to spill files. In a container limited to 4 GB a heavy grouping ran in 22 s on a fresh server and in 430 to 870 s on the second and third runs. At a statement boundary of a server request or the REPL, once the anonymous footprint is past the watermark (the next query's memory would spill, and the room the watermark leaves the page cache is being eaten), empty pools of every heap, standard ones included, are now unmapped (their bytes leave the watermark count) and the pages of the remaining free blocks released. The repeated runs above take as long as the first. Below the watermark nothing changes: the kept memory is what a repeated query reuses. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(index): build hash indexes partition by partition within the memory budget The hash index build kept every row's group id, key word, partition slot and the output arrays live at once, about 58 bytes per row at random, so a 100M-row column needed ~6 GB of private memory and on a small machine paged it through the spill file at random. Numeric and SYM columns are now indexed by a partitioned builder. Key words and row ids are bucketed by the top bits of the key's mixed hash; partitions are deduped in batches whose working set fits a quarter of the heap watermark; their groups, row offsets and rows are written in order. Groups are numbered in ascending order of the mixed hash and a key's home slot is the top bits of that hash, so the slot table is written in one forward sweep and every array follows from the data alone, whatever the partition count, budget or core count. Only a batch is accessed at random; the bucketed input and the outputs are streamed, and past the watermark their heap blocks are file-backed. An interrupt anywhere in the build leaves nothing allocated and the column unindexed. The new tables are marked RAY_MARK_HASH_HIGH and persisted as layout generation 3. Readers take the home slot from the table's own rule, so generation 1 and 2 tables keep loading; older binaries load a generation-3 column unindexed. STR columns keep the serial walk. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(heap): relieve only when it brings the footprint back under the watermark The statement-boundary relief scanned every freelist once per pool (its cost grew with the square of the heap: hundreds of milliseconds per statement on a fragmented heap of a few hundred MB), ran at every boundary while live data held the footprint past the watermark (unmapping pools, draining the direct cache and releasing pages that the next statement mapped and faulted straight back), walked the heaps of threads that may still be allocating, and ignored empty spill pools. Empty pools are now found per heap with a cheap filter (a free block of pool order or above must exist; then one header read per cascade offset) and confirmed by one walk of the freelists that sums free bytes per candidate. Relief acts only when the next pool would not fit under the watermark and handing back the empty pools and the direct cache brings it under again; otherwise the memory stays for reuse. When it acts it also unmaps empty spill pools, whose page cache counts against a container's limit. Relief, the idle decay and gc's pool pass visit only the caller's heap and the parked pool workers' heaps. Without a file spill (Windows) relief does nothing and memory is left to the idle decay. The REPL's ^C path, a script run with a file argument, timer callbacks and .sys.gc now end at the same boundary. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(scan): read ahead the columns a pass reads on cold storage (#747) * fix(store): a reader keeps up with a table that is being rewritten (#748) * fix(store): a reader keeps up with a table that is being rewritten Only the selected generation of a splayed table is kept, so a reader can see the generation it resolved removed before it has opened all its files. It then resolves again and retries, but gave up after eight attempts. A reader slower to open its files than the writer is to publish (many columns, slow storage, a busy CPU) failed with an I/O error after eight saves, although every failure was only the table moving on. splay/generation_reader_races hit it: under a loaded CPU it failed 29 times in 30. Each retry follows a completed publish, so the reader is no longer counted out: it retries while the table keeps resolving to a different generation, at least eight times and for up to 60 seconds, and then reports that the table kept changing rather than the error of its last attempt. An interrupt stops the retries with a cancel error. The symbol domain of the previous attempt stays open across a retry, so a large symfile is extended rather than read again on every attempt; read again each time, it could take longer than the writer's interval and lock the reader out. Under the CPU load above the race test passes 30 times in 30. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(store): a retry that finds no symfile lets go of the domain it held A retry that found the symbol file missing or unreadable left the domain an earlier attempt held in place and then overwrote the only reference to it, so the domain and its mapping stayed cached for the life of the process (a later save to that symfile path then failed). Each attempt now releases the domain held from the one before it, after reopening the symfile when there is one. New test splay/generation_retry_releases_domain drives a read through a FIFO .current served by a child process: the first attempt fails after opening the domain, the symfile is removed before the retry, and the domain must not stay cached. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> * perf(parquet): import column by column when memory is short, through an import symbol dictionary (#753) * perf(parquet): import a splayed table column by column when memory is short The direct import ran one task per column chunk with row groups outermost, so every worker wrote all of the table's column files at once and kept every column's state live together, and the hash indexes waited for the end and re-read their columns. On a machine whose memory cannot hold the output that is a scattered write pattern, and the re-read goes to disk. The import now runs in passes. When the process may use less than twice the output's bytes it goes column by column (a pass is one column, or a few when the file has fewer row groups than the pool has workers): numeric and temporal columns first, each closed as soon as its pass ends and its hash index built right away while the file is still in the page cache; symbol columns after, smallest first, one by one below half the output's bytes of memory and together above. With more memory one pass takes every column, as before. RAY_PQ_PASS_COLS forces the columns per pass. Read-ahead follows the passes: a task requests its own chunk and the same column's chunks of the next row groups (RAY_PQ_PREFETCH), up to a share of the memory budget. In one pass each written chunk's writeback starts as it is written (ray_file_writeback_start), so the final sync finds little. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(sym): build the import's symbol file as the strings arrive The import interned its strings into a file domain that keeps every one as an arena atom (about a hundred bytes each with its index), behind one lock, and wrote the symbol file only at the end: a rewrite of the whole vocabulary through a temporary file, then a sync. On large vocabularies that is several gigabytes of anonymous memory, which a small machine pages in and out, and tens of seconds of writing after the last column. A converter that builds its symbol file alone now uses an import domain (ray_sym_domain_create_import, table/symimp.c): interned strings are appended straight into the mapped symbol file as its records; in memory there are only the records' offsets and a hash index in 1024 shards. A hit is found without a lock, and a batch's new strings are added together under one, so they get neighbouring positions. Position 0 stays "". While the passes run, a background thread appends what is new to the symbol file every quarter second and starts its writeback (ray_sym_domain_flush_append writes the tail in place, and is what the import domain's flush does), so the final flush only syncs. The direct Parquet import uses the import domain; the spooled path keeps the ordinary one. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(parquet): keep the one-pass import as it was; harden the import dictionary One pass over every column (the layout with memory to spare) closed and hash-indexed each numeric column on the main thread as the pass ended, one after another, instead of finishing them on the pool and building their indexes in one parallel wave after the symbol domain is released: a table of wide numeric columns took twice as long. That pass now leaves the columns to the common finish, as the row-group import does; only the column-by-column passes close and index each column as they go. A file with fewer row groups than the pool has workers, imported column by column, put its symbol columns in the numeric pass; they get passes of their own. RAY_PQ_PASS_COLS sets the symbol passes too. Output sizes from the file's metadata are summed without overflow. The symbol file appender slept a quarter second between flushes and the import joined it at the end, so every import with a symbol column took a quarter second longer: it now sleeps in slices that see the stop. A failed flush stops the import at the next pass instead of after the last. When the import dictionary could not be set up after creating its file, the empty or zero-filled file stayed and the fallback to the ordinary domain rejected it ("oom"): the file is removed first. The file grows by fallocate where the filesystem supports it, so a full disk fails the intern instead of faulting a write through the mapping, and from 1 MiB instead of 64; growth stops at the mapping's reserve rather than failing short of it. The file is created 0666 under the umask, as the ordinary domain's is. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(sym): free the import dictionary's replaced tables; look up a batch's repeats once A shard table that grew was kept until the end of the import, since a lookup without the lock might still be reading it, so the dictionary held its tables about twice over. On a machine with little memory that left the page cache too small for the symbol file's records, which every lookup reads to confirm a match, and the import of a large vocabulary became a stream of random reads. Lookups now register in the parity of an epoch for the span of their lock-free probing; a replaced table is retired in the current epoch and freed, under the lock, once no lookup of an older epoch is left. Equal strings of a batch are looked up once, compared with the batch's own bytes, and the symbol file's mapping is marked random so a lookup that misses the page cache reads one page rather than a read-ahead window. Peak anonymous memory of a 2.5M-string import: 200 MB to 120 MB. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(sym): the import dictionary gives back the tables it replaced Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(parquet): finish the one-pass import's columns while the symbol file is still written With memory to spare the import runs one pass over every column, then stopped the symbol file appender and synced the file before closing and indexing the columns. On a disk busy writing back the column data the appender's last writeback request waits behind it, and the import sat idle for that wait, then for the symbol file's sync, before any column work began. The one-pass import now finishes its columns (on the pool) and builds their hash indexes in waves before it stops the appender, so that wait overlaps the work; a symbol column's header takes the domain's final count, which no longer changes once the pass is done. A column whose hash index ray_col_stream_hash_all built no longer asks for one, so the common finish after it has nothing left to do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(sym): random advice only on the written part of the import's symbol file Marking the whole mapping random made every new page of the file being appended a separate major fault, taken under the lock that serialises the appends (a few percent slower with memory to spare). The written part is marked random at each background sync instead, and the tail keeps the default. Replaced tables are freed after the lock is dropped rather than under it. A batch's dedupe table is cleared for the batch's size, not for the largest batch. The reclaim test counts table sizes in the 4 KiB units ray_sys_get_stat uses whatever the page size, so it holds on 16 KiB pages. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(parquet): a chunk whose final flush fails fails the import In the one-pass layout a chunk's stream is flushed before its writeback is started, and a failed flush only skipped the writeback: the stream had dropped the bytes it still buffered, the close after it succeeded, and the import published a table with those rows zeroed. A failed flush is now the task's error, so nothing is published, and the writeback starts only after a flush that succeeded. New test parquet/chunk_flush_error (Linux): a file size limit inside the buffered tail of the first chunk makes that flush fail; the import must report it and publish nothing. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]> * perf(query): isolate sparse group-count worker slices (#741) * perf(query): isolate sparse group counters by cache line * test(query): cover sparse count stride through reachable queries * fix(query): compare ordered symbols by lexical value (#743) * fix(query): compare ordered symbols by lexical value (#738) * perf(query): bound symbol ordering setup to scanned ids * perf(query): compose safe nested selects before planning (#754) * perf(query): compose safe nested selects before planning * fix(query): bound nested select planning and preserve overflow semantics * test(query): cover empty grouped nested selects and large script rewrites * test(query): verify scoped sources shadow global tables * fix(query): preserve materialized product and filtered reduction semantics * fix(ci): start select merge smoke fuzzing from seeds * fix(query): align membership, concat, and grouped fallback semantics (#744) * fix(query): align collection membership across evaluation paths * fix(query): address membership and concat review regressions * fix(query): preserve concat aggregate slots and scalar broadcasting * fix(query): close filtered count and concat fallback gaps * fix(query): preserve per-row enlist constructors * fix(query): preserve collection concat across query scopes * test(pool): drain pending reads before cache eviction * test(query): account for unmerged parallel aggregate variability * fix(group): fold keyless reduction partials in chunk order Scalar reductions and the keyless select scan kept one accumulator per worker while the pool hands out tasks dynamically, so F64 sum, avg, var and prod changed from run to run. Partials are now kept per chunk, with chunk boundaries derived from the row count only, and folded in chunk order, which gives the same bits at every core count. * fix(query): preserve concat operands through helper fallbacks * fix(query): preserve materialized columns for nested sort * test(pool): batch page reads while settling mappings * test(query): restore bounded aggregate comparison after reduction fix * fix(query): preserve helper globals during fallback expansion * fix(query): preserve helper scope across fallback aliases * fix(query): preserve fallback text and grouped output layout * fix(query): retain column provenance in opaque helpers * test(pool): require worker participation before asserting reclaim * fix(query): align helper literals, concat operands and grouped layout across paths The collection-concat detector recursed without end on an opaque helper around row text; it now inspects the unexpanded call's arguments. A grouped output named like its key kept only the key; the layout pass treats the last column of a repeated name as the output. Grouped fallback outputs follow the requested order, as planned outputs do. A concat operand the planner has no node for (a reordered, indexed or cast column) is a whole column in projections, so select agrees with update, where and by; a STR column's cell keeps its type row by row. Helper purity covers every non-restricted, non-special-form builtin outside system namespaces. A literal symbol is the symbol inside a named helper's body on every path, while inline lambdas keep the query's column rule; a named helper's free names never see its caller's formals or a derived alias. Aggregate classification skips the trial compile for bare columns and concat-free column expressions. * fix(eval): run query helpers as bytecode with row provenance on the VM stack A helper called from a query fallback ran on the tree walker so concat could tell column parameters from bound collections. The tree walker ignores return, binds lazy arguments it cannot read twice, stops near 62 scopes and is about three times slower on recursion. Helpers run as bytecode again. Each VM stack slot carries a row flag: parameter loads take it from the call, let stores and loads copy it, builtins the planner lowers row by row keep it, collection verbs clear it, nested compiled calls pass it on and return it with their result, and concat consults it. A call frame marks the lexical boundary: the query's aliases and locals are hidden, a free name that is a source column binds on first use to the row's cell or the whole column, and anything else is a global. The tree walker stays for closures and for lambdas written inline in a query, whose literals follow the column rule; it now forces lazy parameters at binding. An opaque helper under a grouped aggregate evaluates per group. call_lambda is the direct bytecode path again outside queries. * fix(eval): key provenance caches on the symbol epoch and carry opaque helper results The row-wise builtin table, the helper purity tables and the per-object verdict cache are rebuilt when the symbol-table epoch changes, so a runtime re-init cannot leave a stale id or address behind. The compiled call path computes a result flag only for builtins, a scoped window clears the flag of a local it rebound, and the call-frame binding comment states that only an allocation failure leaves a name unbound. At the query level an opaque helper given row data yields row data, so a concat over its result keeps text semantics. A source column shadowing a global helper of the same name is documented and tested. * refactor(eval): drop the dead inline-lambda bytecode gate in query calls A lambda written inline in a query captures the query's bindings and is therefore a closure, which is never compiled; the tree walker handles it with the query's literal rule regardless. Pin that rule with a lambda the planner does not substitute. * fix(eval): keep a helper's free source column on the query's rows A source column bound on demand into a helper's call frame carried its row flag only on the first read; the frame now records where those bindings start and every lookup of one sets the flag. The binding itself is the query's own: the row's cell, the group's slice or the whole column, taken from the frames below the call frame, or sliced by the group's rows when the per-group fallback did not bind that column for its own expression. While a projection binds output aliases, the source table decides, as before. * feat(query): group on a helper the planner cannot lower A by: key that is an opaque helper is evaluated once over the table, where its column arguments keep their rows, and grouped as a hidden column named after the expression, as other computed keys are. * fix(eval): carry row provenance through the tree walker Every evaluation publishes whether its value derives from the active query's rows: a query frame's column binding, a helper's source column, a row-wise builtin over such a value, or a compiled helper's result. The concat hook and the helper call site read that flag instead of re-deriving it from the syntax, which also removes a DAG compile per row from the call site; the syntactic analysis remains for the result of an interpreted closure. Inside a function, concat joins text only when an operand carries row provenance; otherwise it keeps collection semantics, whatever called it. Helper purity is an allowlist again, and a name standing for a user function is never pure. A helper's free source column is the query's binding for it, never a caller's local, and a nested query inside a helper restores the enclosing group's rows. Reordering and indexing keep row provenance in the VM; a bound vector returned by a helper does not. Every grouped result keeps the requested output order, and a purity lookup no longer binds a column into a helper's call frame as a side effect, which the planner then mistook for a lexical local. * perf(string): build a two-cell text concat as an atom Row-by-row text concat of two cells produced a one-row vector and unpacked it; it now builds the SYM or STR atom directly. * fix(eval): keep row provenance on every binding, through forms, and in by keys Scope frames carry a row-provenance flag per binding, so a let local in an interpreted lambda, a parameter, a scoped window's locals and a helper's source column all report their own provenance; the separate call-scope bookkeeping is gone, and a call frame records whether it was made by name for the literal rule. Flags are tri-state in the VM and the tree walker: a try handler's value or an interpreted closure's result is unknown and falls back to the syntactic analysis, so a bound constant is not row data and a row value through a handler still is. Only control forms pass their operand's provenance through; a nested select, update or join builds a new value. A null text atom follows the kernel's null rule row by row. An opaque helper used as the by: key is evaluated over the rows where: keeps, row by row when its body holds a condition over one value, grouped under the planned key's name, and with no outputs the key replaces the source column it is named after. * fix(group): pad keyless chunk accumulators to 128-byte line pairs Blocks of chunks scanned at the same time sat on neighbouring 64-byte lines, which the adjacent-line prefetcher moves as a pair, so they still bounced between cores on every row of the generic kernel. Five aggregates over 70K rows on a two-socket box took 5.7 ms against 0.58 ms before the chunked fold. * fix(eval): scope provenance to the innermost query and carry it through closures A lookup that passes a query frame reports the binding below as plain data, so a nested query inside a helper no longer takes the caller's row value as its own row data. A closure's captures keep their flags, and a try handler's own evaluation reports its value's provenance, so a row value through a handler used inside the helper stays row data. set passes its value's provenance through; a lambda called inside a named helper's body is that body's text, so its quoted symbols stay symbols. A null cell is the empty text the vector kernel reads, while a null literal still nulls the row. An opaque by: key runs row by row only for a condition over one value, looking helpers up lexically before globally; a let, a sequence or a loop keeps the key whole. * fix(env): size a closure's capture for its provenance entry The key vector of a captured scope was sized for the bindings alone, and the provenance entry appended after them wrote one slot past it. Regressions create closures inside a query with several live row bindings, directly in a per-row expression and inside an inline lambda. * fix(env): resolve a closure's capture provenance at call time A closure stores no row provenance: it is relative to a query. When the closure is called while the frames it captured from are live, each capture takes the provenance its binding has at that moment, relative to the innermost query, and a compiled frame publishes its slots for a closure whose scoped window has already closed. An escaped closure's captures are plain data. The stored entry, its spellable key, its serialization and the intern per closure call are gone. The opaque by: key gate leaves and/or to elementwise evaluation, treats an if over an aggregate condition as one value for the column, and resolves names inside a global helper's body globally. A null STR literal follows the kernel's null rule on both paths. * fix(env): keep a closure's capture flags in the query frame it was made under The flags are recorded in the innermost query frame when the closure is made, keyed by the capture object, and consulted only while that frame is the innermost query; they are freed with the frame. Nothing about provenance is stored in the closure, matched by object identity, or limited in count, and the compiled frame publishes nothing. An opaque by: key is evaluated over the whole column and again row by row only if a conditional tested a vector derived from the rows during that run. Two STR literals join as strings on both paths. A try fallback value keeps the provenance its expression had, in both interpreters. A closure is never compiled when called through another function, so it keeps its environment. * feat(eval): compile closures, loading captures as flagged constants A closure compiles like any lambda; its captures are loaded by OP_LOADCAP as fixed values. The capture row flags live on the lambda in two new slots that are never serialized, together with the serial of the query frame the closure was made under, and apply only while a frame with that serial is the innermost query. No record is keyed by address, nothing is kept per closure in a frame, lookups are constant time, and a recursive closure called from a compiled helper keeps bytecode's depth. A lambda made inside a query is query text and stays on the tree walker, which keeps the query's literal rule; the tree walker reports its result's provenance like the VM does, so a try handler of either kind agrees. An opaque by: key is evaluated again row by row when any conditional tested a vector during the whole-column run, or when that run failed. * perf(eval): clear only the VM header per compiled call Every stack, return and trap slot is written before it is read and the locals are set explicitly, so zeroing the whole exec block per call was wasted work that outweighed a small body. * fix(eval): compile a closure only when its captures have the expected shape A closure compiles only with SYM keys and a LIST of values of equal length; anything else stays on the tree walker, whose capture binding reports the type error. The deserializer rejects a lambda whose closure is not such a dict, and the compiled capture loads check the list type. * test(serde): pin the closure shape check and size lambdas by their slot layout The deserializer's rejection of a closure whose values are not a LIST now has a test that fails when the check is reverted. Three tests built lambdas with seven pointer slots while the heap walks every slot of the current layout on retain and free; they and the shallow object-size report use LAMBDA_SLOTS. * fix(mem): count a closure's captures in both object-graph walkers .mem.objsize stopped at a lambda's debug slot and the heap's retained count skipped the capture-flag vector; both now walk the closure and capture-flag slots. objsize.rfl pins that a closure outweighs the same lambda without one. * fix(eval): bind a closure's captures as locals of its compiled body A compiled closure resolved names differently from the tree walker: a let of a captured name allocated a new slot, a capture named like a builtin resolved to the builtin, a captured self was the closure's maker, a caller's local of the same name stood in for a capture inside a window, and a closure with more than 255 captures read globals. The compiler now binds every capture to a local slot in a prologue, a local shadows special forms and builtins, self is never captured and loads through OP_LOADSELF (also for a bare self in any compiled body), and a closure past the slot limit stays on the tree walker. A closure compiles on its second call, so one made and called once keeps no bytecode; capture row flags are kept only for lambdas made inside a query. A by: key body with an effect is evaluated row by row from the start instead of whole first, so the effect runs once per row; a failed whole-column run clears the raise payload and trace it leaves behind. * test(eval): pin the capture-flag release, the self exclusion and the query-text lambda rule The flag-release probe makes a lambda per row; the compiler no longer skips a self capture itself, so the env exclusion is the one mechanism; a lambda with nothing to capture written in query text keeps the column rule for its quoted symbols. * perf(eval): bind a compiled closure's captures with one opcode OP_BINDCAPS stores every capture into its slot from one constant map instead of a load and a store per capture, so a closure call pays one dispatch for its prologue. The flag-release probe's lambda now captures a row-flagged local, so a leaked flag vector shows. * fix(eval): count a closure call once when deciding to compile The VM's call opcode decided not to compile a closure on its first call, then fell back to the tree-walk entry, which decided again and compiled. The entry now takes the decision from its caller. * fix(eval): return ends a lambda on the tree walker too A closure compiles on its second call, so a return in its body gave the identity on the first (interpreted) call and the early exit on the compiled one. Inside a lambda the tree walker's return now parks the value on the VM and raises a return marker that every form propagates; the lambda's call boundary turns it back into the value, try lets it through, and the VM's error path treats a marker from a tree-walked special form as the frame's return. Outside any lambda return is still its value. * fix(query): never inline a closure into a query The fallback inliner skipped a closure only once it had compiled, and a closure now compiles on its second call, so a query inlined an uncompiled closure's body and a captured name read a source column or a global of that name; the planner's own inlining had the same hole. Neither inlines a lambda with a closure. The window sync covers every slot of a frame, and a swallowed whole-column key failure drops a pending return value. * test(query): a closure as the by: key, pure and with an effect * fix(agg): flag a grouped key column as nullable only when a null key was emitted A fused where: can remove every null row of the key column, yet the grouped result inherited the source column's may-have-nulls flag, while the same query over the filtered table materialized first carried none, so one result had two spellings on the wire (the nested select differential fuzzer caught it). The key gather and the dense key emit keep the flag only when a gathered key is null; symbol keys keep it as before. * feat(eval): compile a fn literal once as a template and share it across its closures A closure's first call ran on the tree walker and later calls compiled, so every engine difference showed up as call-count dependence, and each closure compiled its own copy of the body. A fn literal inside a compiled body is now compiled once, as a template, when the enclosing function compiles; OP_MKCLOSURE makes each closure share that bytecode and capture only the enclosing slots the body mentions, with their row flags. OP_BINDCAPS binds captures by name, so a let that had not run leaves its slot empty, and a read of an empty let slot (OP_LOADENVG) falls back to the global, as the tree walker does. Closures no longer compile on their second call; a lazy value is materialized when captured. The by: key purity check follows a callee wherever it is bound (a global, a parameter or let of an enclosing frame, a capture, a lambda literal bound earlier in the body); a computed or unknown callee is an effect, and builtins are pure unless they are system, I/O or a few that read outside their arguments. * perf(agg): settle a grouped key's null flag with a vectorised, pool-split scan The per-key scan behind the flag fix was serial and showed on large groupings. The scan is now a block-wise sentinel compare the compiler vectorises, split across the pool for a large column, and shared by the three emitters and by the legacy wide-key path, which seeded the flag from the source column and could only ever set it; an F64 key, alone or beside another key, now agrees with the materialized reference too. * fix(eval): materialize a lazy slot when a compiled closure captures it A lazy handle is single-use: materializing frees its graph in place, so a closure dict holding the handle would fail the closure's second call. Rayfall call sites materialize lazy arguments, but a caller of the C API reaches OP_MKCLOSURE with one; lang/closure_lazy_capture_vm passes a real lazy handle through call_lambda and calls the closure three times. The Rayfall shape that claimed to cover this never captured a lazy and is gone. A zero-parameter literal ([] parses as an empty I64 vector) now gets a template too instead of a private compile per closure. * fix(query): a text cell reduced from a column is a cell of the rows for concat A grouped (concat (first s) 'zz) gave null for an empty symbol in a grouped update and failed to produce one value per group in a grouped select, while the ungrouped projection read the empty cell as empty text. The planner's concat kernel takes a cell mask: an operand that reduces a text column (first, last, min, max) is a cell, so a null there is empty text and a STR cell keeps STR output. The grouped select's arithmetic-of-aggregates wrappers run with the group result as the active table and the hidden aggregate columns flagged as row-derived. * fix(eval): an unbound capture, eval in closures, deep literals, lexical capture, parameters in the purity walk A capture whose let had not run read as 0: capture slots are no longer fixed, so an empty one falls back to the global or a name error like any let slot. eval and resolve in a compiled body run inside a scope window over its locals, so a closure's eval sees its captures. Template compilation stops nesting at 32 levels and leaves deeper literals to the dynamic path, which compiles one level per call. A tree-walked lambda call marks its frames as the lexical boundary for capture, so a caller's locals are not captured whether the maker compiles or not. The by: key purity walk binds a callee's parameters to the call's argument text, so an effect reached through a parameter counts and a pure helper passed as one keeps the whole column. * perf(eval): share one compiled template per literal for closures made by interpreted code A closure made by the tree walker (the top level, a lambda that could not compile, a literal inside a special form the compiler hands to the tree walker) compiled its own copy of the body on its first call. ray_fn now keeps a per-thread table of templates keyed by the literal's parameter and body nodes (retained, so an address stays the entry's own) and its capture names; a hit shares the bytecode, a miss compiles once. The table is dropped with the runtime. Tests pin the sharing, two capture sets from one literal, the block-boundary case of the key null scan and the interpreted lazy capture. * fix(eval): match a closure template on every body node Two literals built for eval can share their parameter, first and last nodes and differ in between; the template table compared only those, so the second literal ran the first one's bytecode. An entry keeps every body node (literals over eight forms are not cached) and a hit requires all of them. A thread whose table outlived its runtime forgets its entries instead of releasing objects of a destroyed heap, and ray_fn uses the compiler's own closure shape gate. * perf(eval): cheaper closure creation on the interpreted path A template entry remembers the symbols its literal mentions, so a hit costs a pass over the dict keys instead of a walk of the body and allocates nothing; the capture walk gathers row flags in a local buffer and builds the flag vector only when one is set. Closures made and never called by an interpreted maker: 249 ms per 200k before, 202 after (dev 121); the fn literal inside or: 136 to 98 ms per 200k. * fix(eval): closure bodies resolve free names when they run; eval's window wraps only the call The eval/resolve window opened before the arguments were compiled, so a return, a let or a call inside an argument ran in the window and a return leaked the frame; it now opens right before the call and closes right after it. A closure body resolves the builtins it names when it runs instead of baking the one the template saw, and a top-level literal's baked template is recompiled once a function-valued global was rebound (ray_env_fn_generation). The VM's general call applies the same elementwise map, concat rule and provenance join as the dedicated opcodes. The symbol walk and the compiler stop at 1024 and 2048 levels; a literal holding more than 65536 vector elements is not kept in the template table; a body that did not compile is marked and never retried. The by: key purity walk binds a passed lambda's parameters as unknown, lets a nested literal see the enclosing body's parameters, and resolves an argument's name where the call was written. A grouped update expands its helper expression once instead of per group. * fix(query): the grouped update's planner skip is a flag of the call, not a remembered expression A remembered expression pointer could match a fresh expression at a reused address and skip the planner for it, turning a schema error into a name error. The flag now belongs to one grouped update. The OP_RET window unwind was unreachable once eval's window wraps only the call and is gone; the deep-literal test runs at the depth the sanitizer build's recursive release survives. * test(lang): pin the compiler's depth guard by result, within every platform's stack The regression test for the depth guard built a 12000-level literal and relied on the sanitizer build surviving its recursive release; the macOS one does not. The body is now a chain of nested ifs: compiled it runs as jumps and returns the parameter, on the tree walker it recurses and stops at the eval depth limit. 600 and 1500 levels return 1, 2500 (past the 2048 guard, within the bytecode jump range) is a limit error; with the guard removed it compiles and returns 1. The syntax page states the limit; the control-flow page's anchor to the lambdas section now resolves. * fix(query): concat cell flags cover every operand, and the planner takes 255 The text kernel read its per-operand cell flags from a 64-bit mask that was written for the first 64 operands only, so operand 64 shifted by 64. The flags are one byte per operand for all 255 positions, in the planned node and the two-operand path alike. The planner folded a query concat into one node up to 16 operands and left longer forms to the binary builtin, which rejected them; it now takes the executor's 255, so one limit governs the form. Tests run 65-operand concats: a cell at position 0 with a null literal at 64 nulls the row, a cell at 64 is a cell (empty text, STR output), a column joins every row. --------- Co-authored-by: Serhii Savchuk <[email protected]> * fix(query): sort and take a no-output grouping on a computed key (#772) * fix(query): sort and take a no-output grouping on a computed key A grouped select with a computed by: key and no outputs falls back to eval-level grouping and returned its first-of-group rows directly, so asc:, desc: and take: were dropped and groups came back in first-seen order. It now goes through apply_sort_take, as the plain-key branch does. * fix(query): gather a no-output computed-key grouping's columns by type The no-output computed-key branch built its result columns cell by cell through store_typed_elem, which has no STR or LIST case: STR cells were left unset (empty, or strings left from an earlier result, and sorting them aborted on an unset string pool) and a LIST column failed. The key and source columns are now gathered at each group's first row with ray_group_gather, which builds every column type, and a failed gather returns its error. * fix(query): keep a LIST-valued computed key and reject a misaligned one A computed `by:` key with no outputs gathered its key column only when the key was a typed vector, so a LIST-valued key lost both the key and its source column, in the grouped and in the empty-result path. A key whose length is neither the row count nor 1 was grouped as is, and the gathered columns were then read at group rows past their end. It now fails with `length`. * fix(group): release the partial list when a LIST gather append fails ray_group_gather's LIST arm assigned the result of ray_list_append back to its output, so a failed append dropped the list it had built so far. * fix(query): group a no-output select by a global's value, not as a column A bare `by:` name that is not a column of the table, such as a global vector, was still taken for a column on the no-output path, and the missing column was dereferenced. Such a name now takes the computed-key path, as the grouping before it already evaluated it. * fix(query): release the where selection on the no-output grouping path With `where:` and `by:`, the filter keeps an extra reference to its row selection that is released only at the end of the select. The no-output grouping returns earlier, so each call leaked the selection. * fix(query): group a no-output select by a local that shadows a column A `by:` name bound both as a local and as a column was grouped by the local's value, but the no-output path then read the column's key slot, which the grouping never filled, and returned garbage or crashed on a LIST column. Such a key now takes the computed-key path, and a missing key column is an error instead of a read of unset memory. * fix(query): release a by-dict's symbol vector on the no-output paths The vector of by-dict or quoted key names was released only at the end of the select, so the no-output grouping and the eval-level grouping, which return earlier, leaked it on every call. * fix(query): release the where selection on every exit of a select The filter's retained row selection was released only on the success path at the end of the select, so every error return with `where:` and `by:` leaked it. The select body now hands the selection to a thin wrapper that releases it whichever way the body returns. * fix(eval): free the error a `try` catches Neither `try` implementation freed the caught error, and a rethrow left its trace frames behind. Inside a function, the compiled path also handed a runtime error object to the handler; it now passes 0, as the top level does and the error guide documents. * fix(query): group a no-output select by an atom as one group An atom `by:` key, such as a global scalar, failed on the no-output path with a type error. It is now broadcast to one group, as a length-1 key is. A function used as a key now fails with a domain error that says so, instead of a vector-type error. * fix(query): keep every column of a no-output by-dict select with where With no outputs, the where prefilter narrowed the table to the columns the clauses read, so the result lost the other columns and their order. The prefilter now projects only when there are outputs. * fix(query): run a no-output grouped select over a parted table Every no-output grouped select without `where:` failed on a parted table with a vector-type error. It now flattens the table before the paths split. * fix(query): release the by-dict symbol vector on every exit of a select The by-dict and quoted key name vector joins the where selection in the select wrapper, so the error returns that skipped its release no longer leak it, and the per-return releases go away. * fix(query): free compile errors and failed fast-path results A key the compiler rejected left its error on the graph, and freeing the graph released it with ray_release, which skips errors, so it leaked. Failed top-k, fused take, vector allocation and asof operand results were dropped the same way; all now go to ray_error_free. * perf(query): gather only the kept rows of a parted no-output select Flattening the whole parted table to return one row per group cost the full table in memory. The select now runs on a narrow table that flattens only the columns its clauses read and stands in a row number for every other column, then gathers just the kept rows from the partitions. Tables wider than the gather's column limit still flatten. * fix(query): count quoted key and sort names as columns on parted tables The parted no-output select gathered only the columns its clauses referenced, and skipped quoted symbols, so `by: 's` or `desc: 'h` was grouped or sorted by a row-number stand-in. * perf(query): carry one row number through a parted no-output select Each unreferenced column was a row-number stand-in of its own, so a key with many groups gathered one row vector per column and could use more memory than flattening the table. The narrow table now holds the referenced columns and one hidden row number, and the result is rebuilt in the flattened layout from the kept rows. * fix(query): drop the filter's reference when where: keeps every row When every row passed, the filter returned the input table itself with an extra reference, which the no-output and the eval-level grouping never released, so the whole input leaked on every call. * test(query): cover the try trace clear and two error and parted cases A caught error raised through a nested call, a sorted parted select whose every row is its own group, and a failing asof operand on a parted table now each have a check. * fix(group): tell a null key from a function key The function-key check also caught the null and lazy types. A null key now has its own message, a lazy key is materialised first, and only the function types report a function. * fix(query): materialise a lazy computed key and keep where on a parted key A lazy computed key, such as a moving max, failed the no-output path's grouping. On a parted table, a where: on the key column was deferred past the grouping, which a no-output select never reaches, so its rows went unfiltered into the row path. * fix(query): sort a parted table without by: by gathering the kept rows A sort without `by:` that neither streaming path took fell through to the flat sort, which read parted columns as plain ones and failed with a type error, and its take form leaked. The sort now runs over the sort keys and a row number, then gathers the kept rows from the partitions with the row gatherer the no-output grouping uses. Shapes it declines flatten the table first. The tests that pinned the type error compare with the flattened table instead. * refactor(query): drop the redundant key-name entry of the parted grouping The derived key name already covers `key`, so the separate entry did nothing. A test now pins the key-name guard itself. * fix(query): decline the parted row gather when __row is a user name The parted no-output grouping and sort carry a hidden `__row` column and declined only when the table had one. A by-dict alias or a bound local or global of that name shadowed it, giving an error or silently grouping by row number. Any such use now falls back to the flattened table. * refactor(group): drop the unreachable lazy-key materialise Every expression key reaches this check already materialised; the computed-key paths in query.c do the work and stay. * fix(query): keep parted sorts bounded and decline output alias chains A parted sort without by: flattened the table whenever a sort key was not output under its own name, though the narrow sort reads keys as columns either way. It now declines only when an output names another output's alias, which the flat path reads as the alias and the gather read as the source column, a silent wrong result. * fix(query): stream a parted top-k only when the sort key is its own column The parted top-k accepted a sort key that is an output alias of another column: each partition sorted by the column, the merge by the output, so the take kept the wrong rows. * fix(query): flatten a parted no-output select whose clauses run code The parted row gather builds a narrow table from the columns its clauses name, so a column read inside a helper, or a name built at run time, was missing from it or resolved to the hidden row column. Clauses that call a lambda, call a computed head, read a container that may hold lambdas, or evaluate text now take the flattened table. * refactor(query): drop the bound-name check of the parted row column With code-running clauses declined, a bound `__row` can only be shadowed through a name the select writes, which the clause check covers. A test pins a helper that reads a bound `__row`. * fix(exec): keep no rows for a sort with take: 0 The sort-and-head fusion passed the take to the sort, which reads a limit of 0 as no limit, so a sorted select with `take: 0` returned every row. The fusion now applies only to a positive take. * fix(query): check each by-dict value on its own for code in a parted select The run-code check passed a by-dict's value list through the call-head rule, so a dict whose first value was a builtin call looked like a computed call and flattened the whole parted table. * fix(query): follow a symbol binding to a lambda when checking for code A dict literal stores its values unevaluated, so `{f: hy}` holds the symbol `hy`, and calling `(D.f 0)` reaches the lambda through one more lookup. The parted run-code check stopped at the symbol and took the bounded path, which then missed the helper's columns. A binding that is a symbol naming a lambda now counts as code, for plain and dotted names. * fix(query): evaluate a collection concat by: key over the whole column The planner keeps concat for text, so a bare by: key that concatenates collections no longer lowers. Only helper keys fell back to the whole-column evaluation; a bare concat key failed with "failed to compile group key expression", even when aligned with the rows. Route keys that call concat to the same fallback: an aligned one groups, a misaligned one is refused with length. * test(mem): measure top-level try per iteration, not per statement A handler written as a lambda literal adds an entry to the closure template cache once per statement (bounded at 256 entries). Run each top-level try statement 1000 and 4000 times and require the same cost, so the probe still catches a per-iteration leak of the caught error. * fix(query): evaluate any by: key the planner cannot lower over the whole column A bare computed by: key with no helper, such as (reverse x), (asc x) or (til (count x)), failed with "failed to compile group key expression". Only helper and concat keys took the whole-column fallback. Try to lower every computed key and send any key that does not lower to the same fallback: it groups as its lambda form does, honours where:, desc: and take:, and a key of another length is refused with length. A text concat still lowers and stays on the planned path. * fix(query): evaluate an unlowered by: key over parted columns flattened The whole-column key fallback evaluated the key over a parted table's partition columns and failed with "key expression must yield one value per row". With outputs, flatten the columns the select reads (the whole table when a clause runs code whose reads are unseen) before evaluating the key. With no output, leave the select to the first-rows path, and when that path declines, run the select again over the flattened table so the key reaches the fallback there. * fix(query): report an unknown column in an unlowered by: key as schema A key that lowers to the planner reports an unknown column as schema ("column 'c' not found"); one evaluated over the whole column reported the evaluator's name error. Before evaluating, look for a free name in the key that is no column and no bound name, outside any lambda written in it, and report it as schema. An unknown function stays a name error. * perf(group): check for a function or null key inside the scalar-key branch The check that refuses a by: key bound to a function or to null sat as its own early return in exec_group_run, with a release loop of its own. It slowed computed keys on that path by 5-12% at 1M rows (bare bool, mod, like and if keys), through the code built for the function rather than the check itself. Make it part of the existing scalar-key branch, which already returns its errors, and build the error in a cold out-of-line helper. The keys time as on dev again; the errors are unchanged. * fix(query): let and set in a do bind their name for an unlowered key The unknown-column check before the whole-column key evaluation reported a name the key binds itself, `(do (let q x) (reverse q))` or `(do (set q x) (reverse q))`, as an unknown column. A two-argument let or set now binds its name for the forms after it, and only its value is checked. The four-form let the check assumed is no let form. * fix(query): evaluate an unlowered by-dict value over parted columns flattened A by-dict value the planner cannot lower, a helper `{k: (fk)}` or a builtin with no kernel `{k: (reverse i)}`, failed over a parted table: the parted by-dict deferral compiled it ("failed to compile group key expression"), and the eager path evaluated it over the partition columns. The deferral now takes only values that lower; the eager path first flattens the columns the select reads (the whole table with no output, or when a clause runs code whose reads are unseen). The where: prefilter before a computed key no longer narrows the table to the columns the clauses name when a clause calls a helper: the helper's own column reads failed with a name error, flat or parted. * fix(query): keep projecting a where: prefilter that reads a container The where: prefilter before a computed key stopped narrowing the table whenever a clause named a variable bound to a list, dict or table, since it used the parted gather paths' test, where such a container may hold lambdas. A where: reading a config dict then filtered every column of a wide table. The prefilter now declines only for code that reads columns the clauses do not name: a lambda, a name bound to one or to its name, a computed callee, eval, parse, resolve, load or value. The parted gather paths keep the container rule. * fix(query): know code and binders by the builtin, not by the call's spelling Two checks in the by: key paths matched names as written. The unknown-column check before the whole-column key evaluation followed let and set only as siblings in one form, so a name bound in a nested do or an if, `(f (do (do (set q x)) q))`, was refused as an unknown column. The check exists only to pick the error code: it now runs only on keys that bind no name and run no code, and leaves every other key to the evaluator. The test for code whose column reads a clause does not show matched fn/eval/parse/resolve/load/value by the spelling of the call head, so a builtin called by another name, `(set getv resolve)` then `{k: (getv rname)}`, took the parted narrow-copy path and read its private row-number column. Names are now resolved through locals, globals, dotted paths and one name hop, and a builtin is known by the name it was registered under. A name of a column of the table is the column. * fix(query): resolve clause names as the evaluator does, objects included The checks that classify a clause's names and nodes read a name as a column before looking for a lexical local, so a parameter or let that hides a column was taken for the column: - a local lambda named after a column, `(run P (fn [] y))` with `{k: (x)}`, was not seen as code, and the parted narrow copy left out the column it reads; - a binder passed as a parameter, `(run set)` with `(x q y)`, was not seen as one, and the unknown-column check refused the key; - the parted sort path gathered the column for an output `x: x` that reads a parameter x. A lexical local now comes first, then the query column, then a global. A builtin placed in a built query as the object itself, `(list resolve rname)`, was not recognised as code (and `set`, `let` or `quote` as a binder); the checks now look at the object as well as at names. * fix(query): sort a parted table by gathering only stored output columns The parted sort path took any output name that reads a column, a dotted field of one included (`month: date.mm`), and then looked for a stored column of that exact name to gather, failing with "lost a column of a parted table". An output it gathers must be a stored column, and one no lexical local hides; any other leaves the select to the flat sort. * perf(import): bound parquet symbol import and splayed hash-index I/O (#773) * perf(parquet): import dictionary counters under RAY_CSV_TRACE Each symbol pass reports the strings it interned, batch-local repeats, global probes, hits, inserts, slots read, false tag matches, table growth and the dictionary sizes, so the import's access pattern can be measured on real data. * perf(store): allocate SYM stream lookup tables on first remap A SYM column writer allocated and cleared its runtime-to-file lookup tables at open, though a writer fed only chunks already in its target domain never reads them. They are now made by the first chunk that needs a remap; the parquet imp…
Record master as an ancestor without changing the agreed release tree. Master 5d5f47c has exactly the tree of dev ancestor b5a813a; its squash release commit had lost that relationship. Keep all files exactly at accepted dev d9f9ab6, including the deferred-feature and CI-patch exclusions. Refs #984. No master update, tag, or release action.
singaraiona
added a commit
that referenced
this pull request
Nov 11, 2026
## Problem Merging a release PR leaves a commit on `master` that `dev` lacks. The next release PR is then out of date with `master` and, after a squash, shows conflicts that aren't real. #1108 showed 72 conflicting files even though `master` had no content `dev` lacked. `RELEASE.md` asks for a manual merge-back, but nothing enforced it and it was skipped after v2.11.5 and v3.0.1. #985 tried to repair the ancestry, but it merged before #984 existed, so it could only tie `dev` to v2.11.5. ## Change - **New `merge-back` job in `release.yml`:** it checks out the release commit and runs the helper from a copy in `RUNNER_TEMP`, so the dev tip can't change which helper runs. It runs after `prepare` and doesn't wait for the build, because the commit is on `master` whether or not the build succeeds. It isn't best-effort, so a failure shows red. - **New `.github/release-merge-back.sh`:** it checks that the release tree equals the PR head and that `dev` contains the PR head, then does a `-s ours` merge and confirms that no files changed. It retries if `dev` moves during the push, and does nothing if `dev` already contains the release. - **`RELEASE.md`:** the manual fallback runs the same helper with the release PR's SHAs, so it applies the same checks. When a check fails, it says to do a normal, reviewed merge and never `-s ours`. ## Testing The workflow job itself hasn't run. I tested the script against a local bare repo: | Scenario | Result | |---|---| | Squash release, `dev` moved on | Merged, tree unchanged, next release merges cleanly | | Re-run | No-op | | Merge-commit release | Merged | | `master` carries a hotfix | Fails with an error, `dev` untouched | | `dev` lacks the PR head | Fails with an error, `dev` untouched | | Push rejected once | Retried and merged | ## Before merging The job pushes with the existing `PAT` secret, because `GITHUB_TOKEN` can't get past the required `rayforce-audit` check on `dev`. No current workflow uses that secret, so its owner and scopes are unverified. It needs to belong to an admin, and it may need the `workflow` scope. If it can't push, the job fails with instructions for the manual step.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Release ancestry reconciliation for #984
Merge this PR using a merge commit, NOT squash or rebase. Its purpose is to retain
masteras an ancestor ofdev, so the existingdev → masterrelease PR can merge without conflicts.No files change. The complete tree remains exactly accepted
d9f9ab68(d8cfb74f25090c4c33e5594cca375a23fded1bde). The four deferred feature/fix PRs and the separate NDEBUG CI experiment are not included.The previous master release
5d5f47c2has exactly the complete tree of dev ancestorb5a813a1(fae009b2a5700a3c4eee236b437e3b7f2c3ddf5a). Its squash release lost the ancestry relationship. Ordinary merge-tree analysis reports56 conflicted files; this justified ancestry-only merge records that already incorporated release snapshot without manually remixing engine code.Local head
580b1b261c47d803e732c7606865990002c8e41fhas ordered parents accepted devd9f9ab68and master5d5f47c2. All tracked content/tree is unchanged. After this commit, localmerge-tree master HEADis clean and equals the cut tree.Direct dev update was not attempted: dev reports required
rayforce-audit. This topic PR preserves that check normally; no force push, fabricated status, protection change, master update, tag or release action.