Skip to content

v3.0.2 - #1108

Merged
singaraiona merged 193 commits into
masterfrom
dev
Nov 6, 2026
Merged

v3.0.2#1108
singaraiona merged 193 commits into
masterfrom
dev

Conversation

@singaraiona

Copy link
Copy Markdown
Collaborator

What & why

Checklist

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

singaraiona and others added 30 commits October 5, 2026 16:47
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(store): a replaced splayed table keeps one copy of itself (#713)
fix(query): exclude null symbols from not-in
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]>
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]>
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]>
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]>
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]>
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]>
…ory 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]>
…atermark

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(index): narrow hash index arrays and build them partition by partition
fix(heap): off-heap allocations spill, memory goes back between statements (#712)
)

* 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]>
…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 counters by cache line

* test(query): cover sparse count stride through reachable queries
* 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

* 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
…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

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.
…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 import no longer holds about 12 MB of heap per SYM
column.

* perf(symimp): do not clear freshly mapped shard tables

ray_sys_alloc always returns zero-filled memory (a fresh anonymous
mapping or a new fallocated spill file); the contract is now written
down, and the WASM fallback clears what it allocates. A new shard table
is no longer memset, which on a spilled table wrote pages of zeros.

* perf(store): write in-domain W32 symbol chunks with one fwrite

A W32 chunk already in the writer's domain is written as one block per
batch instead of element by element; the null flag is still derived
from the positions written.

* perf(parquet): decompress dictionary pages straight into the dictionary buffer

* perf(parquet): read a row group's column metadata once per task

A direct-import task reuses the column metadata it already parsed, sizes
its reader for the one column it decodes, and borrows page, dictionary
and symbol scratch buffers kept per worker.

* perf(symimp): take import dictionary shard and tag from separate hash bits

The import dictionary chose its shard from the low 32 bits of the hash
that also form the stored tag and home slot, leaving a few independent
tag bits per slot. The shard now comes from the top bits of the 64-bit
hash, so far fewer probes compare a record's bytes for a tag match.
Import domains take 64-bit hashes through a new batch entry point.

* perf(symimp): grouped symbol dictionary resolution for large imports

New symgrp module: staged strings are resolved one hash group at a time
against append-only index logs, with exact byte verification of
candidates read from .sym in position order. The import dictionary gains
bulk reserve/put/get and offset calls; after a reserve the per-batch
intern path refuses to run.

* perf(parquet): import large symbol columns in two rounds by hash group

When the symbol columns' uncompressed bytes exceed a quarter of RAM, each
symbol column is decoded twice: the first round deduplicates each chunk
exactly and stages {hash, length, local id}, the resolve step assigns
positions group by group, and the second round writes new records at
their reserved offsets and the codes. No string bytes are staged, the
dictionary is never probed at random, and .sym is written sequentially.
Small imports keep the direct path.

* fix(parquet): free a task writer's symbol LUT when the task ends

The per-task column writers of the direct and the grouped symbol import
now abort their stream after fclose, which frees the lazily built LUT
block. Tests cover a reused LUT block that must not map a runtime id to
position 0, a W32 chunk from another domain that must be remapped, a
dictionary page whose declared size disagrees with its data, and
repeated imports that must not grow allocated bytes.

* perf(parquet): read the grouped dictionary's records in file order

The second round of the grouped symbol import re-read every record
written by earlier windows: each window's spans covered the whole
earlier region, and with all spans requested at once on a small box the
pages were evicted before the copy faulted them back 4 KB at a time.

Strings that a later row group meets again are now laid out first, each
group in first-occurrence order, so a window's candidates sit in a
short prefix. Spans are requested in 4 MB pieces at most 32 MB ahead of
the copy. Positions in row order come from per-task bitmaps instead of
two random-access lookup arrays and an owners list, new records go out
through a buffered pwrite, and per-worker buffers live for the whole
pass (buffers over 4 MB are freed when it ends). RAY_PQ_SYM_ORDER=
rowsflat keeps the previous layout.

* fix(parquet): deterministic grouped symbol positions under hash collisions

Decode2 workers no longer hand out positions for strings that collide on
the full hash; they record the mismatch, and settle assigns positions to
every mismatch in first-occurrence order (task, local id), so the
dictionary bytes do not depend on which worker ran which task. Grouped
import errors report cancel once interrupted, as the direct import does,
and a failed window load no longer leaks the previous window's records.

* perf(parquet): cut grouped staging from shared chunks, grow dedupe arenas

A task's staging arrays were seven separate mappings held for the whole
pass, about 40 KB per row group; they are now one block cut from shared
1 MB chunks. Each worker's dedupe arena starts at 64 KB and doubles
instead of starting at the generation limit.

* perf(parquet): start writeback over what each grouped window wrote

The per-window sync advanced its cursor over the whole pass's
reservation after the first window, so later windows never started
writeback and their records stayed dirty until the final sync. Each
window now starts writeback of exactly the records it wrote, and the
header and access advice are applied once after the last window.

* perf(parquet): choose direct or grouped symbol import per column

Once the symbol text is large enough for grouping, each column's
vocabulary is bounded from its footer (dictionary page bytes, or the
whole chunk for a plain fallback), and the smallest columns go direct
while they fit; direct columns run first and their strings are adopted
into the grouped index.

* perf(parquet): size a window load's sort arrays by its candidates

* fix(parquet): free extra task errors with ray_error_free

ray_release does nothing for error objects, so the second and later
errors of a failed import leaked.

* test(parquet): fail grouped record writes and check nothing is published

* fix(pool): return from pool creation only after every worker's heap is set up

Workers read the environment while initialising their heaps, so a
caller that changed the environment right after creating a pool could
free it under a worker's getenv. Pool creation now waits on a semaphore
each worker posts once its heap is set up; tests that rebuild pools wait
for the workers too.

* test(parquet): mixed direct and grouped symbol columns across modes and orders

* fix(parquet): bound a symbol column's vocabulary from above

The per-column direct/grouped decision counted the dictionary page's
stored bytes and missed strings in plain data pages after a fallback.
The bound now uses the dictionary page's decoded size plus a per-string
cost, and counts data pages whenever the encoding stats do not rule out
plain values.

* fix(parquet): make mixed direct and grouped imports deterministic

A column goes direct inside a grouped import only when every chunk is a
dictionary page plus ids; those dictionaries are interned serially in
row-group order before any pass, so the parallel direct pass only finds
existing strings and positions do not depend on the workers.

* fix(parquet): report a grouped import's error when the file has no row groups

* perf(parquet): free the direct shard tables at the first grouped reservation

* test(parquet): direct caps, adoption counts, arena cap and top-bit hash collisions

* fix(parquet): report the dictionary decoder's own error when seeding fails

Seeding a direct column's dictionary reported a generic "unreadable or
allocation failed" for any failure; it now carries the decoder's reason
(unsupported codec, oversized or invalid dictionary page) and the column,
as the direct pass does. Adds the skeptic's footer-shape tests.

* fix(parquet): saturate the vocabulary bound and keep the direct pick apart

A crafted footer with a size near INT64_MAX overflowed the bound
(undefined behaviour) and a wrapped negative bound read as the direct
marker. Sums now saturate, negative inputs count as zero, and the direct
choice is its own flag.

* fix(parquet): treat a missing chunk size as unsure, skip zero-row groups

A chunk with values but no positive uncompressed size was taken as
dictionary-only with a zero bound; it is now unsure and unbounded.
Zero-row row groups, as writers emit them, are left out of the bounds,
the dictionary-only test and seeding. Seeded imports report strings the
direct pass had to add (seed_miss) in the trace.

* fix(symimp): close the race between a lookup and the first reservation

reserved is atomic; a reservation stores it before reading the active
lookup counts and frees the shard tables only when none is in flight,
and a lookup registers before rechecking it and checks again under the
add lock, so no table is read after it is freed and no string is added
after a reservation.

* test(parquet): bound waits on worker start, cover a degenerate hash on mixed imports

* perf(index): per-phase I/O counters for the splayed hash build

Under RAY_CSV_TRACE a `splayed hash io:` line reports, per build phase,
the time, major faults, MB read and written, dirty MB dropped before
writeback, and the bytes the phase moves as a multiple of the column.

* perf(index): build a splayed column's hash index in its file

The splayed hash build attached the index to an extra reference of the
mapped column, which copied the whole column into the heap first, then
built every array in heap memory and copied it again into the file. The
index is now attached to the mapping itself and built straight into a
preallocated region of the column file: gkeys, offs and rows front to
back, the slot table batch by batch, the marker last; any failure cuts
the file back to its payload. The splayed save paths use the same build.
Key words and row ids a batch has consumed are punched out of their
spill files so their dirty pages are never written back. The bytes on
disk are unchanged.

* fix(heap): report whether a raw discard punched pages

ray_raw_discard is a no-op where MADV_REMOVE does not exist (macOS); it
now returns whether pages were actually dropped and the discard test
expects zeroed pages only then, and checks both blocks free as direct
blocks.

* fix(store): build a hash index in place only where its blocks are held

A sparse region written through a shared mapping faults with SIGBUS on
a full disk. The in-place build now runs only on Linux file systems
that allocate on fallocate and overwrite in place (ext4, xfs, tmpfs,
overlayfs) and requires fallocate to succeed; elsewhere, and on any
copy-on-write or network file system, the in-memory build and append
are used as before.

* fix(store): fall back to the in-memory hash build when a region is refused

A refused fallocate or mapping cut the file back and dropped the hash
index; it now returns NYI so the callers build the index in memory and
append it, as they did before the in-place build.

* test(index): pin truncate on failure, marker last, direct-block order and save sizing

* fix(store): build a hash index in place only on ext4, xfs and tmpfs

An overlay mount reports its own file-system magic, not its upper
layer's, and an upper layer on a copy-on-write file system does not
reserve space for mapped writes on fallocate. Overlays now take the
in-memory build and append.

* test(heap): expect zeroed pages only where a raw discard punched them

* test(pool): skip the thread-spawn-failure probe under ThreadSanitizer

The probe forks and starts pool threads in the child, which
ThreadSanitizer refuses after a multi-threaded fork.

* test(parquet): unsized chunks, null-only groups, data offsets and grouped messages

* fix(parquet): a symbol chunk with rows but no size takes the grouped path

A chunk with rows and no uncompressed size added nothing to the file's
symbol text, so a file whose other text was small imported fully direct
and the column's unbounded vocabulary was never consulted. Its text now
counts as unbounded, so the per-column bound decides.

* fix(platform): cache the page size in an atomic

Two threads could initialise the lazy page-size static at once; the
value is the same on every thread, so it is now a relaxed atomic, and
block release uses the same cached value.

* test(heap): fail a non-punching discard where the spill directory punches

* fix(parquet): seed a dictionary page within the decoder's chunk bounds

Seeding bounded the dictionary page by data_page_offset, which the
decoder never uses, and refused files the direct import reads. It now
reads the dictionary page within the chunk exactly as the decoder does.

* fix(parquet): name the column in every per-column import error

Codec, chunk-bounds and grouped-mode decode errors now carry the column
name, as the direct pass's errors do.

* test(parquet): seeding refuses a dictionary page with a bad encoding itself

* fix(parquet): check the page CRC when seeding a dictionary

Seeding read a column's dictionary page without the CRC check the
decoder applies, so a damaged dictionary page in a seeded column had
its strings interned into the import's symbol file before the decoder
refused the page.  The header, the CRC check and the dictionary step
are now shared helpers that both paths call.

* fix(symgrp): read ahead through the last adopted record's bytes

The read-ahead span of an adopted run ended at the last record's length
prefix, so a last record crossing into the next page faulted cold.

* perf(stream): hash a string once on the STR to SYM path

The stream append hashed each string to 32 bits and an import domain
hashed it again to 64.  It now computes the 64-bit hash once and
truncates it in place for the other domain kinds.

* refactor(platform): one helper reads the process and thread I/O counters

The hash-index and parquet traces each parsed /proc/*/io and getrusage
themselves; they now share ray_io_counters.

* perf(symimp): count lookup statistics only under the import trace

The import dictionary counted probed slots and tag collisions on every
lookup and flushed them into one shared cache line per batch, though
only the RAY_CSV_TRACE line reads them.  The flag is read once at
create; without it the lookup loop has no counting.

* test(parquet): seeding accepts a dictionary page with a valid CRC

Only the damaged-page case was covered, so a seeding check that refused
every page carrying a CRC went unnoticed.  A file with valid CRCs now
has to import with its dictionaries seeded, and the damaged case checks
that seeding got past the row groups before the bad page.

* fix(parquet): keep a pool task's error message when the import fails

An error's message lives in the raising thread's buffer, so an import
that failed on a pool worker reported a bare `parquet` error.  The task
that fails first now notes its message, and the collector raises the
error again with it on the reporting thread.

* fix(stream): keep the STR to SYM hashes in the positions' stack space

Hashing once at 64 bits added a 64 KB array beside the 32 KB positions,
growing the append frame by 32 KB on pool workers.  The hashes and the
positions now share one buffer, as the positions are written only after
the batch is interned.

* fix(parquet): keep a worker's error message on read and aggregate scans

Reading a file and aggregating over a scan dispatch row groups to pool
workers, and a failure there reported a bare `parquet` error, as the
import did before.  Both collectors now note the failing task's message
and raise the reported error with it.  Errors past the reported one are
freed instead of leaked.

* test(parquet): two failing row groups report the lower one's message

With faults in two row groups, in either order, the direct, grouped
and parted imports must report the message of the lower row group.
* fix(compile): bind every capture when the capture walk gives up

A closure body nested past the symbol walk's 1024-level guard got NULL
capture names, which ray_compile read as "nothing captured": it compiled
without OP_BINDCAPS and the captured names resolved as globals.

A failed walk now binds every capture, as a body that uses eval does; if
that does not compile either, the lambda is marked not compilable and
stays on the tree walker.

* fix(eval): apply the generic null rule to unary builtins in OP_CALLF

A closure body resolves its builtins at call time and reaches them
through OP_CALLF, whose unary path lacked the null check OP_CALL1 and the
tree walker have: (count null) inside a closure returned 1 instead of a
type error.  The unary path now lets only nil?, type and ser take the
generic null, as the tree walker does.

* fix(eval): keep an eval window's locals from the functions its text calls

A compiled body binds its locals in a scope frame around `eval` and
`resolve` so the evaluated text can see them.  A named function called
from that text resolved its free names through the same frame:
(set p 100) (set rd (fn [] p)) ((fn [p] (eval (quote (rd)))) 1) gave 1.

The window is now marked (OP_SCOPE_EVAL).  Compiled code's run-time
lookups pass it by, as do the tree walker's once they cross a lambda
call's frame, so only the evaluated text itself sees the locals.

* fix(eval): bake a definition's builtins on its first call, not at evaluation

A literal evaluated at the top level shared a template compiled when it
was evaluated, with the builtins it names baked then: (set g sum)
(set f (fn [x] (g x))) (set g count) (f [1 2 3]) gave 6.  A function
reached through a dict was baked the same way, and the generation check
missed it, since rebinding a dict moves no counter: the same literal
evaluated after (set D ...) or (set D.f count) kept calling sum.

A lambda with nothing captured no longer takes a template: it compiles
on its first call and bakes its builtins then.  Templates now serve only
closures, whose bodies resolve their free names when they run, so a
shared template cannot go stale and the function generation counter,
whose only reader was the baked-template check, is removed.

* fix(query): read helper globals live when the expression has an effect

Inlining a named helper puts the current value of each global it reads
into the expansion, and a query evaluates that expansion once per group,
row or output.  When an effectful helper in the same expression sets the
global, the expansion no longer saw it: a grouped update gave
[21 24 27 ...] instead of [121 224 327 ...], and a row-wise (+ v G)
helper, an ungrouped update, a grouped select, a derived output and a
projection showed the same.

An expression is expanded only when the purity walk finds no effect in
it; otherwise it is evaluated as written and its helpers read their
globals when they run.  An effect-free expression is still expanded once
for every group.

* fix(query): follow let aliases and map/fold over pure helpers in the purity walk

The walk that decides whether an opaque by: key may run over the whole
column recorded a `let` only when it bound a lambda literal.  After
(let g hk), a call (g v) looked up a global g, found none and counted as
an effect, so a pure key ran row by row: [6] instead of [3 3], and 750 ms
instead of 50 ms over 1M rows.  A map or fold over a list of pure
helpers was rejected the same way, since the literal's parameter was an
unknown callee.

Every `let` now binds in the walk: a literal, an alias resolved with the
bindings in scope at the `let`, or a computed value.  Parameters and lets
share one binding stack searched newest first, so a let rebinding a
parameter shadows it, and each binding resolves in the context where it
was written.  A let in a branch may not have run, so what the name meant
before it counts too.  map, pmap, fold and scan with a lambda literal
bind its parameters to pure callables when every other argument's
callables are known to be pure (fold and scan pass an unknown
accumulator first).

* fix(eval): bound the closure template table by bytes

The table that shares compiled templates between closures of one literal
keeps the literal's text alive after its closures are gone, and was
bounded by the vector elements the text holds.  A string atom weighed
nothing, so 300 literals each holding a 1.3 MB string kept 537 MB; 256
literals just under the element bound could pin about 128 MB.

A literal now weighs the bytes its text holds: every node's header and
payload, string characters and a slice's parent included.  One holding
more than 64 KB is not kept, and the table as a whole stays within 1 MB,
older entries making room for newer ones.

* perf(eval): resolve a closure body's builtins without scanning the globals

A closure body resolves every builtin it names when it runs: OP_RESOLVE
walked the scope frames and then scanned the global table, a few hundred
names, and the call went through OP_CALLF's general dispatch.  A
4-builtin closure mapped over 1M rows took 38% longer than the same
named function, a closure while loop 16% longer.

A per-thread hint remembers where a global was found and is checked
against that slot on use, so a rebinding, a new name or a deletion that
shifts the table is seen at once.  With no scope frame on the stack,
compiled code takes the global straight from it.  The call site emits
OP_CALL1R, OP_CALL2R or OP_CALLNR for a builtin of the kind the name
held at compile time; each runs the fast call while the name still holds
such a builtin and joins OP_CALLF's general call otherwise.

* test: pin the compile-failure mark, the binary call's row flag and per-call DAG retries

Each of these could be reverted with no test failing:

- ray_compile marks a body that does not compile (NLOCALS -1), and a
  lambda so marked is never compiled again;
- a binary builtin reached through the VM's general call, or a closure
  body's resolved one, reports its result's row provenance, so a second
  concat over it still joins text row by row;
- the grouped update asks the planner again for every expression of
  every call, so an expression it declined does not send a later output
  or a later update to the interpreter, whose error would replace the
  planner's schema error.

* fix(compile): look builtins up past an eval window when compiling a definition

A named function compiles on its first call and bakes the builtins it
names then.  When that first call came from text evaluated by `eval` in
a compiled body, the head lookup saw the window binding the caller's
locals: (set rd (fn [x] (count x))) ((fn [count] (eval (quote (rd
[1 2 3])))) sum) baked sum, and rd kept returning 6.

The compiler's head lookup passes an eval window by, as compiled code's
run-time lookups do.

* perf(eval): keep the resolved-builtin calls out of the VM's shared state

OP_CALL1R/OP_CALL2R/OP_CALLNR shared two variables with the rest of the
dispatch loop to join OP_CALLF and to apply ser's null rule; the extra
live state cost the whole loop about 5% (fib 15 per row over 1K rows:
442 ms before, 476 after).  Each now carries its argument count as an
operand, so the fallback jumps to OP_CALLF itself, and a generic null
argument takes that general call, which already applies the tree
walker's null rule.

* fix(query): purity walk sees loop lets, try bodies, shadowed map and functions in data

The walk that decides whether a by: key runs whole and whether a helper
may be inlined called several effectful shapes pure:

- a `let` in a times or while body rebinding a name called earlier in
  the body: the next iteration calls the new value;
- a `let` in a try body after a raise, which never runs;
- map or fold shadowed by a let, a parameter or a capture, which still
  took the builtin's shortcut;
- a function reached through a dotted name (D.a), or taken out of a dict
  or a list (at D 'a), passed to map or fold.

A name rebound by a `let` anywhere in a loop is now marked before the
loop is walked, so any call through it, in the loop or after it, is an
effect.  Every `let` in a try body is conditional.  The map/fold
shortcut applies only when the name means the global builtin.  A dotted
name resolves through its dict, and a list or a dict used as a value is
pure only if every function in it, or named by a symbol in it, is.

Each also hid an effect from the inlining gate, so a grouped update
evaluated a helper's global once for every group again.

* fix(eval): end an eval window's scope at the window, at every depth

A compiled frame binds its locals in a window around text it hands to
the tree walker, and code that text calls passes the window by.  One
level down it did not:

- a callee with no locals opened no window for its own eval or resolve,
  so its text found the caller's window: (set b0 (fn [] (eval (quote
  (+ a 0))))) ((fn [a] (eval (quote (b0)))) 1) gave 1, not the global;
- a callee with locals opened one, but a lookup that missed in it went
  on into the caller's window below;
- a callee's query, or a fn literal it could not compile, went to the
  tree walker with no window at all when it mentioned no local;
- the planner, inlining a helper called from a query in eval text,
  resolved the helper's free names and callees through the window:
  (select {r: (hp x) ...}) in text evaluated with a local p gave
  [2 3 4] where hp reads the global p.

Every window compiled code opens is now marked (OP_SCOPE_EVAL), also
around a dynamic special form or a fn literal that mentions no local,
and also when the frame has no locals.  A lookup that passes a window
skips every window below it, a closure made in the text captures no
further than its window, and the planner looks a helper body's names
up past every window.  The flags are reset when a frame is pushed, so
the pop no longer clears them.

* fix(eval): weigh table and lambda constants in a template's literal

The template table's byte bound counted a node's header and payload but
did not enter a table or a lambda spliced into the text as a constant:
300 closures whose literals each held a 50k-row table kept 133 MB after
they were released.

A table or a lambda in the text now weighs everything it holds: a
table's columns, a lambda's parameters, body and captures.  Tests pin
each part of the count: tables, lambdas, a slice's parent and a string
vector's characters.

* test: pin OP_CALL2R's reading of unknown row provenance

A closure body's resolved binary builtin passes only row data (flag 1)
on as row data; a local an eval rebound (flag 2, unknown) reaching it
through a row-wise builtin left concat joining text row by row, unlike
the same body in a named helper.  Reverting the normalisation fails
this.

* perf(eval): share a definition's bytecode when its baked builtins still hold

A lambda with nothing captured compiles on its first call so that it
bakes the builtins its call heads name then.  Each lambda of a literal
evaluated over and over at the top level compiled again: 100k one-shot
lambdas took 250 ms against 57 ms when they shared a template.

The compiler now records the call heads it looked up and the builtin
each named (or none).  A lambda's first call reuses the bytecode another
lambda of the same literal compiled while every head still names what
it named then, which is the code a fresh compile would produce; a head
rebound in between, through a dict too, compiles the literal afresh.

* fix(query): purity walk reads data as pure, checks the function a builtin calls

0a186fa made a key that only reads a list or a dict walk every element
for a function with an effect, and every symbol in it for an effectful
global, giving up past 4096 elements.  A pure key over large ordinary
data then ran row by row: (in s S5K) over 5000 symbols at 200k rows took
92 ms against 0.4 ms, and even counting ['bump 'a 'b] flipped the
verdict.  It also missed a function held in a table cell, which LIST
columns, list cells and dict cells can hold: (map (first (at TF 'f))
(enlist v)) called an effectful function on a whole-column key.

Reading data is pure again, whatever it holds.  A function taken out of
data is caught where it is called: a computed callee was already an
effect, and the function argument of map, fold, scan, pmap, apply and
the like must now be a literal or a name bound to a known-pure lambda or
builtin; anything computed counts as an effect.

* fix(compile): stop a constant's byte count at the template bound

e0f2e7e walked a table or a lambda in a literal's text with a cap of
2^40 bytes, and shared children were walked again each time they were
reached: a table whose 20000 cells share one 2000-element list cost
228 ms per new lambda, a list shared 2^27 times over 2.4 s.

The count now gets the room left under the template bound and stops as
soon as it passes it, at every level, so its work is bounded by the
bound whatever the value's shape.  That bounds the recursion depth too,
since every level adds a header, so the separate depth cap of 64 is
gone.

* test: a closure of a definition's literal never takes the baked bytecode

The closure template search skips definition entries.  Without the skip,
a closure whose captures its body does not mention matched the entry a
definition of the same text left behind, and ran bytecode with the
builtins the definition baked instead of resolving them when it runs.

* refactor(eval): OP_CALL2R runs OP_CALL2 once the callee is a binary builtin

OP_CALL2R kept its own copy of OP_CALL2 that turned the operands' row
flags into 0 or 1 before the call and the result's after it.  Both
together read an unknown flag exactly as OP_CALL2 does, since the call
compares the flags with 1 and the normalised result can only be 0 or 1;
the hunk changed nothing, so 16e5dd7's note that reverting it fails its
test was wrong: that test fails only when the two normalisations are
split.  OP_CALL2R now checks the callee and jumps to OP_CALL2, and the
test pins that a closure body and a named helper agree.

* perf(eval): give OP_CALL2R its own copy of OP_CALL2's body

d96521c had OP_CALL2R jump into OP_CALL2.  The code is the same, but
the change in the dispatch loop's layout made an F64 > I64 comparison
over 1M rows 30% slower in every build tried (46 ms to 62 ms, at the top
level and in a lambda alike).  OP_CALL2R again holds its own body, now
identical to OP_CALL2's: the same rows in and out as a baked call.

* fix(query): purity walk checks every argument a builtin calls, and try's handler

The check on a function argument covered map, pmap, fold, scan, prior,
apply, fold-right, scan-right, map-left and map-right by name, and only
their first argument.  fold-left and scan-left were missing,
fold-while's step function (its second argument) was not checked, and a
builtin reached through another name was not checked at all:
(fold-left (at D 'b) 0 (enlist v)) ran an effectful function on a
whole-column key.  try's handler, which try calls when it is a function,
was not checked either: (try (raise "x") (at D 'a)).

The builtins are now a table keyed by the C function behind them, with
the argument positions each calls, and a call head is resolved through
let aliases, parameters, captures and globals to the builtins it can
mean, so every name bound to one is covered.  A try handler that is not
a function literal, a literal fallback value or a name known pure is a
computed callee, an effect.

* perf(compile): stop the template's symbol walk at the bound, skip quoted text

The walk that lists a literal's symbols for the template table went on
through text the table would not keep, and through quoted text: a
closure literal quoting a list shared 2^22 times over cost 145 ms on its
first call, against 87 ms on dev.

The walk for the table now stops once the literal weighs more than the
table keeps.  Quoted text is weighed, bounded, and not walked for names
by any of the walks: a name in it reaches nothing unless eval or
resolve evaluates it, and either already makes every capture count.
The same literal now costs 36 ms.

* perf(eval): start the bytecode dispatch loop on a page boundary

The VM's speed moved with code it does not run.  ff7f4f3 and fb8eba8
change only the query planner's purity walk and the compiler's symbol
walk, and leave the bytecode the same, yet together they moved
vm_exec_rows by 896 bytes, and every VM-bound shape got 5-10% slower:
fib 24 by name 37.8 to 40.6 ms, a named while loop over 1M 384 to 399
ms, a closure while loop 425 to 451 ms.  Each change alone, or both
with 3200 bytes of padding added ahead of eval.o, left the loop at its
earlier speed.

vm_exec_rows is now aligned to 4096 bytes, so its handlers keep their
place relative to fetch and branch-predictor boundaries whatever comes
before it.  The shapes above return to 38.0, 373 and 418 ms.

* fix(query): a builtin that calls its arguments is not a known-pure value

The map/fold shortcut binds a literal's parameters as pure callables
when every element it is handed is pure, and map, fold-left and the
other builtins that call an argument counted as pure.  Called through
such a parameter with a computed function, they escaped the argument
check: (map (fn [f] (f (at D 'a) (enlist v))) (list map)) ran an
effectful function on a whole-column key, where dev ran it per row; a
grouped update inlined its helpers the same way.

As a value, such a builtin is no longer known pure, so the shortcut does
not apply and the literal's call through its parameter is an effect.  A
lambda object spliced into the text as try's handler is walked as the
function try calls, not taken for a fallback value.

* perf(eval): guard the dispatch loop's alignment, state its measured effect

The 4096-byte alignment of vm_exec_rows is a GCC/Clang attribute; it is
now applied only by compilers that accept it.

b0736e3 stated a 5-10% slowdown on VM-bound shapes from an unrelated
896-byte shift.  That was one machine.  An independent measurement saw
under 2% on fib by name, the named while loop and the closure while
loop, and 4-6% only on the 5-statement closure and named-function maps.
The comment now gives both.

* fix(query): purity walk, planner and inliner follow bindings, not spellings

Review of #777 found the purity walk trusting how a head is spelled:

- `(list x)` and `(enlist x)` passed as pure constructors whatever list
  and enlist were bound to, so the map/fold shortcut took an effectful
  local list for the builtin;
- the check of a function argument returned the newest binding of a
  name, so a `let` in a branch hid an effectful earlier one.

The same class showed up elsewhere and is fixed with them: a parameter
or local spelled like a special form (if, do, quote, fn, ...) was walked
as the form; println or show bound to another name passed as pure, since
the impurity list was looked up by the name used; the inliner took any
builtin bound to a pure builtin's name as that builtin, and treated a
call through a helper's formal named quote or if as the form, as did
the planner for a formal or a caller's local of that name:
(select {r: (hq neg v) ...}) with hq (fn [quote x] (quote x)) gave
[x x x].

The list constructors are now recognised by the builtin the head
resolves to, through every binding that can reach it; a conditional
binding requires every earlier one to be pure as well, as the name walk
already did; a form is a form only when its name is not bound; a
builtin's purity is decided by its own name; the shortcut also walks
the call's arguments; and the planner and the inliner decline a call
whose head is a bound value.

* fix(compile): keep (quote x) a call when quote is a local

fb8eba8 skipped the contents of every call spelled quote when listing
the names a closure body mentions.  With quote a parameter or a capture
the call is a call through it, and its argument dropped out of the
capture set: (set mk (fn [quote x] (fn [] (quote x)))) made ((mk inc 41))
return the symbol x instead of 42.

Quoted text is skipped only while quote is the special form: not when a
parameter or capture of the lambda is named quote, and not when the
name appears anywhere else in the text (a let, a nested parameter, a
value), in which case the walk is redone over every node.

* fix(compile): walk quoted text for a closure's names, bounded by weight

A global quote set to a function makes (quote x) a call through it, and
fb8eba8's skip of quoted text still dropped x from a closure's capture
set: (set quote (fn [x] (* x 100))) then ((mkq 3)) with mkq
(fn [x] (fn [] (quote x))) raised a name error, where dev and pre-744
give 300.  5d91737 only covered quote bound as a parameter or capture,
and a skip keyed on the global binding would go stale for templates
compiled before a later rebinding.

The skip is gone.  Instead every walk for a closure's names stops once
the text weighs more than the template bound, and the closure then binds
every capture, as for a body nested past the walk's guard; a template
literal that heavy falls back to evaluating the literal.  The closure
that quotes a list shared 2^22 times over costs 40 ms on its first call
(dev 90 ms, 35 ms with the skip).

* fix(query): purity walk reads a globally set quote, cond, and, or as a call

The walk took (quote v) as quoted text even with quote set globally to
a function, which compiled code then calls: an effectful quote passed
on a whole-column key.  A form name not wired into the compiler (quote,
cond, and, or, raise) is now the form only while its global is a
builtin.  do, fn, if, let, return, times, try, while and self stay the
forms whatever their global binding, as the compiler treats them.

* perf(compile): bound the walk for a closure's names by nodes, not bytes

98dc0b2 stopped the walk for a closure's names once the text weighed
more than the template bound, and the closure then bound every capture
in scope.  A closure whose text holds one 66 KB string constant was one
node away from a precise answer, yet bound all 200 bindings in scope and
paid for them on every call: 249 ms per 100k calls against 50 ms on dev.

The walk now stops after 65536 nodes.  A large constant is one node, so
only text shared over and over (the 2^22-fold quoted list, 41 ms on its
first call) falls back to binding every capture.

* perf(env): cache a compiled body's run-time name lookups per thread

A closure body resolves the builtins it names on every call.  With a
scope frame on the stack (a closure made and called inside a top-level
do with a let) each lookup took the general walk: a fn literal made and
called 100k times there ran 9-11% slower than on dev, which baked the
builtins into a shared template.  Baking is what made a rebinding after
the closure was made go unseen (43ceb32), so the lookup stays.

A lookup through plain frames now scans them inline, and its answer is
cached per thread under two epochs: this thread's frames (a pop, a
binding, a change of a frame's kind or flags moves it) and the globals
(any write moves it).  While neither moves, the frames and globals the
answer was read from hold the same values, so the cached value is still
the binding and alive.

* perf(eval): read the resolve cache inline in OP_RESOLVE

564e781's cache still cost a call into env.c per lookup.  OP_RESOLVE
now checks the entry itself and calls ray_env_resolve_compiled only on a
miss.  The fn literal made and called 100k times inside a top-level do
with a let: 63.3 ms, as on dev (65.7 before); a closure mapped over 1M
with 4 builtins 471 to 444 ms.
…l pages (#778)

* fix(heap): relieve memory only on evidence of a spill, park empty pools

The statement-boundary relief unmapped every empty pool whenever the next
pool would not fit under the anonymous watermark.  A statement that ran
near the watermark without spilling then mapped and faulted its pools
again at every boundary, and empty spill pools went with them, so a
statement that spilled again created and refaulted its spill files anew.

The boundary now acts on what the statement did.  After a spill — a pool,
direct or sys block that went past RAM — the empty anonymous pools of the
heaps that did not spill are unmapped, with the direct-block cache and the
pages of their other free blocks, when that brings the next pool under
the watermark; the heap that spilled keeps its pools.  A relief followed
by another spill into pools only is futile, and none follows until a
statement maps without spilling or the watermark moves; a statement that
needed a relief's room for large blocks relieves again.  Otherwise, near
the watermark, empty pools are parked: off the freelists, mapped, and
taken back before a new pool is mapped.  A large block about to cross the
watermark first takes the room of its own heap's empty anonymous pools.

Empty spill pools are parked too and kept for the next statement that
spills.  They are unmapped when the relief acts, from every heap it
visits, when unused for the idle decay's threshold, and when their heap
is abandoned.  A boundary far from the watermark visits the heaps for
them at most every 100 ms.

* fix(heap): open spill files close-on-exec

The files behind spill pools and spilled direct and sys blocks were
opened without O_CLOEXEC.  A child started with .sys.exec inherited
their descriptors and kept the unlinked files — and their dirty pages,
written back for nothing — alive for as long as it ran, after the parent
had unmapped them.  All three opens now pass O_CLOEXEC.

* fix(heap): discard the pages of parked spill pools at the boundary

An empty spill pool parked for the next statement kept its pages: dead
data whose dirty pages the kernel wrote back for nothing, and whose page
cache held RAM the cgroup could not reclaim before writeback — in a small
memory limit, enough for the next statement's anonymous growth to be
OOM-killed.

At the boundary that parks it, a spill pool's pages from its second page
to its last resident one (mincore) are punched out of the file, the dirty
ones dropped unwritten, and the range is reserved again so a later store
still has its disk block.  The file and the mapping stay for the next
statement that spills, whose pages are zero-filled anew.  A pool is
discarded once per use: a boundary after a statement that spilled
nothing makes no call.  Where a mapped range cannot be punched — no
FALLOC_FL_PUNCH_HOLE, macOS, or a file system or disk that refuses — the
pool is unmapped instead.  ray_heap_set_spill_discard(false) forces that
path for tests.

After spill pages are dropped, memory.stat is read once
(ray_os_mem_used, on the limiting cgroup's directory, else
/proc/meminfo) to flush the cgroup's statistics, which the kernel
otherwise updates lazily: the dropped dirty pages would throttle the next
writes as if they were still there.

* refactor(heap): flush cgroup statistics without computing memory in use

After spill pages are dropped, the boundary read the RAM in use only for
the side effect of reading memory.stat, which flushes the cgroup's
statistics.  The figure itself was never used, and outside a limiting
cgroup every such boundary opened and parsed /proc/meminfo for nothing.

ray_os_cgroup_stat_flush reads the cgroup's memory.stat and nothing else;
ray_sys_mem_flush calls it when a limiting cgroup is known and does
nothing otherwise.  The v1/v2/meminfo arithmetic and its test go.

* test(heap): relief tests hold where spill pages cannot be discarded

Six relief tests took a parked spill pool's survival for granted.  Where
a mapped range cannot be punched — macOS, or a kernel without
FALLOC_FL_PUNCH_HOLE — the boundary unmaps the pool instead, and those
tests failed on what was the intended behaviour there.

ray_heap_spill_discards() says which way the boundary goes, from the
same check heap_spill_discard makes, and ray_heap_set_spill_discard()
now returns the setting it replaced.  Each of the six tests asserts the
unmapping where discarding is off, and runs a second time with the
discard forced off (heap/relieve_*_unmap), so that path is checked on
every platform.  The fallback test also pins discarding on by default.

* test(heap): a parked spill pool is discarded once per use

Nothing checked that a pool is marked discarded: without the mark every
later boundary set out to discard each parked spill pool again, a
mincore per pool per boundary, and no test noticed.

ray_heap_spill_discard_count() counts the pools a boundary sets out to
discard; heap/relieve_spill_discard asserts that a second boundary over
the same parked pool adds none.

* test(heap): the close-on-exec test covers spilled off-heap blocks

heap/relieve_spill_cloexec mapped a spill pool and a spilled direct
block but no spilled sys block, so the raysys_ file never appeared in it.
It now also maps an off-heap block past the watermark and counts raysys_
files with the others.  That file is closed as soon as it is mapped, so
only a fork racing that window could inherit it; the test pins that no
child does.

* test(heap): keep the inotify reader inside the Linux-only test

The helper that counts cgroup file reads used struct inotify_event
outside the Linux guard, so the test file did not build on macOS.

* test(heap): keep Linux-only test helpers inside the Linux guard

Three helpers used only by Linux-only tests were compiled everywhere, so
the macOS debug build failed on unused static functions.

* test(heap): keep the cgroup file writer inside the Linux guard

Its only caller is the Linux-only cgroup fixture, so the macOS debug build failed on an unused static function.

* fix(heap): seed the next statement's peak after the boundary reclaims

A boundary reset the statement peak to the footprint it found, before
its relief drained the direct-block cache and unmapped pools.  The next
statement then started from that higher footprint: right after a relief
that took other heaps' pools, a light statement that mapped a large
block and a pool looked as if it had run up to the watermark, was taken
to have needed the relief, and its boundary unmapped pools it would have
reused.

The completed statement's peak is still sampled first; the next one's
is seeded once the boundary has reclaimed, from the footprint it leaves.
heap/relieve_needed_baseline covers the case.

* test(heap): a statement's relief is judged by its peak, not its end

Nothing told a statement's high-water footprint from the one it ended
with: had the boundary judged whether a statement needed a relief by its
end footprint, every relief test still passed.

heap/relieve_needed_peak runs a statement right after a relief that took
the workers' pools: it maps a large block up near the watermark, frees
it before its boundary and ends far below.  Judged by its peak it needed
the relief, and its boundary hands back the pool it left empty.

* test(heap): give the stale-baseline test room with one pool worker

heap/relieve_needed_baseline needs the relief to free more than a pool
and a half so its light statement — a 40 MB block and a pool — ends a
pool clear of the watermark.  With one worker the relief freed a single
pool, the fixture could not hold, and the test failed under
RAYFORCE_CORES=1.

The worker tasks can now leave several empty pools each, and the test
asks for at least two across however many workers there are.
* perf(store): reuse unchanged partitions across parted mounts

Mapping a STR column rehashed every pooled string and stored the hash
into every descriptor of the private mapping, so each map cost a pass
over the pool and a private copy of the descriptor pages.  Writers now
store the content hash in every pooled descriptor and mark the header;
readers take marked descriptors as written and repair only legacy files,
writing only a descriptor whose value is wrong.

.db.parted.get opened every partition from scratch on every call.  Loaded
partition tables are now kept keyed by path and reused while the resolved
generation directory and the identity, size and mtime of the schema and
column files are unchanged; changed partitions reload, vanished ones are
dropped.  The heap gained a teardown callback so the cache releases a
heap's tables before its pools are unmapped.

* fix(store): bound partition reuse to thread and view lifetimes

* test(store): use POSIX stat timestamps on macOS

* test(store): read Darwin POSIX timestamp components
* fix(store): prune unused partition domains before symbol opens

* test(store): preserve live partitions across domain opens
pf_sink in test/test_pool.c is only ever added to, so recent clang
(-Wunused-but-set-global, on by -Wall, made fatal by -Werror) rejects
the file.  gcc does not warn, which is why CI and a default `make test`
(CC defaults to cc, i.e. gcc on Linux) never saw it.  Read it once at
the end of test_scan_read_ahead.

Co-authored-by: Claude Opus 5.5 <[email protected]>
…sion aggregate (#760)

* fix(query): a multi-key select with a distinct count beside an expression aggregate (#756)

A select grouped by two or more keys failed with `name` when it held a
`(count (distinct x))` beside an aggregate over an expression, such as
`(sum (if (== st 'bad) 1 0))`.  The distinct count is not a DAG aggregate,
so with more than one key the select fell to the eval-level grouping,
which evaluated an aggregate's argument with no column in scope — and
which is serial, 8x slower than the parallel path for the shapes that did
not fail.

The eval-level grouping now evaluates an aggregate's argument over the
selected rows with the columns bound, as a row-wise projection
(group_key_eval), since the eval-level `if` is scalar.

A plain multi-key by: stays on the DAG path when the outputs the DAG
cannot serve are distinct counts and literal broadcasts: the post-group
scatter maps rows to groups through the composite key (rgid_build_multikey,
a parallel tuple probe that applies the selection), and the existing
per-group kernels serve the distinct counts.

Two shapes the issue's workarounds exposed go the same way.  An aggregate
over an `if` dropped the group onto the legacy engine, 6x slower under a
where: selection: the v2 expression bridge now materializes an input the
element-wise compiler declines through the DAG executor.  A distinct count
alone took the two-pass rewrite — group by (keys, value), then count —
which is a radix grouping of every tuple when that composite is not dense
(1.8 GB and 3x the time at 10 M rows with 45 groups of 3 M values); the
rewrite is now gated on a sampled estimate of the group and value counts
(agg_group_card_estimate) and the select otherwise groups by the keys and
counts over the slices.

Closes #756.

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

* fix(query): guard the distinct-count gate's division for static analysis

* fix(query): -0.0 keys in the distinct-count probe, a sampled gate, by-dict aliases

Review round on #760.

- The row→group probe (key_read_i64, KEY_READ) reads an F32/F64 key's
  -0.0 as +0.0, as the grouping does (group_key_f64_bits, #407).  A -0.0
  row missed the merged zero group and was dropped from every per-group
  kernel — n fell to 0 beside a right count — on the single-key path
  before, and on the composite path since 7c17cf7.
- agg_group_card_estimate samples 65,536 rows at a fixed stride (the
  description's claim; the code read 64 blocks of 1,024) and raises the
  sample's distinct count by the Chao1 estimator from the values seen
  once and twice, capped at the sampled span for an integer key and the
  domain count for a SYM key.  Skewed and clustered keys estimated low
  before, so the gate took the slice dedup where the rewrite is 2–4x
  faster: a single-key where: count-distinct over a skewed SYM key ran
  405 ms against 99; it is 45 ms now.  The set is sized to the sample,
  so a 10-row select plans in 4 µs, not 80.
- The gate no longer prefers the rewrite under fewer groups than
  workers.  At 2 to 9 groups of 3 M to 6 M values on 28 workers the
  slice dedup takes the same time or less at 40% of the memory, and the
  issue's 45 groups at -c 46 take 42 ms / 512 MB against the rewrite's
  89 ms / 1375 MB.
- The two-pass rewrite keeps a by-dict's aliases, so `{a: k1 b: k2}`
  names its columns a, b on every route; it declines an alias naming
  another input column, as the by-dict materialization does.
- ray_execute resets the pool's cancel flag at the outermost call only:
  the grouped expression bridge's nested execution would have dropped a
  cancel that arrived before it, and the workers would have run the
  remaining tickets.

Tests: -0.0 keys through the probe (F64, F32, one key and a composite,
where:, the distinct count alone); a 60 K-group composite under where:,
where the probe's selection feeds the global-hash kernel; aliases on
both routes, with desc:/take: and where:.  Each fails with its fix
reverted.  Full ASan/UBSan suite 4,111 of 4,111.

* fix(query): where: stays alias-blind to a by-dict's keys

`(select {from: T by: {a: k1} where: (!= k1 'a) n: (count v)})` returned
no rows.  The eager by-dict path adds each alias as a column of the
table the rest of the select is compiled over, and a literal symbol
naming a from-table column resolves to that column (B3 Part 2), so `'a`
read the new alias column and the filter compared k1 with itself.  The
two-pass distinct-count rewrite and the deferred parted route add no
column and kept the symbol, so the same where: meant different things
on different routes.

where: names source columns only, like by: and the sort keys.  Before
the aliases are added, every literal in it naming an alias the table
does not already hold is wrapped in `(quote …)` — the compiler folds a
quote call to the symbol; only the tick atom takes the column rule — and
the select runs again over the rewritten dict, as the materialized
fallback does.  Outputs are untouched: a literal naming an earlier
projection resolves to it by design.

Tests in literal_col_ref.rfl: the alias as a quoted literal in where:
with count, sum, asc:/desc:/take:, two aliases, the rewrite route for
comparison, a vector literal and a source-column literal (both
unchanged), and a trivial self-alias.  They fail with the wrap disabled.
Full ASan/UBSan suite 4,111 of 4,111.

* fix(query): guard the cardinality estimate's division for static analysis

* test(query): the composite select's columns in declaration order, as #744 orders grouped outputs

* fix(group): F32 keys through the shared column reader

read_col_i64 had no F32 arm, so an F32 group key fell to its one-byte
default: the parallel group hash table's builders hashed and stored a byte
of each key, and a multi-core group by an F32 column over more than a
morsel of rows emitted garbage keys and split or merged groups — on a
plain count, on a distinct count beside the key, and for a composite key
with an F32 member once #760's probe admitted F32.  The reader now decodes
the 4-byte lane, with -0.0 canonicalised to +0.0 as the F64 key readers
do, and write_col_i64 stores it back.  F32 stays off the packed-key
whitelist: a packed region is raw bit identity, as for F64.

test/rfl/query/group_f32_key.rfl runs 100 K rows through every shape at
the suite's two workers; its first assertion fails without the arm.

* fix(query): the fused kernel's alias, from: evaluated once, a dead decline

The fused single-key distinct-count kernel named its key by the source
column (K_syms[0]) where every other route names a by-dict's key by its
alias, so `{g: k1}` came out as `k1` from 262,144 rows with workers and
as `g` below.  The where: shield's re-run took the from: expression, so
`(do (set C (+ C 1)) T)` ran twice; it now takes the table from: evaluated
to.  The rewrite's decline of an alias equal to the count's name changed
nothing on any route — the key comes out under the name first and the
count second everywhere — and is removed; the output is pinned instead,
with the duplicate-alias error on the rewrite's route.

* perf(query): the distinct-count gate reads the key and (key, value) tuples

agg_group_card_sample replaces the estimator's body: one strided pass
over the columns, prefetched, 32,768 rows, one row per window at a hashed
offset (a fixed position read a key whose period divides the stride as one
value), that also hashes the key tuple and the (key, value) tuple into two
more sets — the groups a composite forms, which the product of its
columns overstates, and the tuples the rewrite's (K, X) pass would keep.
A sorted prefix defeats a stride, so when the sampled tuples never
decrease, blocks of adjacent rows are read as well and the lower reading
stands.  Planning costs 0.6 ms of 10.5 on the dense 2-key shape at 10 M
rows, from 1.8.

The gate keeps its rules — dense (K, X) → rewrite; up to 256 K groups
otherwise → slice dedup; past 1 M groups → rewrite — and between 256 K
and 1 M groups asks the tuple estimate: the rewrite when its (K, X) pass
dedups, the slice dedup when the tuples are nearly the rows.  A sorted
750 K × 20 composite now takes the slice dedup at 138 ms / 849 MB against
the rewrite's 175 / 1596 (15 M rows, 28 workers); the other measured
shapes route as before.

test_agg_contract.c's card_estimate pins the Chao1 correction, the span
and domain caps, the tuple against the product, and the blocks on a
sorted prefix; each fails with its hunk reverted.

* fix(agg): the estimator samples each window at a hashed offset, caps SYM at its codes' span

The sampled row of window i was i * stride plus the high bits of i times
the golden ratio modulo the stride, an offset nearly linear in i: the
sampled rows stayed an arithmetic progression, and a key whose period is
near the stride was read at a nearly fixed phase.  At 10 M rows the
(k1, k2, x) tuples of (% i 1000), (% i 1009) and (% i 50) estimated at
ten million (1,009,000 true; no tuple seen twice) and the groups of
(% i 1000), (% i 1013) at 106,015 (1,013,000 true; too many seen twice),
so the gate sent the usual periodic test data to the slice dedup at
twice the rewrite's time.  The offset is now the splitmix64 finaliser of
i: the collisions are a random sample's, and both land within an eighth
of the count.

A SYM key's cap was the process-wide domain's count, which grows with
every symbol interned and moved the estimate with it.  It is now the
span of the sampled codes, as for an integer key: fixed once the
column's symbols are interned, and never above the domain's count.

card_estimate pins the tuple cap (2,002 tuples against a Chao1 of
500,502), a key whose period equals the stride (32; 1 at a fixed
offset), the two periodic composites at 10 M rows, the permutation
(i x 7919) mod N, and the SYM estimate before and after another symbol
is interned.  Each fails with its hunk reverted.

Refs #756, #760.

* test(query): the distinct-count route gate under test

cd_two_pass_preferred moves from query.c into cdfuse.c as
ray_cd_two_pass_preferred, declared in cdfuse.h beside the fused kernel
it routes around, so the contract tests can call it.  agg_contract/
cd_route turns each rule on by itself: the dense check (45 x 100 takes
the rewrite, 45 x a million the slices), the 256 K floor (100 K groups
whose tuples would dedup to a fifth take the slices), the band (524,288
groups of 19 rows: tuples a twentieth of the rows take the rewrite,
every row distinct the slices; both again over a sorted key read through
the blocks; the periodic 1000 x 1009 composite takes the rewrite), the
million-group rule, and the two declines (an F64 key takes the rewrite,
an F64 value the slices).  Removing the dense check, the floor or the
million-group rule, or pinning the band either way, fails the test.

Refs #756, #760.

* fix(query): the distinct-count gate sees the rows a where: keeps and the largest group

On the published 100 M-row dataset, a distinct count of users by phone
model behind `(!= MobilePhoneModel "")` took the slices at 2x the
rewrite's time, and the two-key form the same.  The gate estimated over
the whole table, where the empty model is the dominant value; the filter
keeps 5.56 M rows, and of those one model holds 5.1 M.  The slice dedup
(cdpg_buf_par_fn) runs one group per task, so that group ran on one
worker while the rewrite's (K, X) pass spread every row.

The gate now samples the predicate: 262,144 table rows at the
estimator's hashed stride, the columns the predicate names gathered from
them (typed loads with reads in flight; a byte-wise copy took 25 ms) into
a table of that size, the predicate run over it as the select runs it,
and the survivors handed to the estimator with the population they stand
for (query_cd_gate_where_rows; 2.4-2.9 ms at 100 M rows).  Running the
predicate in full cost 18 ms of a 90 ms select whenever the slices were
then chosen and evaluated it again.  A predicate naming a text, nested or
parted column, or keeping every sampled row, leaves the gate on the whole
table.

The estimator takes the row list and its population, keeps a count per
sampled value and reports the largest group's rows; a group holding more
than CD_SCATTER_SKEW (8) workers' shares of the rows takes the rewrite.
Synthetic 100 M rows with 12 M surviving a filter, 28 workers: a value on
half the rows took 180 ms on the slices against 136 on the rewrite, one
on 8% of them 107 against 138, equal groups 89 against 140.  The real
queries: 51-52 ms from 99-108 (dev 48) and 58 from 101-103 (dev 55).

card_estimate pins the largest group's rows, a selection whose dominant
value is filtered, and a list standing for a population; cd_route the
dominant group on 28 and on 2 workers, the filtered key over the table
and over the survivors, and the sampled predicate itself.  Removing the
skew rule, ignoring the rows, the count or the population, or disabling
the predicate sample fails them.

Refs #756, #760.

* perf(query): confirm a sampled group count in full before the slices

A distinct count of users by search phrase behind `(!= SearchPhrase "")`
took the slices at 2x the rewrite's time: 6.02 M phrases over the 13.2 M
surviving rows, most on one row and a few on thousands.  The Chao1 takes
the phrases seen twice for the whole tail's repeats and lands in the low
hundreds of thousands, under the 256 K floor.

Before the slices are chosen on a count above the sample's size — any
larger count is the Chao1's correction, not the sample's evidence — the
key columns are counted approximately in full (ray_count_distinct_approx,
parallel, 12 ms at 100 M rows): a column past a million groups takes the
rewrite.  Over the whole table, an upper bound that errs towards the
rewrite.  The real query: 150-152 ms from 314-318 (dev 143-148).

cd_route pins a heavy-tailed key the Chao1 reads as ~100 K of 5 M values;
the test fails with the confirmation removed.

Refs #756, #760.

* fix(query): release the gate's sampled table, gather SYM at its width

The filter over the gate's sampled table returns that table retained,
as the rewrite's own where: pre-pass returns the source table, and
neither reference was released: every gated where: select kept its
262,144-row sample, a few MB per query on a long-running server.  Both
are released now.

A SYM predicate column was gathered into a 64-bit vector by its
narrower source width (a mapped table's columns are 8, 16 or 32-bit; an
in-memory one 64), so the predicate read packed codes and garbage, kept
every sampled row, and the gate fell back to the whole-table estimate.
The gather allocates at the source's width.

cd_route runs eight gate samples under the memory trace and holds
nothing afterwards (33.5 MB with the release reverted), and writes the
key at 32 bits over the same domain and checks the survivors against the
key's integer twin (no survivors list with the width reverted).

Refs #756, #760.

* perf(store): request many short page runs over the pool

ray_col_want_rows lists the runs of pages its rows touch and, from 256
of them, asks for them over the pool's threads instead of one request
at a time on the calling thread: a sparse sample of a large mapped
column marks one page per row, and each request costs a few
microseconds of the kernel's — 14,000 to 34,000 of them on the
distinct-count queries of the published 100 M-row dataset. Few or long
runs still go through ray_pool_want, which splits a long range itself.

* perf(query): the distinct-count gate asks for its pages before it reads them

Cold, the gate cost more than the select: the predicate sample read
262,144 rows a stride apart — every page of a 400 MB mapped column, one
page fault at a time on the main thread, 0.8–3.4 s — and the estimator
then read the key and value columns at the survivors, a fault each. The
select's own scan asks for its pages ahead through the pool, and the
other samplers do the same before their scattered reads; the round 3–4
estimator, the predicate sample and the full count did not.

- The predicate sample lists its rows and asks for their pages first
  (ray_col_want_rows: at this stride the column whole, in parallel), and
  gathers the rows over the pool's threads, one task per range.
- The estimator lists the rows it reads — the strided sample and the
  sorted-prefix blocks — and asks for them: the sampled rows' pages, or
  the column whole when the rows the estimate describes fall on every
  page of it (a row per page or more: the select reads it whole then,
  and the stream runs while the pass waits on its first pages).
- The full count asks for the key column whole before the parallel pass.
- ray_vm_willneed_bytes counts the bytes asked for at the one place
  requests are made, for the pool's trace summary and the test.

On the published 100 M-row dataset at 28 workers, first run after the
page cache is evicted: the phone-model query 1240 → 297 ms (dev 272),
the two-key one 1496 → 352 (317), the search phrase 1338 → 452 (378).
Warm the gate is 2 ms on the first two and 10 on the third, 6.7 of them
the full count.

Test cd_gate_read_ahead evicts a splayed table it writes and checks, for
the predicate sample, the estimate and the gate over a sparse selection,
that each asks for the bytes it reads and takes at most a handful of
major faults; each of four reverts fails on the bytes asked for.

* fix(query): release the filter result in the count-distinct rewrite

A lone (count (distinct x)) under a where: and a by: takes
try_count_distinct_v2_rewrite. Its where: branch ran the filter node and
kept the result, the input table with a reference of its own, releasing
it only on error. Each such query left one extra reference on its table,
so the table was never freed and the next insert into it copied every
column.

Release it once the filter has run. The constant node keeps the graph's
reference until ray_graph_free, and the group reads the rows from
g_in->selection.

Fixes #757

* perf(query): the gate asks for the span its sample covers, from the chunks the zone gate keeps

The estimator asked for the key and value columns whole whenever the
selection averaged a row per page, without looking at where the sampled
rows were: a 1% window of a time-ordered table pulled 92 MB where 2 was
needed. It now takes the first and last sampled row and asks for that
span as one range when the selection keeps a row per page of it or more,
and the sampled rows' pages otherwise.

The predicate sample read every page of the filter column. It is drawn
now from the chunks the select's own zone gate lets through
(scan_gate_where), so a slice of a sorted column samples its one or two
chunks — every row of them, the survivors and the population exact —
and the key and value columns follow through the span. A predicate the
gate says nothing about samples the whole table as before.

ray_col_want_rows splits its page runs over ray_pool_dispatch_n, a task
per 256 runs: the plain dispatch cut at 8,192 elements, so thousands of
runs stayed on one or a few tasks.

agg_est_sample_row took a whole-row stride, nrows / sample, and so read
sample * stride rows of a selection, the last fifth of 41,943 rows under
a sample of 32,768 unread; its windows are fractional now.

Test cd_gate_read_ahead gains the sorted-column window and the
contiguous-slice estimate; the sparse step moves to a 272 MB column. Seven
reverts each fail on the bytes asked for.

---------

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

A lone (count (distinct x)) under a where: and a by: takes
try_count_distinct_v2_rewrite. Its where: branch ran the filter node and
kept the result, the input table with a reference of its own, releasing
it only on error. Each such query left one extra reference on its table,
so the table was never freed and the next insert into it copied every
column.

Release it once the filter has run. The constant node keeps the graph's
reference until ray_graph_free, and the group reads the rows from
g_in->selection.

Fixes #757

Co-authored-by: Anton Kundenko <[email protected]>
belowzeroff and others added 26 commits October 30, 2026 20:17
fill, dyadic min and dyadic max over SYM, STR and GUID operands returned a
boxed LIST instead of a typed vector: (type (fill 'z (enlist 'a '))) and
(type (min (enlist 'b 'a) (enlist 'a 'c))) were 'LIST.

Cause: the atomic binary mapper packed only numeric, boolean and temporal
scalar results into typed vectors; wide cells stayed boxed.

Fix: after mapping fill/min/max, a result whose cells are all SYM, all STR
or all GUID atoms collapses into the matching typed vector. Mixed-type
LIST operands keep their boxed shape.

Behaviour versus dev: only the result type of these three operations on
homogeneous wide operands changes; empty and mixed inputs answer as before.

Tests: collection/wide_atomic_results.

Fixes #977
`(as 'GUID v)` on a non-empty GUID vector raised `type: as: cannot cast GUID
to guid`, although every other same-type cast is the identity, so a generic
`(as 'T (enlist x))` failed for GUID only.

Cause: the GUID branch of ray_cast_fn returned a GUID atom unchanged and
handled a string, an empty vector and a list, but a GUID vector fell through
to the type error.

Fix: a GUID vector is returned unchanged (retained), as the atom is.

Behaviour versus dev: only that cast changes, from an error to the identity.

Tests: ops/cast_guid_identity (one-element, multi-element, null-holding and
sliced vectors, the empty-vector and atom cases).

Fixes #1011
Release notes for a squashed dev → master release listed only the release
wrapper commit: the generator walked previous-tag..release-commit, which on
master holds just the wrapper (v3.0.1 came out as a single `v3.0.1 (#984)`
line instead of its features, fixes and performance changes).

The generator now works from the verified release source cut instead of the
artifact commit: it resolves the source from the merged master release PR,
or from hidden release metadata the previous release recorded, requires
immutable objects and identical source/artifact trees, and walks
current-source --not previous-source previous-artifact, so the previous
wrapper is excluded. Provenance, API and git failures are reported instead
of producing incomplete notes. The feature/fix/performance/docs sections,
the collapsed internal changes and the comparison link are kept; a small
hidden source record is saved for the next release and left out of the
announcement. Manual dispatch may name a non-wrapper merge as its own
source. PR-read access is granted to the prepare job only.

Build, packaging, upload, tag, publish and formula steps are unchanged;
existing-release reruns reuse their body.

Tests: 21 offline regressions (.github/test_release_notes.py, run in the
clang-current CI job) over disposable git histories and stubbed API/CLI
fixtures: linear, merge and squash histories, annotated tags,
reconciliation, future/unrelated/numeric tags, provenance and tree
failures, metadata round trip, manual source mode, error propagation and
announcement filtering.
…1045)

Comparing GUID vectors (`==` `!=` `<` `<=` `>` `>=`) and `in` with a GUID vector on either side boxed every cell into an atom: the compare fell to the atomic map's per-element loop, and `in` to the generic hashset because the typed membership kernel declines 16-byte cells.

- Compare: a GUID arm in the atomic map, one pool-parallel loop over the 16-byte cells. Equality compares the two 8-byte halves, ordering uses memcmp as the atom compare does. A cancelled loop returns `cancel`.
- `in`: an in-place table of 16-byte keys built on the smaller side, pool-parallel; a vector against one guid is a byte scan. It runs after the attached-index check. Scratch allocation failure returns `oom` and a cancelled loop `cancel`, with no fallback to the hashset.
- Release, 24 cores: `(all (== a b))` 7.00 → 0.22 ms, `(in held probes)` 7.58 → 0.73 ms, `select where: (== k g)` 25.94 → 0.14 ms over 140K–800K-row columns.

Behaviour versus dev: a GUID cell is null when its 16 bytes are zero, whatever its vector's HAS_NULLS flag says, as `==` and the query null masks already read it. `in` now agrees. With one zero cell in a flagged vector `f` and one in an unflagged vector `u`, `(in f u)` is `[false true]` (was `[false false]`) and `(in 0Ng u)` is `true` (was `false`). The orderings' answers are unchanged.

Tests: `test/rfl/cmp/guid_vec.rfl` and `test/rfl/collection/in_guid.rfl` (vector/vector, vector/atom, atom/vector, nulls, duplicates, empty, past the parallel threshold, slices, in a query); `lang/eval/in_guid_unflagged_nulls`, `lang/eval/in_guid_oom` (fails each scratch allocation through a debug-only hook) and `lang/eval/guid_cancel` in `test/test_lang.c`.

Fixes #763
Working plans and censuses for aggregation, grouping, multicast and
Parquet were tracked under docs/ and three were published as Design
Notes. Plans belong outside the tree; the implemented behaviour is in
the language, architecture and guide pages. The Design Notes section
leaves the nav, and the Parquet validation record no longer names the
removed plan.
… is known (#1057)

On a CPU that reports AVX10.1-256 together with AVX-512F, clang under `-march=native` notes that it will promote the target to avx10.1-512 and reports it as `-Winvalid-feature-combination`. `-Werror` turned that into a failure on the first object, so `make` with clang stopped there.

The Makefile now probes each compiler with `$(CC) -Werror -Wno-error=invalid-feature-combination -x c -fsyntax-only /dev/null` and adds the option only when the compiler accepts it. The diagnostic then stays visible as a warning. gcc and clang older than 16 reject the name, so they get nothing and still build. The fuzz and tsan objects build with `$(CLANG)` and use `WARNS_CLANG`, probed against that compiler.

Behaviour versus dev: none on hosts without AVX10. Verified locally that debug builds with clang 15, gcc and clang 23 all compile (the earlier unprobed version broke clang 15).

Fixes #1056
A string atom tested against a list was split into characters, so `in` answered one verdict per character: `(in "f" (list " " "\t"))` returned `[false]`, a non-empty vector, and `(if (in "f" (list " " "\t")) "T" "F")` took the true branch.

`ray_in_fn` now compares a standalone string with each list element as one whole value, as it already did for a string cell drawn from a collection, and returns a scalar boolean.

Behaviour versus dev: `(in "ab" (list "ab" "c"))` is `true` (was `[true true]`), and `(in "ab" (list "a" "b" "c"))` is `false` (was `[true true]`). A string in a string still answers per character, `(in "ab" "abc")` → `[true true]`, and a vector or list of strings still answers element by element.

Tests: the membership fixture under `test/rfl/collection/`. Docs: `language/functions.md` and `reference/all-functions.md` state the three cases with examples.

Fixes #1037
Adds `make install-headers`, which stages the headers a C client needs into a staging root, so a client can build against an engine revision without a checkout. It stages `include/rayforce.h`, the internals bindings include directly (`src/ops/ops.h`, `src/io/parquet.h`, `src/mem/heap.h`), and the two those reach through quoted includes (`src/store/hnsw.h`, `src/core/platform.h`). They are read-only copies that mirror the source layout under `install/include/rayforce/`, with `rayforce.h` also at the stage root.

A client needs two include roots, `-Iinstall/include -Iinstall/include/rayforce/src`, because the internals include their siblings by `src/`-relative path. `DESTDIR` and `INSTALL_INCLUDE` move the root, quoted throughout. Any failed copy aborts the target, and `make clean` removes what the same overrides staged. Staging promises the header contents at the commit, with no ABI or API stability.

Behaviour versus dev: a new target only; existing targets are unchanged.

Docs: README (Embedding) and `c-api/core.md` describe the target, the two include roots and the stability caveat. Verified locally: `make lib && make install-headers` stages the 7 files and `examples/analytics.c` links against them with the documented command.

Fixes #849
`map` collected every callback result into a boxed `LIST`, so `(map (fn [x] (+ x 1)) [1 2 3])` needed a cast before any typed-vector consumer could use it.

The collector reserves a typed vector after the first representable atom, writes later results of exactly that type directly, and releases each temporary atom. On the first mixed or nested result it reboxes the completed prefix into a list, without re-running any callback, and stays a list. Lazy results are forced before their representation is chosen. `pmap` shares the implementation.

Behaviour versus dev (an accepted language change): a nonempty `map` whose results are all atoms of one vector type returns that typed vector, including strings, symbols, GUIDs, temporals and typed nulls. Mixed types, with no numeric promotion, nested results and untyped `null` stay a `LIST`, as does empty input. BOOL/U8 null atoms and graph, HNSW and Datalog handles stay boxed, because a vector cell cannot carry them. Callers that need a list can box explicitly with `(concat (list) r)`.

Tests: `test/rfl/hof/map_typed.rfl`, `map_handles.rfl` and `mem/map_typed_peak.rfl`, native map/pmap checks in `test/test_lang.c`, and existing fixtures updated where they relied on list results. Docs: `functions.md`, `all-functions.md`, `math.md`, `control-flow.md` and `guides/analytics.md`.

Fixes #958
The compact formatter wrote STR bytes between quotes without escaping them. A quote or backslash in a cell broke the form that `format "%"` prints for a table, and a crafted cell turned the following bytes into code when the output was evaluated: a cell holding `x"] (println "INJECTED") ["` printed `INJECTED` on `(eval (parse (format "%" t)))`.

STR atoms, STR vectors and the cells of parted columns now go through one byte-quoting helper that escapes quotes, backslashes, newlines, tabs, carriage returns and other control bytes. Parted columns have their own compact writer, which previously passed the non-compact flag. The string parser's fixed 4096-byte escape buffer is replaced with one sized to the input, so a long printed string that contains an escape reads back.

Behaviour versus dev: compact output of strings is escaped and parses back to the original bytes. Table and REPL grid output is unchanged.

Tests: `test/rfl/lang/compact_string_escape.rfl` round-trips quotes, backslashes, control bytes, a crafted expression, flat and parted STR columns, and a string longer than 4096 bytes; the `lang/parse` assertion that pinned the old buffer limit is updated.

Fixes #988
`str-find` treated its needle as a search pattern: `?` matched any byte and `[...]` a character class, so `(str-find "a?c" "?")` found the `a` instead of the literal `?`, and a `*` needle raised `domain`. The documentation already described a plain substring search.

`str-find` is now a literal substring search on every path: the builtin, the parallel STR and SYM vector paths, the DAG `exec_str_find`, and the derived-key group program. Each calls `ray_str_find_literal` (memmem) or the derived-key program's memchr-led literal scan. `?`, `*`, `[`, `]` and `.` are ordinary bytes. Patterns remain `like`'s job. The search-pattern engine (`ray_strpat_*`) that only `str-find` used is removed.

Behaviour versus `dev`: needles holding `?` or `[...]` now match literally (`(str-find "abc123" "b?1")` gives `0Nl`, `(str-find "a?c" "?")` gives `1`), and a `*` needle is a literal star instead of a `domain` error.

Tests: `strop/string_search_join` covers each special byte through the builtin, vectors, a derived column, `where:` and a derived group key. `group/derived_key_sym_domain` keeps the derived-key program equal to the row-wise answer for a needle holding `?`.

Docs: `language/string.md`, `language/functions.md` and `reference/all-functions.md` state the literal contract and point to `like` for patterns.

Closes #1051
…1067)

A whole-column count distinct didn't scale with threads, for three reasons:
- it scattered every row into a fixed set of partitions chosen by the value's low bits, so rows in runs of equal values each cost a slot;
- the partition count didn't grow with the column;
- values sharing their low bits (multiples of a power of two) all landed in one partition and were deduplicated serially.

The histogram and scatter passes now skip a value equal to the previous row of the same task, so a run costs one slot. A value's partition is the top bits of its multiplicative hash, and the distinct-values scatter uses the same partition function. The partition count follows a distinct-value estimate taken from 4096 rows, one at a random place in each of 4096 equal stretches of the column:
- with at least 4 values met twice, the estimate is Chao1;
- otherwise, if singletons are under an eighth of the sample, the larger of Chao1 and the singleton tail;
- otherwise the row count.

The count starts at 16, 32 or 64 partitions by worker count and doubles up to 1024 while either holds: the estimate exceeds 64K values a partition, or there are fewer than 8 partitions a worker and each would still hold 1K values. Tasks are 8K rows and grow only while the per-task histograms exceed 64K cells.

Behaviour versus `dev`: the counts are unchanged. Timings, 20M rows, median of 60 runs:
- columns in runs of equal values: 77.5 → 50.2 ms at 4 workers and 65.4 → 19.4 ms at 28;
- multiples of 4096: 924 → 142 ms and 1089 → 38.6 ms;
- random values with no runs: 454 → 168 ms and 158 → 42.6 ms.

A column of 1000 or 100K values with no runs is 2–5% slower at 1–2 workers than `dev` (best of 21 here: `(% i 1000)` 41.6 → 43.1 ms at 1 worker). At 4 workers it is within noise for 1000 values and 13% faster for 100K values; at 28 workers both are faster.

Tests: `group_extra/count_distinct_runs_partitions` checks exact counts over 8.4M rows for I64 runs of three, I32 runs of seven, F64 with signed zeros and several NaN patterns inside runs, multiples of 4096 in runs of two, a column without runs, 1000-value and 300-value columns without runs, and a column repeating with a period of 100K rows.
The quoted-symbol forms of `alter` and `insert` couldn't target a function's locals. `alter` refused a local target with a `domain` error, and `insert` could write back to a same-named global when it rebuilt its result. Growing a local table or vector in a loop therefore copied it at every step.

`alter` and `insert` now resolve a quoted target to the innermost visible local or parameter, then to a global, and publish their result back to that binding. A sole-owned local is amended in place. Aliases, captures, slices, mapped storage and shared dictionary paths keep copy-on-write isolation. An unbound target is an error, and an error never redirects a local write into a same-named global. Dictionary paths rooted in a local work, and a closure with a computed target keeps the enclosing bindings it could name.

Scope: a local is a target only when the call's head is the literal `alter` or `insert`, or a global alias of one bound when the function compiles (`(set ins insert)`). Through any other head (a parameter, a `let`, a dotted head, a computed head, or a name unbound at compile time), the mutator is an ordinary callee and a quoted target resolves as a global, as before. Compiled code and the tree walker apply the same rule.

Also in this change:
- **Dotted reads of locals.** `d.v` and `(d.f x)` rooted in a local now read through the local. They compile to `OP_PATHGET` and cost no more than `(at d 'v)`.
- **Interpreted query helpers** keep their own bindings apart from the query's columns, so they can mutate their own locals and parameters.
- **Constant pool.** A function with more than 65,535 constants used to load the wrong constant through `OP_LOADCONST_W`; it now stays on the tree walker. The pool is indexed past 64 constants, so building a large pool is no longer quadratic.

Behaviour versus `dev`:
- **Locals.** Literal `alter`/`insert` on a local or parameter now amend it, where `alter` raised `domain` and `insert` could write the global.
- **Dotted locals.** Dotted reads and calls rooted in a local resolve through it.
- **Large functions.** Those over the constant limit run interpreted, with correct results.
- **Timing.** Calls through a parameter and global dotted reads time the same as on `dev`.

Tests:
- **`lang/local_mutation`** covers locals, parameters, aliases, nested closures, computed targets, dictionary paths, copy-on-write isolation and the head limit, each compiled and on the tree walker; `local_mutation_walker_fixture` checks the walker cases really are interpreted.
- **Dotted reads.** `dotted_local_read_reinit` and `dotted_local_read_slot` pin the dotted-read path.
- **Constant pool.** `compile/pool_*` pins the limit for both opcodes and the pool's sharing rule.

Docs: `language/syntax.md`, `language/name-resolution.md` ("Mutating a named table"), `language/functions.md` and `reference/all-functions.md` describe the targets and the head limit.

Closes #950
Fixes #1071
…1044)

`(try expr handler)` called the handler with `0` for an error the engine raised itself: a type error, an I/O error, an unbound name, an error in a callee. The error's code and message were freed before the handler ran, so a handler couldn't tell one failure from another or report what failed.

For an engine error, the handler now receives a dict `{code msg}`: `code` is the error class as a symbol (`'type`, `'io`, `'name`, ...) and `msg` is the message as a string, `""` when there is none. Both engines build the same dict and the same message for the same mistake. Values passed to `raise` are unchanged. A plain-value handler builds nothing and gets its value. If the dict can't be built (out of memory), the handler gets `null`.

Also in this change:
- The `code`/`msg` key ids are cached per thread and refreshed when the symbol table is rebuilt.
- `ray_str` and `ray_sym` return an `oom` error instead of writing through a failed allocation.
- A debug-only allocation-failure hook in the heap drives the OOM tests.

Behaviour versus `dev`: an engine-error handler gets `{code msg}` where it got `0`; handlers that compare against `0` need updating. A name error compiled inside a function now carries the name in `msg`, as at the top level, and "head is not callable" reads the same on both engines.

Timings, release builds, 200k iterations:
- a caught engine error with a lambda handler: about 100 ns slower (62.7 → 82.4 ms), the cost of building the dict;
- a value handler: faster (41.6 → 36.9 ms);
- the no-error path: unchanged to slightly faster.

Tests: `hof/try_raise` and `integration/error` cover the dict on both engines, the message parity, re-raise, nested `try`, and handler kinds. `lang/eval/try_catch_releases` checks net bytes over repeated catches. `lang/eval/try_error_keys_reinit` covers a runtime restart. `atom/oom` and an allocation-failure sweep cover OOM.

Docs: `guides/errors.md`, `language/control-flow.md`, `language/functions.md` and `reference/all-functions.md` describe the handler argument.

Closes #923
Track persisted file identity independently of mappings, reject stable POSIX same-size replacement on cached reopen, and preserve own flush/growth baselines.

Closes #1058
Preserve caller lexical scalar probabilities before source-column/global fallback; retain literal, native-callee and grouped behavior.

Related #981. Computed probability expressions remain outstanding; this change does not close that issue.
…o RDMA across hosts when both sides can (#1046)

A connection opens over TCP as before. The second handshake byte now
carries capabilities; a server echoes them only when the client
advertised any, so an older peer on either side never sees a byte it
would refuse. With the capability agreed the client sends one UPGRADE
frame (message type 3, never evaluated or journaled) and the connection
moves: to shared-memory rings when both processes are on one host, to
RDMA when they are on different hosts that both have an active device,
and stays on TCP otherwise. The frames are unchanged on every road, so
sync/async/response, hooks, journaling and restricted mode behave the
same; the socket stays open only to tell of the peer's going.

Shared memory (core/shm.c): a memfd with a control page and a 16 MB ring
per direction plus two eventfds, passed over a private abstract Unix
socket under a one-use token with a peer-credential check. The server
moves once the descriptors have gone and writes one last TCP frame; the
client moves after reading it, so every TCP byte is read before the
rings are. A side with nothing to do raises its sleeping flag and is
rung through its eventfd only then; a busy pair makes no system calls.

RDMA (core/rdma.c, built when the verbs headers are present, the
library loaded at run time only on a host that has it): each side
registers a 64 MB receiving ring; a sender copies a frame into its
staging ring and writes it into the peer's ring with one RDMA write
whose immediate counts the bytes; the receiver returns space the same
way. Completions are polled from memory, the channel's descriptor is
waited on in the poll loop.

Poll layer: a transport vtable on the selector; the rx/tx pumps are
one function each (ray_poll_serve_rx/serve_tx), shared by the epoll
loop, the sync-send wait and the upgrade wait; a pre-wait pass serves
rings whose bytes landed without a wakeup, spins briefly, then raises
the sleeping flags. An upgraded socket no longer takes EPOLLOUT.

Surface: `.ipc.open` option `transport` (auto, tcp, shm, rdma; an
explicit one that cannot be taken fails the open with `io`),
`(.ipc.transport ['policy])` for the process policy, and `transport`
in `(.ipc.handle h)`. A moved link stops compressing unless `compress`
was explicit.

Measured (release): across two hosts on FDR InfiniBand a round trip
goes from 27 µs to 6 µs and 10M longs from 151 ms to 43 ms; on one host
a round trip from 16 µs to 3 µs, bulk transfers 10-25% (they are bound
by serialising and copying, which both roads still do).

Tests: ring unit tests (test/test_shm.c), an end-to-end spawned-server
test (test/rfl/io/ipc_transport.rfl); the multicast tests pin TCP
because they drive the socket itself; two tests that encoded the old
wire facts are updated.


Not in this PR: reading vector payloads in place out of the ring (the bulk-transfer win on one host needs a frame layout that writes vectors from where they lie), RDMA reads straight from the sender's vector, and same-host rings on macOS (memfd and eventfd are Linux).

Review fixes:
- Cutover in both directions: each direction switches on its writer's last TCP frame (XP_SWITCHED), so frames written during the move (greetings, hook posts, replies to them) are kept in order.
- RDMA send queue: queue room is part of admission and readiness, so a non-blocking write never waits on completions.
- Shared memory: rings are mapped lazily, a server makes at most 2 GB of them (63 connections), an idle side connection is dropped after 5 s, and the memory file is sealed at its size.
- RDMA memory: a peer's ring must be 1-64 MB, server endpoints share a 2 GB budget (16 connections), at most 16 wait unconfirmed and an unconfirmed one is dropped after 10 s.
- Cancel on a moved connection: the urgent byte carries the number of the sync request it cancels, so a late cancel is dropped instead of cancelling the next request. A request is numbered only once its frame is built, and a write that fails part way closes the connection.
- Cancel confirmation: the server marks its next reply after it takes a cancel byte (RAY_IPC_FLAG_CANCEL_SEEN, 0x08), and the client keeps at most one byte unconfirmed. A cancel for another request while one is unconfirmed is not sent (Ctrl-C closes the connection), and a request that would carry the unconfirmed number again closes it, so a byte held up in the network never cancels a request it was not for.
- Nested requests: the running request's cancel context is saved and restored around a request dispatched inside its eval, so a byte taken in the nested one is attributed to it, and the outer request stays cancellable after it. The confirmation is set only through the connection looked up again after the eval, which may have closed it.

Verified between two hosts on FDR InfiniBand: cutover with traffic in flight, 20000 posts to a busy server all delivered, the RDMA memory bounds under a hostile client, and cancels. Tests: test/test_shm.c, test/test_rdma.c, the moved-link cancel tests in test/test_ipc.c, test/rfl/io/ipc_transport*.rfl, and the pub/sub tests over rings.
Enforce existing 256 MiB body/decoded admission before allocation and compression. Preserve the separate complete queued-frame cap and valid compression-eligible boundary sizes. Return a serializable IO response on oversized results without copying an extra full frame. Add metadata, genuinely backed shared-value and same-handle response regressions.

Fixes #1100.
Use position-ordered dictionary work for cold FILE-SYM LIKE and grouped extrema, retain resident fallback and correct nullable handling. Gate residency sampling on effective work, and account for NOT operand filter cost.

Accepted as a bounded FILE-workload tradeoff; a 65536-row repeated-code resident case retains a measured sampling premium. No universal no-regression claim.
…er (#1093)

Prepare SYM prefix bounds in dictionary file order, retaining the row-wise fallback. Poll serial/nested marking and filling between 65536-item blocks; parallel dispatch and partial-publication cleanup remain unchanged.
Expose checked journal status with success-only identity and nullable size probing. Keep handle observation separate from append health/durability and fail-closed IPC policy; isolate fault fixtures in a child.
Restore the cppcheck2.19 baseline with analyzer-only feature-probe definition and individually reasoned narrow suppressions. No engine C tokens changed; compiler layout probes and producer/consumer contracts support the classifications.
Normalize only determining non-BOOL scalar logical results; reuse already-BOOL owned accumulators and preserve laziness, single-argument identity and vector routes. Refs #976: broadcasting and NOT remain separate, this partial fix does not close it.
Stream numeric generation-2 Parquet chunks using immutable first-chunk training and ordered parts with cooperative encode/put cancellation. Reuse codec statistics/delta widths/dictionary codes and full-width multiplicative dictionary hashing, and collect grouped-SYM prefix bounds during decode. Add spread, delta, cancellation and staged-versus-chunked route tests; preserve explicit file/mem staging controls. Source and targeted evidence retain their documented heads/layers; all actual integrated-head checks passed.
@singaraiona
singaraiona merged commit d5a44cd into master Nov 6, 2026
14 checks passed
singaraiona added a commit that referenced this pull request Nov 8, 2026
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, as #1108 did. RELEASE.md asked for a manual
merge-back, which was skipped after v2.11.5 and v3.0.1.

Add a merge-back job to the Release workflow. It verifies that dev already
has everything the release shipped, then records the ancestry with a -s ours
merge that changes no files. If master carries changes of its own, it fails
instead of merging.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants