Skip to content

v2.8.1 - #582

Merged
singaraiona merged 33 commits into
masterfrom
dev
Sep 18, 2026
Merged

v2.8.1#582
singaraiona merged 33 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

vbmithr and others added 30 commits September 17, 2026 23:18
ray_env_get() segfaults when called from any thread that did not call
ray_runtime_create(). env_lookup_flat() dereferences the thread-local
__VM unconditionally, while every other function on the same path
already guards it — including ray_env_get_local() immediately below,
which does the identical scope-stack walk behind `if (!__VM)`.

__VM is assigned in exactly one place in the tree (runtime.c, inside
ray_runtime_create), and no public API binds a VM to any other thread,
so every other thread has __VM == NULL by construction.

This is reachable from the public IPC API: ray_ipc_close ->
ray_poll_deregister -> ipc_on_close -> hook_call_lifecycle ->
hook_lookup -> ray_env_get -> env_lookup_flat. With no hook installed
hook_call_lifecycle is meant to be a no-op — its next statement is
`if (!fn) return;` — and the unguarded dereference is the only thing
preventing that.

Skip the local scopes when there is no VM; global bindings must still
resolve. No behavioural change on a thread that has a VM: the loop body
is unchanged, only wrapped in `if (__VM)`.

Co-Authored-By: Claude Opus 5 <[email protected]>
The v2.8.0 Pages deploy failed with "Aborted with 10 warnings in strict
mode": several top-level engineering docs lived in docs/ but were absent
from nav, and grouping-engine-scaling-plan.md linked to a results doc
that nav never listed either.

- Add a "Design Notes" nav section for the three design plans.
- List multicast-usage.md under the .mc namespace; it was an orphan too.
- Delete aggregation-fast-path-results.md and grouping-engine-scaling-results.md:
  raw measurement dumps belong with the benchmark harness, not the
  published site. The two references to them in the scaling plan now
  point at bench/groupby_shapes/.
ray_table_nrows and ray_table_ncols segfault when handed a value that is
not a table (#567). They guard NULL and errors but not the type tag, then
decode the argument's payload as the two-slot {schema, cols} layout and
dereference whatever comes out.

The reporter framed this as a quirk of IPC-deserialized atoms, since a
locally built ray_i64(42) was benign. The real trigger is just payload
bytes that dereference badly — a plain I64 vector crashes deterministically:

    ray_t* v = ray_vec_from_raw(RAY_I64, poison, 4);
    ray_table_ncols(v);   /* SIGSEGV at table.c:274 */

These are not holding a deliberate line. The rest of the layer already
checks its own tag — ray_dict_keys rejects a non-RAY_DICT, ray_parted_nrows
rejects a non-parted vector — so the table accessors are the outlier, and
the same hole is in all eight of them, not just the two reported. An
embedder sees one opaque ray_t* and has nothing to check against but the
tag the accessor already holds.

Add tbl_is_table() and route every public accessor through it: wrong tag
gets the empty answer (0 / NULL / -1), mutators become no-ops, and none of
them reads the payload as slots. Document the guarantee in rayforce.h,
which previously said nothing either way, and point callers who need a
diagnosable rejection at ray_table_validate_rectangular.

No cost: the call sites are per-operation, not per-row (agg_engine.c:128's
parallel-size test is the hot one), and the compare hits a field in the
same cache line as the NULL check already there. Interleaved A/B over
ClickBench q13/16/17/20/22/28 on the 10M splayed store, min-of-3 x 2
passes, shows no movement outside run-to-run spread.
fix(env): guard env_lookup_flat against a thread with no VM
…n type

The audit caught a real hole in the first commit. The header block I added
promised totality for every declaration below it, and ray_table_add_col is
in that list but was not converted — so the documentation invited exactly
the call that corrupts memory: a non-table gets ray_cow'd, then new schema
and cols pointers are written straight into the argument's payload. Worse
than the crash #567 reported, and now advertised as safe.

Guard it. It consumes its tbl ref and owns its result, so the wrong-tag
answer is a typed "type" error rather than an empty one, releasing tbl on
that path exactly as the bad-column path beside it already does.

Rewrite the header block to say what each function actually returns on a
wrong tag instead of asserting one blanket answer for a list whose members
have different return contracts, and to spell out that add_col consumes tbl
on the error path.

Tests: table/add_col_wrong_type, written first and watched to fail in
ray_vec_append on the decoded 0x4141... payload. Broadened
table/accessors_reject_dict from three functions to the whole set, since a
dict carries real pointers and was certifying less than the header claimed.

Also corrects a stale comment the audit flagged in passing: table.h:30 said
RAY_TABLE was 13, it is 98.

make test: 3890 of 3890 passed.
fix(table): make the public table accessors total over ray_t
…lines

The keyless scalar path (no `by:`) hands every pool worker a 1-slot
accumulator whose count/sum/min/max/sumsq/nn_count arrays were separate
8-24-byte scratch allocations.  Those land next to each other on the
heap, so adjacent workers' counters share cache lines and every row
bounces a line between cores — across sockets the query collapses:
`sum / count / avg` over 100M rows took 2.7 s on one thread, 0.27 s on
12 threads of one socket, and 8.8 s on all 48.

Each worker now gets one block, aligned to a 64-byte line and padded to
whole lines, carrying all of its arrays; `_h_sum` owns it and the other
headers stay NULL for da_accum_free.  Same box, 48 threads: 8.8 s -> 0.10 s.

Test agg/keyless_pool_accum.rfl: the combined multi-aggregate form over
200k rows (pooled path) against the single-aggregate forms and the plain
vector reductions — integer, float and nullable inputs, with a where
filter, and thirteen aggregates at once.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ng instead of materialising atoms

Resolving a symbol of a FILE domain (`ray_sym_domain_str`) materialises
an arena atom for its position under the global domain spinlock on the
first touch.  `like` over a near-unique SYM column resolves every symbol
once, so a cold scan paid one lock + one allocation per distinct entry —
and on the pool the workers serialised on that lock: a cold
`(count (select {where: (like URL "*x*")}))` over 300k splayed rows took
318 ms on the pool against 42 ms single-threaded.  An aggregate over
`(strlen URL)` walked the same road row by row.

A FILE domain's mapping already holds every entry as [u32 len | bytes]
at a known offset.  `ray_sym_domain_raw_pin` hands a reader the
(map, offsets, count) triple; while any reader is pinned an extend (the
symfile grew under another opener) raises a flag, drains the readers and
only then swaps the mapping, so the reads are lock-free and the unmap is
safe.  Runtime-domain columns and positions appended after open resolve
as before.

Users: both `like` paths over SYM (the flat/selection path and the
parted path, plus the case-insensitive flat path), the fused predicate's
LIKE leaf (pinned at compile, released at cleanup), `exec_strlen`, and
the legacy group path's strlen-on-SYM aggregate, which now materialises
the lengths off the mapping once (parallel) and aggregates a plain I64
vector.

300k splayed rows, pool: cold like-count 318 -> 4.7 ms, `select … where
like` 3.7 -> 1.5 ms, like + asc/take 3.9 -> 1.1 ms, like + group 4.6 ->
2.5 ms; `avg (strlen URL)` cold 46 -> 9 ms.  In-memory (runtime domain)
and STR columns unchanged.  Results byte-identical.

Tests: symbol/file_domain_like_strlen.rfl — 120k-row splayed table, every
like path (count, select, top-k, plain) and strlen (plain, sum/avg in a
group) against the same computation over the strings, incl. suffix and
exact patterns that see the last byte; domain/raw_pin — raw bytes equal
the atoms for every position, runtime domain refuses, appended entries
stay past the mapped prefix.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ing instead of draining readers

The first version made an extend raise a flag and spin under g_dom_lock
until every raw reader had unpinned — while a pinned reader that met a
position past the mapped prefix fell back to ray_sym_domain_str, which
takes that same lock: an ABBA deadlock, and short of it a stall of every
domain operation for as long as a fused predicate held its pin.

The domain now publishes (map, offsets, count) as one atomically swapped
record.  An extend builds the new record and RETIRES the previous one
together with its offsets array and its mapping (unmapped only when the
domain is destroyed, the way replaced atom arrays already are), so a
snapshot stays readable for as long as its holder keeps the domain
alive.  No waiting on either side; pin is an acquire load and unpin a
no-op kept for symmetry.  The include in fused_pred.h moves inside the
guard.

A null cell (the empty symbol) in the group path's strlen aggregate is a
null length that the accumulate skips — the behaviour of the per-row
path — and the test now asserts it on groups made of empty symbols.
domain/raw_pin grows the file under a held snapshot: the reopen extends
the domain and the old snapshot still reads every old position.

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

Closes #573.

An embedded process could not learn anything about itself — no pid, no
hostname — and .sys.exec discarded stdout. The reported consequence: an
owner process handing subscribers an (epoch, cursor) pair had no way to
mint an epoch unique to one process start, so a cursor held across a
restart stayed plausible and a subscriber silently resumed mid-stream.
The working version cost three process spawns, a world-readable temp file
and an interpolated shell string to obtain one identity.

.sys.info gains pid and hostname beside the existing machine facts, so
one call answers both "what am I running on" and "which process am I".
host+pid+timestamp is a better epoch than a random token because it is
diagnosable: reading it back names the machine and the process.

.sys.exec now returns the exit code the shell would report rather than
the raw waitpid-encoded status — (.sys.exec "exit 3") was 768. Signals
report 128+signum. Success was 0 before and after, so code that only
tests for zero is unaffected; the docs carry a warning for code comparing
against an encoded value. The docs previously stated the 256 behaviour
outright, so this is a deliberate correction, not an accident.

A second argument 'out returns {code, out}, capturing stdout. The buffer
grows geometrically rather than sizing from stat(), so pipes and procfs
reads come back whole — which is also the common workaround for #572.
stderr is deliberately left uncaptured: a shelled-out command's
diagnostics belong in the log, and merging them would corrupt whatever
parses the captured value.

Not addressed here: (timestamp 'global) already exposes a wall clock, so
the issue's "no wall-clock time" premise was wrong — but it is built on
time(NULL) and is second-resolution. pid separates two starts within the
same second, so the epoch case is covered; ns resolution is a separate
question.

Tests: test/rfl/system/process_identity.rfl, written first and watched to
fail. Covers pid/hostname shape and stability, exit codes including the
127 shell convention, code+output reported together, empty output, output
larger than one read buffer, stderr staying out of the capture, and mode
rejection. Two existing tests asserted (count (.sys.info)) is 3; updated
to 5.

make test: 3891 of 3891 passed. mkdocs build --strict clean.
…paths

Blocking CI finding: exec_capture and exec_exit_code are file-static and
were defined unconditionally, but their only callers sit in the #else arm
of the RAY_FUZZING switch in ray_system_fn. Under -DRAY_FUZZING the
callers preprocess away, exec_capture has no references left, and
-Wunused-function under -Werror takes the whole fuzz build down.
Reproduced locally with RAY_MARCH=x86-64 make fuzz-smoke, which now
builds clean and completes its three targets.

Also took three non-blocking observations from the same audit:

- system() returns -1 when the shell cannot be started at all. Decoded,
  that became 128+127 = 255, indistinguishable from a command that really
  exited 255. It is now an io error, matching how the capture path already
  reports the equivalent pclose failure. Added (.sys.exec "exit 255") to
  the tests so the two cases stay distinguishable.
- The {code, out} dict build fed ray_sym_vec_new/ray_list_new results
  straight into the append calls with no RAY_IS_ERR guard, unlike
  ray_sysinfo_fn beside it. Guarded, releasing what was already built.
- Two test cases were coupled to the environment rather than to the
  behaviour under test: the 100 KB producer leaned on seq and ARG_MAX
  (now a pipe), and the hostname case asserted non-empty, which the
  implementation deliberately does not promise — it degrades to "" when
  the platform cannot answer. It now cross-checks against uname(1), which
  tests the thing that matters: that a reported hostname is the right one.

make test: 3891 of 3891 passed. make fuzz-smoke: clean.
…he length off the snapshot there

Materialising the lengths as an I64 vector changed the answer of
`avg`/`sum (strlen sym)` for an on-disk column: the per-row accumulate
counts an empty symbol as length 0 (and, under a row selection, the other
accumulate skips it), while a materialised vector carries a null the
generic accumulate skips — so the same data answered differently on disk
and in memory.  The aggregate keeps its per-row path; group_strlen_at now
reads a FILE-domain entry's length off the published raw snapshot (one
acquire load per cell, no atom, no lock) and falls back as before.
ray_sym_strlen_into loses the flag nobody else needed.

Test: keyed avg/sum(strlen) over a column with empty symbols, with and
without a where, must give the same answer for the splayed table as for
the identical in-memory table — plus the two-empties/one-mixed minimal
case.  A wrong raw length fails it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
cppcheck flagged the unsigned char* -> double* cast (invalidPointerCast);
the block is now addressed as 8-byte words and every array cast goes
through void*.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
feat(sys): process identity in .sys.info; .sys.exec exit codes and output capture
Closes #572.

read_file_bytes sized the read from fseek/ftell. Everything under /proc
and /sys reports 0 while yielding data, so those files came back as a
well-formed empty string — no error, no short-read signal. A caller
branching on the content silently took the wrong branch, which is how the
reporter's process ended up with an empty identity from
(read "/proc/sys/kernel/random/uuid").

Two more cases fall out of the same cause: a FIFO cannot be seeked at all,
so it was an outright io error rather than a stream to read; and an
ordinary file that changed size between the measure and the read produced
a spurious io error, since the code required fread to return exactly the
measured count.

Now: loop on fread until EOF, growing as needed. The reported size is kept
as a capacity hint where it is plausible, so an ordinary file is still one
allocation and one read — measured on a 90 MB file, time and peak RSS are
unchanged.

A directory seeks fine and reports LONG_MAX, which UBSan caught as signed
overflow on the +1 for the growth probe. An implausible hint is now
treated as no hint; the read itself is what rejects a directory, since
fread sets the error flag and we return io.

Tests: test/rfl/io/read_until_eof.rfl, written first and watched to fail.
Ordinary, empty and 300 KB files; /proc/sys/kernel/hostname cross-checked
against both uname(1) and .sys.info's gethostname value; two reads of
/proc/sys/kernel/random/uuid asserted to differ, which proves the file is
really being read rather than a cached view of it; a FIFO; and missing
path / directory still raising io.

make test: 3892 of 3892 passed. fuzz-smoke and mkdocs --strict clean.
perf(sym): like and strlen read a FILE domain's entries off the mapping instead of materialising atoms
fix(agg): keep each worker's keyless accumulators on their own cache lines
Closes #571.

guid seeded its per-thread xorshift state from rand(), on the stated
assumption that "rand() is itself seeded by the runtime". Nothing in the
tree has ever called srand(), so rand() ran from libc's default seed of 1
and every process produced the same GUID sequence. The comment asserted a
behaviour that was never implemented.

The reporter's first value on their machine and their build was
byte-identical to ours — daa76c35-3e3a-4f10-acce-5ec3dfb2fcab — which is
what a total absence of entropy looks like rather than a per-machine seed.
Uniqueness is the one property the type exists to provide, and it failed
silently: the values are well-formed and carry the correct version-4
nibble, so two processes writing GUID row ids into one table collided
with nothing to notice.

Seeded from /dev/urandom on POSIX at first use, per thread. Process id, a
high-resolution clock and a stack address are always folded in and run
through a splitmix64 finaliser, so a chroot without /dev, or a platform
with no reachable entropy source, still cannot hand two processes or two
threads the same stream. The folded material is structured — a small pid,
a slow-moving clock — and xorshift64* needs its state well mixed or the
first outputs stay correlated with the seed.

rand() is deliberately untouched. Its determinism is defensible and is
what makes tests and simulations reproducible; the issue asked for the
two to be separated rather than for rand to change, and (rand 3 1000)
still returns [383 886 777] in every process. Both are now documented as
drawing from different sources on purpose.

No cost: the seed is taken once per thread behind the existing
RAY_UNLIKELY(state == 0) branch, and the generator body is unchanged.
1M guids, three runs: 4.672/4.711/5.226 ms before, 4.719/4.721/4.703
after. 40 fresh processes produce 40 distinct values; 200k in one process
have no duplicates.

Tests: test/rfl/lang/guid_entropy.rfl, written first and watched to fail
on the cross-process comparison. Spawns two fresh ./rayforce processes via
.sys.exec's capture form and asserts their first GUIDs differ, with a
length check on each so two empty reads cannot masquerade as a pass. Also
pins the in-process properties so a future seeding change cannot regress
them into a constant.

make test: 3892 of 3892 passed. fuzz-smoke and mkdocs --strict clean.
…s explicitly

macOS CI failed: test/rfl/io/read_until_eof.rfl asserted on
/proc/sys/kernel/hostname, which does not exist there, so read correctly
returned io. The .rfl harness is line-based and has no per-platform skip,
so procfs cannot be asserted from it at all.

Moved those cases to test_lang.c as lang/io/read_procfs_zero_size, which
SKIPs off Linux and also SKIPs when procfs is not mounted. In C it can
assert the premise directly — stat reports st_size 0 — then check the read
is non-empty, matches gethostname, and that two reads of
/proc/sys/kernel/random/uuid differ.

The .rfl file keeps the portable half, and the FIFO case covers the same
"cannot be sized, must be read to EOF" class on every platform. Its 300 KB
producer moved from  to dd, since tr's handling of \0 differs
between GNU and BSD.

Also made the directory case deterministic instead of platform-dependent.
Linux fails the read with EISDIR so ferror caught it, but that is not
guaranteed elsewhere, and a directory returning "" would be precisely the
silent wrong answer this change exists to remove. read_file_bytes now
rejects a directory up front with an io error, mirroring the S_ISDIR check
ray_load_file_fn already does in the same file.

make test: 3893 of 3893 passed. fuzz-smoke clean.
From the PR 577 audit's non-blocking list, which turned out to matter more
than its blocking one.

Reading to EOF made an endless stream unbounded: (read "/dev/zero")
previously returned "" instantly and now grew until the process died. That
is a regression this change introduced, and a worse answer than either the
old empty string or an error.

The growth loop now stops once the next doubling would cross
ray_heap_anon_watermark() — the heap's existing spill threshold, which
resolves to physical RAM — and returns io naming the budget. Derived from
a budget already in the tree rather than a new constant. This converts an
OOM kill into a diagnosable error; it does not make reading an infinite
device cheap, and is a safety net rather than a policy.

The same guard covers the theoretical cap * 2 overflow the audit noted:
hint is clamped to INT64_MAX/2, so cap could reach INT64_MAX/2 + 1 and
double into UB. ncap <= 0 now fails before allocating.

Also corrected a comment the audit flagged as describing a now-dead
fallback: since directories are rejected up front by the S_ISDIR check,
the in-loop guard is for anything else reporting a size it cannot back.

make test: 3896 of 3896 passed. fuzz-smoke clean.
…eshold

Second round of PR 577 audit findings. The substantive one corrects my own
reasoning.

ray_heap_anon_watermark() is not a memory ceiling — it is the spill
threshold, and crossing it routes the mapping to a disk file rather than
failing ("this never rejects work, it just picks disk over RAM" —
mem/heap.c). Bounding an unsized read by it therefore traded an OOM kill
for filling the spill file, which is worse, not better. My previous commit
message claimed it converted an OOM into a bounded error; that was wrong.

Now bounded by a quarter of the *remaining* anon headroom
(watermark - committed), following the admission gate in ops/cdfuse.c,
which uses the same watermark as an input to a derived limit rather than
as the limit itself, and the same "unknown RAM stays permissive"
convention. ray_heap_set_anon_watermark still steers it, so no new knob.
(read "/dev/zero") now errors in 8.4 s at 12.5 GB peak RSS, under the
budget and with no spill, instead of growing until the process died.

The same budget applies to the hinted path, which previously relied on
ray_vec_new to OOM on a file claiming an implausible size.

The overflow guard was also written as if it caught cap * 2, which it
could not — the multiply is UB before the check runs. It now tests
cap > INT64_MAX / 2 before multiplying.

Windows: mem/heap.h is a project header and was inside the POSIX include
guard, and struct stat / S_ISDIR were used unconditionally in a function
compiled on both paths. Moved the include out and guarded the directory
check. Noting for the record that no CI job builds Windows — it is
commented out at release.yml:117 — so this was not a live break, but the
file carries Windows arms and should stay self-consistent.

Tests: the .rfl file now pid-suffixes its paths, since a shared FIFO on a
concurrent runner hangs in fopen rather than failing, and it grew a case
that reads 120000 bytes from a real FIFO — five doublings — because the
previous cases all had size hints and never entered the growth loop at
all. A first attempt passed while testing nothing: a format call was
missing its second argument, mkfifo failed, and dd left an ordinary file
that took the hinted path. lang/io/read_unsized_bounded drives the budget
directly by moving the watermark just above what is committed.

make test: 3897 of 3897 passed. fuzz-smoke clean.
…ction

Third round of PR 577 audit findings. Both blockers correct.

The hinted path must not be bounded. A reported size is a finite claim the
filesystem backs, and a file larger than the headroom previously allocated
and spilled to disk and worked; bounding it turned that into a hard io
error. Worse, the bound moved with ray_heap_anon_committed(), so whether a
given read succeeded depended on what the rest of the session had
allocated at that instant — the same script on the same file could pass
and then fail.

I applied it there because the previous audit round listed the hinted
path's absence as an inconsistency. This round is right and that one was
not: the budget exists to terminate an endless stream, which is not a
situation a size hint can describe.

Removing that check also removes the FILE* leak, which was on exactly that
early return — every other error exit in the function closes fp. Neither
test covered it, because /dev/zero reports size 0 and so takes the growth
path, whose check does close fp.

The growth guard now bounds peak rather than result: the old buffer stays
alive across the memcpy, so the transient footprint is 3*cap, not 2*cap.
Overflow is checked against INT64_MAX/3 before the multiply, and the
"too large" and "over budget" cases are separate messages — the combined
one printed "budget of 0 bytes" when RAM was unknown.

Also: the hint range check compared through long, which is
implementation-defined on ILP32; it now compares in int64_t. And the C
test restored the watermark to its *effective* value, pinning it to the
RAM figure where the suite had the 0 "use physical RAM" sentinel; it now
detects that case and restores the sentinel.

Tests: lang/io/read_unsized_bounded now also asserts that a 2 MB sized
file reads fine under a ~1 MB budget — the regression this round
identified. Mutation-verified: re-adding the hinted-path check fails it.

Docs now state that an unsized stream can be refused by size and that a
sized read cannot.

make test: 3897 of 3897 passed. fuzz-smoke and mkdocs --strict clean.
fix(io): read and read-bytes read until EOF, not to the reported size
fix(guid): seed from the OS, independently of rand
…bound the capture

Closes #579.

The capture reads to EOF on the child's stdout, and a backgrounded
grandchild inherits that pipe, so 'out waits for it too rather than only
for the shell:

  (.sys.exec "(sleep 3 &) ; true" 'out)          -> 3.00 s
  (.sys.exec "./server &" 'out)                  -> waits for the server
  (.sys.exec "(sleep 3 &) >/dev/null 2>&1" 'out) -> 0.00 s

This is inherent to popen(3) and not something to fix in the builtin --
the one-argument form does not have it, since it waits only for the
shell. Documented in namespaces/sys.md with the detaching idiom and a
pointer at the one-argument form for launching anything that outlives the
call, plus a note in the code so the next reader does not rediscover it
from a hang.

Also bounded the capture buffer, which the audits flagged twice and which
#579 records: a command that never stops writing has no end to capture,
exactly as an endless file has no EOF to read. The ceiling already
written for read/read-bytes now backs both -- ray_unsized_read_budget
moved to lang/internal.h rather than duplicated, since the two call sites
bound the same thing for the same reason.

Tests: lang/io/exec_capture_bounded runs `cat /dev/zero` under a lowered
watermark and asserts io. Mutation-verified -- removing the budget check
hangs the suite until the runner kills it, which is precisely the failure
the bound prevents.

make test: 3899 of 3899 passed. fuzz-smoke and mkdocs --strict clean.
Closes #569.

__VM is bound only by ray_runtime_create, so any thread an embedder drives
IPC from -- the FFI teardown path in particular -- has none. PR 565 made
the *no hook installed* case safe by letting ray_env_get fall through to
globals, and deliberately left this open: with a hook actually bound,
call_fn1 would run user code with __VM == NULL.

A hook is user code and should behave the same wherever the event came
from, so dispatch now binds a VM for the duration. The alternatives were
worse: skipping the hook is silent and invisible at the call site, and
failing the close would break the FFI teardown that runtime.c:50-54
explicitly supports.

Binding also restores `.ipc.handle` inside the hook. ipc_ctx_set stores
through __VM and returns early without one, so on a VM-less thread the
hook previously saw a handle of -1 even when it ran.

ray_vm_t is ~68 KB, too large for a teardown-path stack, so the temporary
comes from the buddy heap -- process-wide and already live, since the heap
belongs to the runtime rather than the thread. Teardown mirrors
ray_runtime_destroy: release raise_val and trace, then free. Grown scope
frames are not walked, matching that same teardown. Threads that already
have a VM pay one predicted branch and allocate nothing.

Tests: ipc/close_hook_vmless_thread stands up a real server, connects,
then drives ray_poll_deregister from a thread that never called
ray_runtime_create. It asserts the hook ran and that it observed a real
`.ipc.handle` rather than -1.

Mutation-verified, and the mutant reproduces the reported hazard exactly:

  src/lang/eval.c:124:16: runtime error: member access within null
  pointer of type 'struct ray_vm_t'

make test: 3899 of 3899 passed. fuzz-smoke clean.
docs(sys): warn that .sys.exec 'out waits for backgrounded children; bound the capture
The audit was right and it corrects a claim I made in the PR description.

.ipc.on.close is one process-global binding and ipc_on_close fires it for
both ends of a connection, so the server thread -- which has a VM -- also
incremented the counter and also set a valid handle. Both assertions were
satisfied by that firing alone, so the test did not distinguish fixed from
unfixed behaviour. It additionally read those globals through ray_eval_str
while the server poll thread could still be writing them, which is an
unsynchronised access to g_env.

My "mutation-verified" claim was true only in a weaker sense than stated:
the mutant was caught by UBSan aborting on the NULL deref at
eval.c:124 (fn_is_restricted reading __VM->restricted), not by the
assertions. In a build without UBSan, or whenever the server processed
EOF first, the test would have passed with the fix reverted.

Fixed by stopping the server before installing the hook. With no hook
bound during shutdown there is no server-side firing, so the single
firing afterwards is unambiguously the client-side teardown driven from
the VM-less thread -- and the poll loop that was racing the reads is gone
by then. The assertions are now exact: fired == 1, and the handle equals
this connection's h rather than merely being non-negative.

Re-verified with a mutant that does not crash, so only the assertions can
catch it -- hook_vm_bind refusing to bind, i.e. the "skip silently"
alternative:

  test/test_ipc.c:731: fired->i64 != 1  (got 0, expected 1)

Also took the three non-blocking items: the OOM path now logs before
skipping the hook, matching how this file reports every other hook
failure; hook_call_auth and the sync/async dispatch carry a note saying
they are unbound because they only run under ray_poll_run, so a future
embedder-driven path knows it needs the same treatment; and the test
registry entry is aligned with its neighbours.

make test: 3900 of 3900 passed. fuzz-smoke clean.
fix(ipc): bind a VM for lifecycle hooks on VM-less threads
@singaraiona
singaraiona merged commit e7091be into master Sep 18, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants