From 559b37cfea4ad256e1121c3736bc568fc6d68b94 Mon Sep 17 00:00:00 2001 From: Vincent Bernardoff Date: Thu, 17 Sep 2026 23:18:39 +0200 Subject: [PATCH 01/20] fix(env): guard env_lookup_flat against a thread with no VM MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/lang/env.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/lang/env.c b/src/lang/env.c index 2aeefd733..a4356f630 100644 --- a/src/lang/env.c +++ b/src/lang/env.c @@ -294,10 +294,15 @@ void ray_env_destroy(void) { * Returns NULL if not bound. Always used as the head-segment resolver * for dotted paths, and as the fast path for plain names. */ static ray_t* env_lookup_flat(int64_t sym_id) { - for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) { - ray_scope_frame_t* f = &__VM->scope_stack[d]; - for (int32_t i = 0; i < f->count; i++) { - if (f->keys[i] == sym_id) return f->vals[i]; + /* FFI/embedding callers reach this on threads that never bound a VM + * (cf. ray_env_get_local, already guarded). Such a thread has no + * local scopes; global bindings must still resolve. */ + if (__VM) { + for (int32_t d = __VM->scope_depth - 1; d >= 0; d--) { + ray_scope_frame_t* f = &__VM->scope_stack[d]; + for (int32_t i = 0; i < f->count; i++) { + if (f->keys[i] == sym_id) return f->vals[i]; + } } } for (int32_t i = 0; i < g_env.count; i++) { From 17bc874db021e16797567c94f3213d042334c6a1 Mon Sep 17 00:00:00 2001 From: Anton Date: Thu, 17 Sep 2026 23:57:48 +0200 Subject: [PATCH 02/20] docs: fix the strict-mode Pages build; publish plans, drop results dumps 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/. --- docs/aggregation-fast-path-results.md | 46 ----- docs/grouping-engine-scaling-plan.md | 7 +- docs/grouping-engine-scaling-results.md | 245 ------------------------ mkdocs.yml | 5 + 4 files changed, 9 insertions(+), 294 deletions(-) delete mode 100644 docs/aggregation-fast-path-results.md delete mode 100644 docs/grouping-engine-scaling-results.md diff --git a/docs/aggregation-fast-path-results.md b/docs/aggregation-fast-path-results.md deleted file mode 100644 index a8ce6596e..000000000 --- a/docs/aggregation-fast-path-results.md +++ /dev/null @@ -1,46 +0,0 @@ -# Aggregation and query type coverage - -This records earlier type-coverage work. Current implementation and validation -are tracked in the [grouping engine plan](grouping-engine-scaling-plan.md) and -[results report](grouping-engine-scaling-results.md). - -## Implemented coverage - -| Plan | Gaps | Final implementation | -|---|---|---| -| P1 | Plumbing for A1–A10 | Native input widths, F32 NaN validity, type-correct scalar writes, disjoint parallel payload writes with null metadata merged afterward. Native extrema emission avoids temporary atoms. Stable source row indices retain column/domain ownership for ordered and wide values. | -| P2 | A1–A4, A6–A8, A11 | Streaming sum/min/max/avg/product/statistics across legal numeric/temporal types. F32 truth and mixed binary statistics. COUNT counts every row, including nulls. DATE/TIMESTAMP sum and temporal product/truth remain illegal. | -| P3 | K1, K3, K4 | Nullable dense mapping reserves a null slot without spanning the sentinel; selected/composite/all-null keys use the same mapping. Signed radix keys preserve nulls. Dense worker/global slabs have allocation and sampled traffic budgets; setup, merge and scalar emission are parallel. Removed full-input-per-worker generic hash allocation. | -| P4 | A2, A5 | First/last use stable original-row order, including selections; wide extrema use source rows and existing comparators. SYM extrema compare domain strings. LIST first/last retain selected values. | -| P5 | K2 | Canonical float hashing/equality, GUID bytes, STR bytes and structural LIST grouping. Small/ordered/buffered shapes use one shared index layout. Plain LIST-key aggregate queries, including composite keys, reach it through `select`. Large float/GUID/STR streaming shapes with up to eight keys use the existing parallel wide-key engine. | -| P6 | A9, A10 | Shared group IDs and stable row slices for median, quantile, mode, top/bottom-K, ordered/wide and mixed streaming aggregates. Wide/F32 top-K stores at most K row indices. Existing typed numeric heaps and rank helpers remain shared. | -| P7 | Q1, Q2 | Fused exact count-distinct accepts nullable BOOL/U8/signed/temporal/SYM/F32/F64 pairs. SYM is reachable despite conservative null metadata. F32 generic exact counting widens losslessly once to reuse F64 dedupe. | -| P8 | Q3–Q5 | F32/F64, nullable numeric/temporal, GUID and ordinary STR fused comparisons. Float/GUID filter/top-k sorting. Composite F32 sorts reuse the tested single-column float transform and radix-compose ranks. | -| P9 | Q6–Q8 | Typed F32/GUID/STR broadcasts, F32 numeric/pow admission, and one-time materialization of pure temporal arithmetic through unit-aware operations before typed aggregation. | - -The [census](aggregation-type-census.csv) preserves the original 210 observations -and adds current streaming registration and grouped route columns. Registry -presence and query strategy are different: holistic/ordered operations use row -indices instead of streaming accumulator states. - -## Explicit generic and rejected cases - -- Heterogeneous LIST arithmetic/extrema/rank operations retain dynamic value - evaluation. No inference from the first element selects a fixed-width kernel. - Structural LIST keys and LIST first/last have a bounded shared-index route. -- GUID/STR/LIST count-distinct uses exact generic dedupe. The packed count-distinct - rewrite still requires total key/value width at most 16 bytes; wide values - are not truncated or interpreted as integers. -- Large float/wide streaming keys retain the established parallel implementation. - On one million rows, moving these to serial index grouping regressed STR and - F32 key workloads by about 3x. Admission now reports `parallel wide-key strategy`. - Shapes needing ordered/buffered states, LIST keys, and more than eight keys - use the bounded index route. -- Nullable LIKE/IN, SYM ordering predicates, and cross-unit temporal comparisons - retain their existing evaluators. The new fused comparison leg covers the six - scalar comparison operators; it does not silently extend other evaluators. -- Raw temporal DAG arithmetic stays guarded. Pure `+`, `-`, and `*` expressions - are materialized once using existing unit/promotion rules. Other expressions, - side-effecting calls, and unsupported partition shapes retain existing evaluation. -- Eval-level `as 'F32` remains outside this change's language surface. F32 test - and benchmark fixtures use the existing query projection cast or C constructors. diff --git a/docs/grouping-engine-scaling-plan.md b/docs/grouping-engine-scaling-plan.md index 5faa649c4..65285f1db 100644 --- a/docs/grouping-engine-scaling-plan.md +++ b/docs/grouping-engine-scaling-plan.md @@ -5,8 +5,9 @@ The feature is ready for PR review into `dev`; required CI checks gate merging. This extends the type-coverage plan. Acceptance compares immutable release binaries with identical generated inputs. -The rebased ASan/UBSan suite passes 3,828/3,828 tests. Current measurements -and reproducible commands are in [the results report](grouping-engine-scaling-results.md). +The rebased ASan/UBSan suite passes 3,828/3,828 tests. Measurements and the +commands that reproduce them are kept with the benchmark harness in +`bench/groupby_shapes/`, not in the published docs. ## Objective @@ -33,7 +34,7 @@ additional data structures. Each family needs its own baseline and scaling proof | Count-distinct | Pair-hash partitioning and parallel stable output ordering | Native/wide value and ordering oracles; repeated worker sweep | | Mixed streaming/indexed aggregates and expressions | Shared groups and stable row slices | Independent mixed contracts and repeated worker sweep | -The [results report](grouping-engine-scaling-results.md) links the complete +The benchmark harness in `bench/groupby_shapes/` holds the complete 900-configuration summary, all 2,700 process records, phase investigations and regression repeats. Baseline failures receive no speedup claim. Measured cold setup and bounded-memory tradeoffs remain explicit. diff --git a/docs/grouping-engine-scaling-results.md b/docs/grouping-engine-scaling-results.md deleted file mode 100644 index 559a02f44..000000000 --- a/docs/grouping-engine-scaling-results.md +++ /dev/null @@ -1,245 +0,0 @@ -# Grouping engine scaling results - -Status: the full scaling matrix was validated at `f61a4eda`; the audit -follow-up below covers the query regression fixes. This report contains only synthetic -fixtures and generic engine validation. Required PR checks gate merging. - -## Audit follow-up - -The PR audit identified missing query coverage and an empty-result inference -regression after the measured revision above. - -- Restored the original W32 SYM single-key query and kept the additional - two-key radix fixture. The single-key result is normalized after query - execution by its unique numeric row value before checking every source key - and aggregate. This preserves query-path coverage and key/value association - checks without assuming a group output order that the engine does not promise. -- Added query fixtures for all nine STR/GUID/LIST key/value combinations, - selected and mixed count-distinct queries, full key-column emission, and - composite keys wider than 16 bytes. Expected counts come from a four-row - pattern, with values differing beyond a shared prefix. -- Added empty-input and selected-out query fixtures, including aggregate - aliases that exercise generic unary evaluation. Empty-input domain/type - errors no longer turn a zero-group query into an error. A separate injected - error test checks that OOM and cancellation still propagate. -- Added task-array bounds assertions, a dense partition capacity assertion, - a generic native-width copy fallback, and invalid rank-selection checks. - -The cancellation concern does not require clearing every slab on the -coordinator: dispatch joins its tasks, cancellation is checked before merge, -and destruction already skips slabs whose `ready` flag is false. Cancellation -after that check cannot undo a completed task's initialization. - -Validation at `fdf365f3`: **3,832/3,832 ASan/UBSan tests passed**. The restored -symbol fixture and wide count-distinct fixture also passed separately with -28 total threads. Injected empty-result errors and invalid rank boundaries -are covered in the full suite. - -A clean release of `fdf365f3` completed without warnings (SHA-256 -`ab1f19e100f89164af1ef511fe6390cf3e634114a1fb0c5df9bd039c578e343b`). -The follow-up compared eight dense-query shapes against `f61a4eda` at 1, 8, -and default workers: **144/144 fresh-process typed comparisons passed**. -Three default-worker warm slowdowns were repeated with five processes per -binary, adding **30/30 passing comparisons**. Their slower medians did not -reproduce in that follow-up; both samples remain available. - -| Default-worker case | Initial baseline / candidate warm ms | Repeat baseline / candidate warm ms | -|---|---:|---:| -| Binary aggregates | 2.431 / 3.034 | 2.349 / 2.316 | -| Clustered keys | 0.630 / 0.730 | 0.626 / 0.603 | -| Symbol keys | 0.232 / 0.249 | 0.237 / 0.229 | - -See the [environment](../bench/groupby_shapes/results/2026-09-16-audit/environment.json), -[summary](../bench/groupby_shapes/results/2026-09-16-audit/grouping.csv), -[all process samples](../bench/groupby_shapes/results/2026-09-16-audit/processes.csv), -[repeat summary](../bench/groupby_shapes/results/2026-09-16-audit/repeat.csv), and -[repeat process samples](../bench/groupby_shapes/results/2026-09-16-audit/repeat-processes.csv). -This focused comparison does not establish a new general speedup. - -The restored query fixture also exposed two sorting races under hosted TSan. -The shared sortedness flag now uses relaxed atomic accesses, and in-place key -packing no longer reads a neighboring task's element; the existing coordinator -pass checks boundary pairs after the dispatch barrier. The triggering fixture -reproduced both races before the fix and passed afterward. Follow-up validation: -**130/130 sort ASan/UBSan tests** and **41/41 parallel TSan tests** passed without -race reports, using four total threads for TSan. The aggregation TSan suite at -`fdf365f3` also passed **26/26** without suppressions. These sorting fixes do not -change the grouping traversal measured above. - -The timing tables below remain measurements of `f61a4eda`; they are not -presented as a new full sweep of the audit follow-up. - -## Method - -Use separate immutable release binaries, identical generated inputs and worker -settings 1, 2, 4, 8, 16 and default. Run binaries sequentially, reversing their -order between rounds. Record the first query separately from five warm queries -in each of three fresh processes. Retain timing ranges and peak RSS. - -The default pool uses all 28 logical CPUs on the validation host. Typed result -comparisons check keys, nulls and integer values exactly; floating reductions -use relative tolerance `1e-9` and absolute tolerance `1e-8`. Independent unit -oracles cover ordering, nulls, rank and distinct semantics. - -## Correctness - -The following completed checks apply to revision `f61a4eda`. - -- **2,700 fresh-process runs**, 77 synthetic cases, six worker settings and three rounds: all typed cold/warm result comparisons passed. -- Complete ASan/UBSan suite: **3,828/3,828 passed**. -- Targeted TSan: **24/24 passed**, `RAYFORCE_CORES=3` (four total threads), `setarch x86_64 -R`, no suppressions. -- Coverage includes native widths, source symbol domains, structural LIST keys, - stable row indices, dominant-group exact `med`/quantile, frequency ties, - parallel top/bottom-K merges, adaptive symbol slices and typed empty output. - -Earlier TSan attempts with five total threads stalled during pool shutdown before -the aggregation checks; they are not counted as passes. The final run used four -total threads and reported no races. No pool implementation or suppression was -changed to obtain that result. - -Four synthetic cases fail in the baseline: STR-valued count-distinct and its -mixed form crash; LIST-key count-distinct and its mixed form raise a type error. -These cases receive no baseline speedup claim. Candidate results are checked -across workers and with independent unit-test oracles. - -## Warm performance by family - -Times below are medians of three process warm medians, in milliseconds. -The [complete summary](../bench/groupby_shapes/results/2026-09-15/grouping.csv) -contains all 77 cases and all worker counts. The [process records](../bench/groupby_shapes/results/2026-09-15/processes.csv) -retain every cold time, five warm times, result/binary hashes and peak RSS. - -| Synthetic case | Baseline, 28 | Current, 8 | Current, 28 | Baseline/current at 28 | -|---|---:|---:|---:|---:| -| `extrema-time` | 6.379 | 1.816 | 0.958 | 6.66x | -| `sum-time` | 5.228 | 1.098 | 0.678 | 7.72x | -| `sum-i64` | 6.013 | 1.101 | 0.724 | 8.30x | -| `count` | 3.350 | 1.249 | 0.571 | 5.86x | -| `statistics` | 10.153 | 2.320 | 1.313 | 7.73x | -| `binary` | 17.848 | 4.203 | 2.415 | 7.39x | -| `product` | 5.789 | 1.221 | 0.737 | 7.85x | -| `truth` | 8.331 | 1.802 | 1.004 | 8.30x | -| `median` | 6.209 | 3.247 | 2.021 | 3.07x | -| `quantile` | 6.110 | 3.323 | 2.022 | 3.02x | -| `mode` | 6.682 | 4.346 | 2.264 | 2.95x | -| `top-bottom` | 9.028 | 5.655 | 4.373 | 2.06x | -| `first-last` | 9.594 | 2.808 | 1.738 | 5.52x | -| `distinct` | 12.735 | 6.107 | 4.112 | 3.10x | -| `mixed` | 8.763 | 3.857 | 2.397 | 3.66x | -| `composite` | 13.981 | 3.886 | 2.119 | 6.60x | -| `selected` | 2.525 | 1.191 | 0.968 | 2.61x | -| `sparse` | 5.975 | 7.922 | 7.014 | 0.85x | -| `float-key` | 6.357 | 4.220 | 2.208 | 2.88x | -| `string-key` | 8.497 | 2.628 | 1.652 | 5.14x | -| `guid-key` | 10.530 | 2.948 | 2.518 | 4.18x | -| `list-key` | 27.750 | 3.764 | 2.762 | 10.05x | - -Aggregate costs differ, and these measurements do not establish linear scaling -or a universal best worker count. I64 sum improves from eight to 28 workers in -this final sweep; its strategy changes from task-local state to partitioned -state. The GUID case now splits medium-sized rank groups using the common -parallel grain, closing the scheduling gap found during phase review. - -## Cold costs and repeatability - -The main sweep retains these regressions. The follow-up used five additional -fresh processes per binary for every configuration that was over 5% slower in -at least two main-sweep rounds: 13 configurations and **130 verified runs**. -All [follow-up process records](../bench/groupby_shapes/results/2026-09-15/regression-repeat.csv) -are retained; they do not replace the main samples. - -| Case / workers | Metric | Main baseline ms | Main current ms | Repeat baseline ms | Repeat current ms | -|---|---|---:|---:|---:|---:| -| `clustered` / 4 | cold | 1.700 | 2.588 | 2.248 | 1.709 | -| `clustered` / 8 | cold | 2.145 | 2.596 | 1.938 | 2.506 | -| `hot-min-descending` / 8 | cold | 1.446 | 2.047 | 1.409 | 2.099 | -| `float-key` / default | cold | 3.841 | 4.994 | 3.921 | 5.040 | -| `nonnull` / 8 | cold | 3.062 | 3.411 | 2.493 | 3.191 | -| `product` / 8 | cold | 2.348 | 2.615 | 2.260 | 2.600 | -| `symbol-key` / 2 | cold | 0.647 | 0.885 | 0.750 | 0.710 | -| `symbol-key` / 2 | warm | 0.527 | 0.763 | 0.671 | 0.559 | -| `sparse` / default | warm | 5.975 | 7.014 | 6.196 | 5.890 | - -Neither warm slowdown reproduced in the five-process follow-up. The symbol -and sparse samples vary across runs; these fixtures support neither a fixed -warm regression nor a universal speedup claim. The additional cold flags for -`extrema-f32`, `sum-f64`, `truth`, `extrema-i32` and `sum-time` also did not -retain a median regression above 5% in the follow-up. - -Cold regressions remain for the eight-worker descending-min, clustered, -nonnull and product fixtures, and for default-worker float keys. The -[68 profiled runs](../bench/groupby_shapes/results/2026-09-15/phase-profiles.csv) -place the extra time in slab allocation, histogram/scatter, directory setup -and filling row indices: - -- Descending-min and product spend about 0.66 and 0.64 ms, respectively, in - cold slab allocation; the corresponding warm phase rounds to zero. -- Clustered histogram/scatter takes about 1.83 ms cold versus 0.49 ms warm. -- Float-key directory allocation/initialization takes about 1.05 ms cold - versus 0.09 ms warm; row-index filling takes 1.49 versus 0.59 ms. - -The bounded state and shared-directory strategies reduce repeated state -initialization and merging, while retaining these first-execution costs. -The report keeps those costs alongside the warm improvements. - -The rank profiles also confirm the medium-group scheduling change: the -four-group GUID fixture now uses parallel rank selection within its groups. -Small groups retain the direct consumer; task counts remain bounded by work -and scratch storage. All query state is rebuilt per execution. - -## Coverage ledger - -The `agg_contract` tests in [test_agg_contract.c](../test/test_agg_contract.c) -check values and routes independently of benchmark timings. - -| Engine work | Synthetic cases | Correctness evidence | -|---|---|---| -| Native streaming and scalar output | `sum-*`, `extrema-*`, `count`, `statistics`, `product`, `truth` | Unary scalar/grouped contracts, every streaming registry writer, native null/overflow output, parallel float oracle | -| Binary reductions | `binary` | All numeric input-type pairs; zero weights, null-only pairs and empty states | -| Dense strategies and skew | `clustered`, `unique-keys`, `skew`, `all-null-key`, `hot-min-*` | Route assertions, extreme native values, constrained heap budget, independent per-key results | -| Selected and composite grouping | `selected`, `composite`, `selected-indexed` | Selected source-row identity, composite keys and mixed consumers | -| Shared wide-key directory | `float-*`, `string-*`, `guid-key`, `list-key` | Full value equality, float canonicalization, structural keys and stable group indices | -| Ordered and wide consumers | `first-last`, `wide-extrema`, `symbol-extrema`, corresponding `hot-*` cases | First/last source order, symbol domains, native gathering and dominant-group winners | -| Exact rank, mode and top/bottom K | `median`, `quantile`, `mode`, `top-bottom`, wide/symbol and `hot-*` variants | Rank/null/slice oracles, frequency ties, reordered indices, bounded heaps and parallel merges | -| Exact distinct and mixed consumers | `distinct*`, `mixed-distinct*`, `mixed`, `skew-indexed` | Native and wide distinct oracles, first-row ordering, shared stable layouts | - -The final timing matrix covers each case at 1/2/4/8/16/default workers. Invalid -operation/type pairs stay explicit errors; heterogeneous LIST arithmetic keeps -its existing dynamic evaluation. Default pool size and useful task count are -separate: the pool exposes all CPUs while each stage bounds tasks by its work -and memory budget. - -## Internal top/bottom-K kernel - -All **90 runs** at revision `f61a4eda` matched the independent histogram oracle. -These synthetic inputs have 4,000,003 rows; K above 1024 exercises the internal -kernel, without changing the query language limit. - -| K | 1 worker warm ms | 8 workers warm ms | Default (28) warm ms | -|---:|---:|---:|---:| -| 1024 | 11.206 | 2.148 | 1.795 | -| 65536 | 53.571 | 20.432 | 17.512 | -| 4000003 | 772.737 | 159.594 | 89.194 | - -Values are medians of the three process warm medians. The CSV in -`bench/groupby_shapes/results/2026-09-15/topk.csv` retains process ranges, -cold medians and peak RSS. Scaling varies with K; these results do not establish linear scaling. The baseline fails the -full-size-K oracle because of partially filled heap ordering, so that case -has no baseline speedup claim. - -## Reproduction - -```sh -python3 bench/groupby_shapes/grouping_scaling.py \ - --binary /path/to/candidate --baseline /path/to/baseline \ - --baseline-skip-cases distinct-string-values,mixed-distinct-string-values,distinct-list-keys,mixed-distinct-list-keys \ - --workers 1,2,4,8,16,default --rounds 3 --output /tmp/grouping.json - -python3 bench/groupby_shapes/summarize_scaling.py /tmp/grouping.json /tmp/grouping.csv \ - --process-output /tmp/grouping-processes.csv -``` - -To investigate one configuration, use the same driver with, for example, -`--cases symbol-key --workers 2 --rounds 5`. Add `--profile` for a separate -phase-timing run; profiling measurements are kept separate from the main sweep -and unprofiled repeats. diff --git a/mkdocs.yml b/mkdocs.yml index a3d9835ca..f70922102 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -132,6 +132,7 @@ nav: - .idx — Indexes: docs/namespaces/idx.md - .ipc — IPC client: docs/namespaces/ipc.md - .log — Write-ahead log: docs/namespaces/log.md + - .mc — Multicast: multicast-usage.md - .mem — Measurement: docs/namespaces/mem.md - .os — Process env: docs/namespaces/os.md - .repl — REPL control: docs/namespaces/repl.md @@ -170,6 +171,10 @@ nav: - Pipeline & Optimizer: docs/architecture/pipeline.md - Memory Model: docs/architecture/memory.md - Block Offloading: docs/architecture/offloading.md + - Design Notes: + - Aggregation Fast Paths: aggregation-fast-path-plan.md + - Grouping Engine Scaling: grouping-engine-scaling-plan.md + - Multicast Implementation: multicast-implementation-plan.md - C API: - Core API: docs/c-api/core.md - DAG API: docs/c-api/dag.md From c7ccc45b2aeca03366ec7e237b852164c99a9d03 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 00:32:59 +0200 Subject: [PATCH 03/20] fix(table): make the public table accessors total over ray_t MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- include/rayforce.h | 14 ++++++++++++- src/table/table.c | 28 +++++++++++++++++-------- test/test_table.c | 51 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+), 9 deletions(-) diff --git a/include/rayforce.h b/include/rayforce.h index 2ab292714..e2c273eb3 100644 --- a/include/rayforce.h +++ b/include/rayforce.h @@ -677,7 +677,19 @@ ray_err_t ray_sym_load(const char* path); ray_t* ray_env_get(int64_t sym_id); ray_err_t ray_env_set(int64_t sym_id, ray_t* val); -/* ===== Table API ===== */ +/* ===== Table API ===== + * + * The accessors below are total over ray_t: handed a value whose type is not + * RAY_TABLE — an atom, a vector, a dict, an error, NULL — each returns the + * empty answer (0, NULL, -1) and each mutator is a no-op. They never read the + * argument's payload as table storage, so an embedder holding an opaque + * ray_t* can call them without first establishing the type. + * + * ray_table_validate_rectangular() remains the way to get a *diagnosable* + * rejection: it returns a typed error naming what it got, where these + * accessors answer 0/NULL indistinguishably from a genuinely empty table. + * Use it when the difference matters. + */ ray_t* ray_table_new(int64_t ncols); ray_t* ray_table_add_col(ray_t* tbl, int64_t name_id, ray_t* col_vec); diff --git a/src/table/table.c b/src/table/table.c index 10a6c09fb..73485a139 100644 --- a/src/table/table.c +++ b/src/table/table.c @@ -50,6 +50,18 @@ static inline ray_t** tbl_slots(ray_t* tbl) { return (ray_t**)ray_data(tbl); } +/* The public accessors below decode `tbl`'s payload as the two-slot + * {schema, cols} layout, so they are only meaningful for a RAY_TABLE. An + * embedder sees one opaque ray_t* and has nothing to check against, so each + * accessor is total over ray_t: a wrong tag gets the empty answer, never a + * read through a decoded payload (#567). Matches ray_dict_keys and + * ray_parted_nrows, which already check their own tags. Internal callers + * establish the type during dispatch and pay one predicted compare against a + * field already in the same cache line as `type`. */ +static inline bool tbl_is_table(ray_t* tbl) { + return tbl && !RAY_IS_ERR(tbl) && tbl->type == RAY_TABLE; +} + static inline ray_t* tbl_schema(ray_t* tbl) { return tbl_slots(tbl)[0]; } @@ -189,7 +201,7 @@ ray_t* ray_table_validate_rectangular(ray_t* tbl, const char* context) { * -------------------------------------------------------------------------- */ ray_t* ray_table_get_col(ray_t* tbl, int64_t name_id) { - if (!tbl || RAY_IS_ERR(tbl)) return NULL; + if (!tbl_is_table(tbl)) return NULL; ray_t* schema = tbl_schema(tbl); ray_t* cols = tbl_cols(tbl); if (!schema || !cols) return NULL; @@ -206,7 +218,7 @@ ray_t* ray_table_get_col(ray_t* tbl, int64_t name_id) { * -------------------------------------------------------------------------- */ ray_t* ray_table_get_col_idx(ray_t* tbl, int64_t idx) { - if (!tbl || RAY_IS_ERR(tbl)) return NULL; + if (!tbl_is_table(tbl)) return NULL; ray_t* cols = tbl_cols(tbl); if (!cols) return NULL; if (idx < 0 || idx >= cols->len) return NULL; @@ -221,7 +233,7 @@ ray_t* ray_table_get_col_idx(ray_t* tbl, int64_t idx) { * -------------------------------------------------------------------------- */ void ray_table_set_col_idx(ray_t* tbl, int64_t idx, ray_t* col_vec) { - if (!tbl || RAY_IS_ERR(tbl) || !col_vec) return; + if (!tbl_is_table(tbl) || !col_vec) return; ray_t** slots = tbl_slots(tbl); ray_t* cols = slots[1]; if (!cols || RAY_IS_ERR(cols)) return; @@ -240,7 +252,7 @@ void ray_table_set_col_idx(ray_t* tbl, int64_t idx, ray_t* col_vec) { * -------------------------------------------------------------------------- */ int64_t ray_table_col_name(ray_t* tbl, int64_t idx) { - if (!tbl || RAY_IS_ERR(tbl)) return -1; + if (!tbl_is_table(tbl)) return -1; ray_t* schema = tbl_schema(tbl); if (!schema) return -1; if (idx < 0 || idx >= schema->len) return -1; @@ -253,7 +265,7 @@ int64_t ray_table_col_name(ray_t* tbl, int64_t idx) { * -------------------------------------------------------------------------- */ void ray_table_set_col_name(ray_t* tbl, int64_t idx, int64_t name_id) { - if (!tbl || RAY_IS_ERR(tbl)) return; + if (!tbl_is_table(tbl)) return; ray_t** slots = tbl_slots(tbl); ray_t* schema = slots[0]; if (!schema || RAY_IS_ERR(schema)) return; @@ -269,13 +281,13 @@ void ray_table_set_col_name(ray_t* tbl, int64_t idx, int64_t name_id) { * -------------------------------------------------------------------------- */ int64_t ray_table_ncols(ray_t* tbl) { - if (!tbl || RAY_IS_ERR(tbl)) return 0; + if (!tbl_is_table(tbl)) return 0; ray_t* schema = tbl_schema(tbl); return schema ? schema->len : 0; } int64_t ray_table_nrows(ray_t* tbl) { - if (!tbl || RAY_IS_ERR(tbl)) return 0; + if (!tbl_is_table(tbl)) return 0; ray_t* cols = tbl_cols(tbl); if (!cols || cols->len <= 0) return 0; ray_t* first_col = ((ray_t**)ray_data(cols))[0]; @@ -313,6 +325,6 @@ int64_t ray_parted_nrows(ray_t* v) { } ray_t* ray_table_schema(ray_t* tbl) { - if (!tbl || RAY_IS_ERR(tbl)) return NULL; + if (!tbl_is_table(tbl)) return NULL; return tbl_schema(tbl); } diff --git a/test/test_table.c b/test/test_table.c index 97530cbe5..209e8e14a 100644 --- a/test/test_table.c +++ b/test/test_table.c @@ -564,6 +564,55 @@ static test_result_t test_table_accessors_null_and_err(void) { PASS(); } +/* Every public table accessor is total over ray_t: handed a value that is not + * a table it returns the empty answer, it does not read the payload as slot + * pointers. Issue #567 — an embedder sees one opaque ray_t*, so there is + * nothing to check against but the tag the accessor already has. The payload + * here is poisoned so that any accessor still treating it as slots dereferences + * 0x4141... and takes the process down rather than quietly returning garbage. */ +static test_result_t test_table_accessors_wrong_type(void) { + int64_t poison[] = {0x4141414141414141LL, 0x4141414141414141LL, + 0x4141414141414141LL, 0x4141414141414141LL}; + ray_t* vec = ray_vec_from_raw(RAY_I64, poison, 4); + TEST_ASSERT_NOT_NULL(vec); + + TEST_ASSERT_EQ_I(ray_table_ncols(vec), 0); + TEST_ASSERT_EQ_I(ray_table_nrows(vec), 0); + TEST_ASSERT_NULL(ray_table_schema(vec)); + TEST_ASSERT_NULL(ray_table_get_col(vec, ray_sym_intern("c", 1))); + TEST_ASSERT_NULL(ray_table_get_col_idx(vec, 0)); + TEST_ASSERT_EQ_I(ray_table_col_name(vec, 0), -1); + + /* Mutators must be no-ops rather than writes through a decoded payload. */ + ray_table_set_col_name(vec, 0, ray_sym_intern("c", 1)); + ray_table_set_col_idx(vec, 0, vec); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(vec))[0], 0x4141414141414141LL); + + ray_release(vec); + PASS(); +} + +/* A dict shares the table's two-slot layout, so the accessors would happily + * read real pointers out of it and answer with a dict's shape. The tag is the + * only thing separating the two; assert it is honoured. */ +static test_result_t test_table_accessors_reject_dict(void) { + int64_t kraw[] = {1, 2, 3}; + int64_t vraw[] = {10, 20, 30}; + ray_t* keys = ray_vec_from_raw(RAY_I64, kraw, 3); + ray_t* vals = ray_vec_from_raw(RAY_I64, vraw, 3); + ray_t* d = ray_dict_new(keys, vals); + TEST_ASSERT_NOT_NULL(d); + TEST_ASSERT_EQ_I(d->type, RAY_DICT); + TEST_ASSERT_EQ_I(ray_dict_len(d), 3); + + TEST_ASSERT_EQ_I(ray_table_ncols(d), 0); + TEST_ASSERT_EQ_I(ray_table_nrows(d), 0); + TEST_ASSERT_NULL(ray_table_schema(d)); + + ray_release(d); + PASS(); +} + /* ray_parted_nrows on a plain (non-parted) vector returns vec->len directly. */ static test_result_t test_parted_nrows_plain_vec(void) { int64_t raw[] = {1, 2, 3, 4}; @@ -615,6 +664,8 @@ const test_entry_t table_entries[] = { { "table/set_col_name", test_table_set_col_name, table_setup, table_teardown }, { "table/set_col_name_shared", test_table_set_col_name_shared, table_setup, table_teardown }, { "table/accessors_null_and_err", test_table_accessors_null_and_err, table_setup, table_teardown }, + { "table/accessors_wrong_type", test_table_accessors_wrong_type, table_setup, table_teardown }, + { "table/accessors_reject_dict", test_table_accessors_reject_dict, table_setup, table_teardown }, { "table/parted_nrows_plain_vec", test_parted_nrows_plain_vec, table_setup, table_teardown }, { "table/nrows_empty_col", test_table_nrows_empty_col, table_setup, table_teardown }, { NULL, NULL, NULL, NULL }, From 142de18b69232cc1026871ae92ff199e6b596968 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 11:22:02 +0200 Subject: [PATCH 04/20] fix(table): guard ray_table_add_col too; state the contract per return type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- include/rayforce.h | 27 +++++++++++++++-------- src/table/table.c | 11 ++++++++++ src/table/table.h | 2 +- test/test_table.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 10 deletions(-) diff --git a/include/rayforce.h b/include/rayforce.h index e2c273eb3..7b23814f7 100644 --- a/include/rayforce.h +++ b/include/rayforce.h @@ -679,16 +679,25 @@ ray_err_t ray_env_set(int64_t sym_id, ray_t* val); /* ===== Table API ===== * - * The accessors below are total over ray_t: handed a value whose type is not - * RAY_TABLE — an atom, a vector, a dict, an error, NULL — each returns the - * empty answer (0, NULL, -1) and each mutator is a no-op. They never read the - * argument's payload as table storage, so an embedder holding an opaque - * ray_t* can call them without first establishing the type. + * Every function here that takes a `ray_t* tbl` is total over ray_t: handed a + * value whose type is not RAY_TABLE — an atom, a vector, a dict, an error, + * NULL — none of them reads the argument's payload as table storage. An + * embedder holding one opaque ray_t* can call any of them without first + * establishing the type. What a wrong tag yields differs by return contract: * - * ray_table_validate_rectangular() remains the way to get a *diagnosable* - * rejection: it returns a typed error naming what it got, where these - * accessors answer 0/NULL indistinguishably from a genuinely empty table. - * Use it when the difference matters. + * ray_table_ncols / ray_table_nrows -> 0 + * ray_table_col_name -> -1 + * ray_table_schema / ray_table_get_col* -> NULL + * ray_table_set_col_name / ray_table_set_col_idx -> no-op + * ray_table_add_col -> typed "type" error + * ray_table_validate_rectangular -> typed "type" error + * + * ray_table_add_col consumes its `tbl` ref on every path, the error path + * included, so a wrong tag releases the argument exactly as a bad column does. + * + * The two that return a typed error are the ones to reach for when the + * distinction matters: the accessors answer 0/NULL indistinguishably from a + * genuinely empty table, so they cannot tell you *why* the answer was empty. */ ray_t* ray_table_new(int64_t ncols); diff --git a/src/table/table.c b/src/table/table.c index 73485a139..10d39b6ef 100644 --- a/src/table/table.c +++ b/src/table/table.c @@ -130,6 +130,17 @@ ray_t* ray_table_new(int64_t ncols) { ray_t* ray_table_add_col(ray_t* tbl, int64_t name_id, ray_t* col_vec) { if (!tbl || RAY_IS_ERR(tbl)) return tbl; + /* Unlike the accessors, this consumes `tbl` and owns its result, so the + * wrong-tag answer has to be a typed error rather than an empty one — + * same consume-and-error contract as the bad-column path below. Without + * it a non-table gets ray_cow'd and then has slot pointers written into + * its payload (#567). */ + if (tbl->type != RAY_TABLE) { + ray_t* err = ray_error("type", "table add_col: expected table, got %s", + ray_type_name(tbl->type)); + ray_release(tbl); + return err; + } if (!table_col_is_valid(col_vec)) { ray_release(tbl); return ray_error("domain", "table add_col: column must be list/vector-like, got %s", diff --git a/src/table/table.h b/src/table/table.h index 16eff4ebc..dfd1c34a4 100644 --- a/src/table/table.h +++ b/src/table/table.h @@ -27,7 +27,7 @@ /* * table.h -- Table operations. * - * A table has type = RAY_TABLE (13), len = current column count. + * A table has type = RAY_TABLE (98), len = current column count. * Data region: first sizeof(ray_t*) bytes = pointer to schema (I64 vector * of column name symbol IDs), then ncols * sizeof(ray_t*) = column vector * pointers. diff --git a/test/test_table.c b/test/test_table.c index 209e8e14a..55d8415e0 100644 --- a/test/test_table.c +++ b/test/test_table.c @@ -592,6 +592,40 @@ static test_result_t test_table_accessors_wrong_type(void) { PASS(); } +/* ray_table_add_col is the one mutator that cannot answer "empty": it consumes + * its table ref and returns an owned result, so the wrong-tag answer has to be + * a typed error, matching the bad-column path right beside it. Handed a + * non-table it previously ran ray_cow then wrote new slot pointers straight + * into the argument's payload — the same #567 hazard, but corrupting rather + * than only crashing. */ +static test_result_t test_table_add_col_wrong_type(void) { + int64_t poison[] = {0x4141414141414141LL, 0x4141414141414141LL, + 0x4141414141414141LL, 0x4141414141414141LL}; + ray_t* vec = ray_vec_from_raw(RAY_I64, poison, 4); + TEST_ASSERT_NOT_NULL(vec); + + int64_t col_raw[] = {1, 2, 3}; + ray_t* col = ray_vec_from_raw(RAY_I64, col_raw, 3); + TEST_ASSERT_NOT_NULL(col); + + /* add_col consumes one ref of its first argument, so hand it one of ours + * and keep the reference we assert through afterwards. */ + ray_retain(vec); + ray_t* res = ray_table_add_col(vec, ray_sym_intern("c", 1), col); + TEST_ASSERT_NOT_NULL(res); + TEST_ASSERT_TRUE(RAY_IS_ERR(res)); + TEST_ASSERT_STR_EQ(ray_err_code(res), "type"); + + /* And the payload it would have decoded is untouched. */ + TEST_ASSERT_EQ_I(((int64_t*)ray_data(vec))[0], 0x4141414141414141LL); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(vec))[1], 0x4141414141414141LL); + + ray_error_free(res); + ray_release(col); + ray_release(vec); + PASS(); +} + /* A dict shares the table's two-slot layout, so the accessors would happily * read real pointers out of it and answer with a dict's shape. The tag is the * only thing separating the two; assert it is honoured. */ @@ -608,6 +642,25 @@ static test_result_t test_table_accessors_reject_dict(void) { TEST_ASSERT_EQ_I(ray_table_ncols(d), 0); TEST_ASSERT_EQ_I(ray_table_nrows(d), 0); TEST_ASSERT_NULL(ray_table_schema(d)); + TEST_ASSERT_NULL(ray_table_get_col(d, ray_sym_intern("c", 1))); + TEST_ASSERT_NULL(ray_table_get_col_idx(d, 0)); + TEST_ASSERT_EQ_I(ray_table_col_name(d, 0), -1); + + /* Mutators would otherwise write through the dict's real slot pointers. */ + ray_table_set_col_name(d, 0, ray_sym_intern("c", 1)); + ray_table_set_col_idx(d, 0, d); + TEST_ASSERT_EQ_I(ray_dict_len(d), 3); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_dict_keys(d)))[0], 1); + + int64_t col_raw[] = {1, 2, 3}; + ray_t* col = ray_vec_from_raw(RAY_I64, col_raw, 3); + ray_retain(d); + ray_t* res = ray_table_add_col(d, ray_sym_intern("c", 1), col); + TEST_ASSERT_TRUE(RAY_IS_ERR(res)); + TEST_ASSERT_STR_EQ(ray_err_code(res), "type"); + TEST_ASSERT_EQ_I(ray_dict_len(d), 3); + ray_error_free(res); + ray_release(col); ray_release(d); PASS(); @@ -665,6 +718,7 @@ const test_entry_t table_entries[] = { { "table/set_col_name_shared", test_table_set_col_name_shared, table_setup, table_teardown }, { "table/accessors_null_and_err", test_table_accessors_null_and_err, table_setup, table_teardown }, { "table/accessors_wrong_type", test_table_accessors_wrong_type, table_setup, table_teardown }, + { "table/add_col_wrong_type", test_table_add_col_wrong_type, table_setup, table_teardown }, { "table/accessors_reject_dict", test_table_accessors_reject_dict, table_setup, table_teardown }, { "table/parted_nrows_plain_vec", test_parted_nrows_plain_vec, table_setup, table_teardown }, { "table/nrows_empty_col", test_table_nrows_empty_col, table_setup, table_teardown }, From be33fef8ad0c5e15b306290e1328094e21492d94 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Fri, 18 Sep 2026 06:28:40 +0300 Subject: [PATCH 05/20] fix(agg): keep each worker's keyless accumulators on their own cache lines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/ops/group.c | 46 ++++++++++++++++----------- test/rfl/agg/keyless_pool_accum.rfl | 49 +++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 19 deletions(-) create mode 100644 test/rfl/agg/keyless_pool_accum.rfl diff --git a/src/ops/group.c b/src/ops/group.c index f6ae68a3b..be7f3b4f8 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -12117,44 +12117,52 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, sc_n * sizeof(da_accum_t)); if (!sc_acc) { scratch_free(sc_vla_hdr); goto da_path; } - /* Allocate 1-slot accumulators per worker (n_aggs entries) */ + /* One cache-line-aligned block per worker holding every 1-slot + * accumulator array (n_aggs entries each). Separate small + * allocations land next to each other on the heap, so adjacent + * workers' counters share cache lines and every row bounces the + * line across cores: on a two-socket 48-thread box the keyless + * SUM/COUNT/AVG over 100M rows took 8.8 s against 0.27 s on one + * socket. The block is padded to a whole number of lines and + * carried by _h_sum; the other headers stay NULL for + * da_accum_free. */ bool alloc_ok = true; + const size_t sc_line = 64; + size_t sc_words = 1; /* count[1] */ + if (need_flags & DA_NEED_SUM) sc_words += n_aggs; /* sum */ + if (need_flags & DA_NEED_MIN) sc_words += n_aggs; /* min_val */ + if (need_flags & DA_NEED_MAX) sc_words += n_aggs; /* max_val */ + if (need_flags & DA_NEED_SUMSQ) sc_words += n_aggs; /* sumsq_f64 */ + if (sc_any_nullable) sc_words += n_aggs; /* nn_count */ + size_t sc_bytes = ((sc_words * sizeof(int64_t)) + sc_line - 1) / sc_line * sc_line; for (uint32_t w = 0; w < sc_n; w++) { + uint8_t* raw = (uint8_t*)scratch_calloc(&sc_acc[w]._h_sum, sc_bytes + sc_line); + if (!raw) { alloc_ok = false; break; } + uint8_t* blk = (uint8_t*)(((uintptr_t)raw + sc_line - 1) & ~(uintptr_t)(sc_line - 1)); + size_t off = 0; + sc_acc[w].count = (int64_t*)(blk + off); off += sizeof(int64_t); if (need_flags & DA_NEED_SUM) { - sc_acc[w].sum = (da_val_t*)scratch_calloc(&sc_acc[w]._h_sum, - n_aggs * sizeof(da_val_t)); - if (!sc_acc[w].sum) { alloc_ok = false; break; } + sc_acc[w].sum = (da_val_t*)(blk + off); off += n_aggs * sizeof(da_val_t); } if (need_flags & DA_NEED_MIN) { - sc_acc[w].min_val = (da_val_t*)scratch_alloc(&sc_acc[w]._h_min, - n_aggs * sizeof(da_val_t)); - if (!sc_acc[w].min_val) { alloc_ok = false; break; } + sc_acc[w].min_val = (da_val_t*)(blk + off); off += n_aggs * sizeof(da_val_t); for (uint32_t a = 0; a < n_aggs; a++) { if (group_fp_type(agg_types[a])) sc_acc[w].min_val[a].f = DBL_MAX; else sc_acc[w].min_val[a].i = INT64_MAX; } } if (need_flags & DA_NEED_MAX) { - sc_acc[w].max_val = (da_val_t*)scratch_alloc(&sc_acc[w]._h_max, - n_aggs * sizeof(da_val_t)); - if (!sc_acc[w].max_val) { alloc_ok = false; break; } + sc_acc[w].max_val = (da_val_t*)(blk + off); off += n_aggs * sizeof(da_val_t); for (uint32_t a = 0; a < n_aggs; a++) { if (group_fp_type(agg_types[a])) sc_acc[w].max_val[a].f = -DBL_MAX; else sc_acc[w].max_val[a].i = INT64_MIN; } } if (need_flags & DA_NEED_SUMSQ) { - sc_acc[w].sumsq_f64 = (double*)scratch_calloc(&sc_acc[w]._h_sumsq, - n_aggs * sizeof(double)); - if (!sc_acc[w].sumsq_f64) { alloc_ok = false; break; } + sc_acc[w].sumsq_f64 = (double*)(blk + off); off += n_aggs * sizeof(double); } - sc_acc[w].count = (int64_t*)scratch_calloc(&sc_acc[w]._h_count, - 1 * sizeof(int64_t)); - if (!sc_acc[w].count) { alloc_ok = false; break; } if (sc_any_nullable) { - sc_acc[w].nn_count = (int64_t*)scratch_calloc( - &sc_acc[w]._h_nn_count, n_aggs * sizeof(int64_t)); - if (!sc_acc[w].nn_count) { alloc_ok = false; break; } + sc_acc[w].nn_count = (int64_t*)(blk + off); off += n_aggs * sizeof(int64_t); } } if (!alloc_ok) { diff --git a/test/rfl/agg/keyless_pool_accum.rfl b/test/rfl/agg/keyless_pool_accum.rfl new file mode 100644 index 000000000..5194ca657 --- /dev/null +++ b/test/rfl/agg/keyless_pool_accum.rfl @@ -0,0 +1,49 @@ +;; Keyless aggregates (no by:) over enough rows for the pooled scalar +;; path: each worker keeps one accumulator block, merged at the end. The +;; combined multi-aggregate form must agree with the single-aggregate +;; forms and with the plain vector reductions, for integer, float and +;; nullable inputs, with and without a where filter. +(set N 200000) +(set i (til N)) +(set a (as 'I64 (% (* i 7919) 1000))) +(set f (as 'F64 (% (* i 31) 977))) +(set n (as 'I64 (map (fn [k] (if (== 0 (% k 13)) 0N (% k 500))) i))) +(set g (as 'F64 (map (fn [k] (if (== 0 (% k 17)) 0N (* 0.5 (% k 300)))) i))) +(set T (table [a f n g] (list a f n g))) +(set R (select {from: T s: (sum a) c: (count a) av: (avg f) mn: (min f) mx: (max a) sd: (stddev f) v: (var a) sn: (sum n) avn: (avg n) mnn: (min n) mxn: (max n) sg: (sum g) avg: (avg g) vg: (var g)})) +(count R) -- 1 +(== (at (at R 's) 0) (sum a)) -- true +(== (at (at R 'c) 0) (count a)) -- true +(== (at (at R 'av) 0) (avg f)) -- true +(== (at (at R 'mn) 0) (min f)) -- true +(== (at (at R 'mx) 0) (max a)) -- true +(< (abs (- (at (at R 'sd) 0) (stddev f))) 1e-9) -- true +(< (abs (- (at (at R 'v) 0) (var a))) 1e-6) -- true +(== (at (at R 'sn) 0) (sum n)) -- true +(== (at (at R 'avn) 0) (avg n)) -- true +(== (at (at R 'mnn) 0) (min n)) -- true +(== (at (at R 'mxn) 0) (max n)) -- true +(== (at (at R 'sg) 0) (sum g)) -- true +(< (abs (- (at (at R 'avg) 0) (avg g))) 1e-9) -- true +(< (abs (- (at (at R 'vg) 0) (var g))) 1e-6) -- true +;; the single-aggregate forms take the specialised tight loops; they must +;; match the combined form +(== (at (at (select {from: T s: (sum a)}) 's) 0) (at (at R 's) 0)) -- true +(== (at (at (select {from: T av: (avg f)}) 'av) 0) (at (at R 'av) 0)) -- true +(== (at (at (select {from: T c: (count n)}) 'c) 0) (count n)) -- true +;; with a where filter (row selection through the same accumulators) +(set W (select {from: T s: (sum a) c: (count a) av: (avg f) mn: (min n) mx: (max g) sn: (sum n) where: (> a 500)})) +(set ORA (select {from: T a: a f: f n: n g: g where: (> a 500)})) +(== (at (at W 's) 0) (sum (at ORA 'a))) -- true +(== (at (at W 'c) 0) (count (at ORA 'a))) -- true +(== (at (at W 'av) 0) (avg (at ORA 'f))) -- true +(== (at (at W 'mn) 0) (min (at ORA 'n))) -- true +(== (at (at W 'mx) 0) (max (at ORA 'g))) -- true +(== (at (at W 'sn) 0) (sum (at ORA 'n))) -- true +;; many aggregates at once (the per-worker block scales with the count) +(set B (select {from: T a1: (sum a) a2: (sum f) a3: (sum n) a4: (sum g) a5: (min a) a6: (min f) a7: (max n) a8: (max g) a9: (avg a) a10: (avg f) a11: (count a) a12: (var f) a13: (stddev a)})) +(== (at (at B 'a1) 0) (sum a)) -- true +(== (at (at B 'a4) 0) (sum g)) -- true +(== (at (at B 'a7) 0) (max n)) -- true +(== (at (at B 'a10) 0) (avg f)) -- true +(< (abs (- (at (at B 'a13) 0) (stddev a))) 1e-9) -- true From 6d771e3d35ce78add94a7642763b856a6bbdde45 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Fri, 18 Sep 2026 00:19:14 +0300 Subject: [PATCH 06/20] perf(sym): like and strlen read a FILE domain's entries off the mapping instead of materialising atoms MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/ops/fused_pred.c | 38 +++++--- src/ops/fused_pred.h | 6 ++ src/ops/group.c | 16 ++++ src/ops/internal.h | 1 + src/ops/string.c | 100 ++++++++++++++++---- src/table/domain.c | 35 ++++++- src/table/domain.h | 24 +++++ test/rfl/symbol/file_domain_like_strlen.rfl | 68 +++++++++++++ test/test_domain.c | 42 ++++++++ 9 files changed, 298 insertions(+), 32 deletions(-) create mode 100644 test/rfl/symbol/file_domain_like_strlen.rfl diff --git a/src/ops/fused_pred.c b/src/ops/fused_pred.c index ac5d5ee75..391d741a9 100644 --- a/src/ops/fused_pred.c +++ b/src/ops/fused_pred.c @@ -450,12 +450,17 @@ void fp_eval_cmp(const fp_cmp_t* p, int64_t start, int64_t end, } uint8_t state = lut[sid]; if (!state) { - ray_t* s = sym_strings ? sym_strings[sid] - : ray_sym_domain_str(like_dom, (int64_t)sid); + const char* sp = NULL; + size_t sl = 0; + if (p->like_raw_ok && (int64_t)sid < p->like_raw.count) { + sp = ray_sym_domain_raw_str(&p->like_raw, (int64_t)sid, &sl); + } else { + ray_t* s = sym_strings ? sym_strings[sid] + : ray_sym_domain_str(like_dom, (int64_t)sid); + if (s) { sp = ray_str_ptr(s); sl = ray_str_len(s); } + } uint8_t match = 0; - if (s) { - const char* sp = ray_str_ptr(s); - size_t sl = ray_str_len(s); + if (sp) { match = use_simple ? (uint8_t)ray_glob_match_compiled(&p->pat_compiled, sp, sl) : (uint8_t)ray_glob_match(sp, sl, p->pat_str, p->pat_len); @@ -607,13 +612,18 @@ static inline uint8_t fp_eval_cmp_one(const fp_cmp_t* p, int64_t row) { uint8_t state = p->like_lut[sid]; if (!state) { /* NULL sym_strings ⇒ FILE-domain column (see fp_eval_cmp) */ - ray_t* s = p->like_sym_strings - ? p->like_sym_strings[sid] - : ray_sym_domain_str(ray_sym_vec_domain(p->col_obj), (int64_t)sid); + const char* sp = NULL; + size_t sl = 0; + if (p->like_raw_ok && (int64_t)sid < p->like_raw.count) { + sp = ray_sym_domain_raw_str(&p->like_raw, (int64_t)sid, &sl); + } else { + ray_t* s = p->like_sym_strings + ? p->like_sym_strings[sid] + : ray_sym_domain_str(ray_sym_vec_domain(p->col_obj), (int64_t)sid); + if (s) { sp = ray_str_ptr(s); sl = ray_str_len(s); } + } uint8_t match = 0; - if (s) { - const char* sp = ray_str_ptr(s); - size_t sl = ray_str_len(s); + if (sp) { match = (p->pat_compiled.shape != RAY_GLOB_SHAPE_NONE) ? (uint8_t)ray_glob_match_compiled(&p->pat_compiled, sp, sl) : (uint8_t)ray_glob_match(sp, sl, p->pat_str, p->pat_len); @@ -825,6 +835,8 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, out->like_lut = lut; out->like_lut_count = (uint32_t)dn; out->like_sym_strings = NULL; /* resolve via col_obj's domain */ + out->like_dom = ray_sym_vec_domain(col); + out->like_raw_ok = ray_sym_domain_raw_pin(out->like_dom, &out->like_raw) ? 1 : 0; } } out->cval_in_dict = 1; @@ -1042,6 +1054,10 @@ int fp_compile_pred(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, void fp_pred_cleanup(fp_pred_t* p) { if (!p) return; for (uint8_t i = 0; i < p->n_children; i++) { + if (p->children[i].like_raw_ok) { + ray_sym_domain_raw_unpin(p->children[i].like_dom); + p->children[i].like_raw_ok = 0; + } if (p->children[i].aux_hdr) { scratch_free(p->children[i].aux_hdr); p->children[i].aux_hdr = NULL; diff --git a/src/ops/fused_pred.h b/src/ops/fused_pred.h index 89c7c0be2..0b16ce812 100644 --- a/src/ops/fused_pred.h +++ b/src/ops/fused_pred.h @@ -1,3 +1,4 @@ +#include "table/domain.h" /* * Copyright (c) 2025-2026 Anton Kundenko * All rights reserved. @@ -77,6 +78,11 @@ typedef struct { uint8_t* like_lut; uint32_t like_lut_count; ray_t** like_sym_strings; + /* FILE-domain column, pinned at compile: entries of the file prefix + * read straight from the mapping (see ray_sym_domain_raw_pin). */ + ray_sym_domain_raw_t like_raw; + uint8_t like_raw_ok; + struct ray_sym_domain_s* like_dom; } fp_cmp_t; typedef struct { diff --git a/src/ops/group.c b/src/ops/group.c index f6ae68a3b..e4652f25c 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -11697,6 +11697,22 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if ((agg_kind == OP_SUM || agg_kind == OP_AVG) && try_strlen_sumavg_input(g, tbl, agg_input_op, &agg_vecs[a])) { + /* A SYM column on a FILE domain: the per-row string resolve + * would materialise an atom per distinct symbol under the + * domain lock. Read the lengths off the mapping once + * (parallel, no atoms) and aggregate the plain I64 vector. */ + ray_t* sc = agg_vecs[a]; + if (sc->type == RAY_SYM && ray_sym_vec_domain(sc) != ray_sym_runtime_domain()) { + ray_t* lens = ray_vec_new(RAY_I64, sc->len); + if (lens && !RAY_IS_ERR(lens)) { + lens->len = sc->len; + ray_sym_strlen_into(sc, lens); + agg_vecs[a] = lens; + agg_owned[a] = 1; + continue; + } + if (lens) ray_error_free(lens); + } agg_strlen[a] = 1; continue; } diff --git a/src/ops/internal.h b/src/ops/internal.h index 60da88417..6465b0a1d 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -1606,6 +1606,7 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op); ray_t* exec_ilike(ray_graph_t* g, ray_op_t* op); ray_t* exec_string_unary(ray_graph_t* g, ray_op_t* op); ray_t* exec_strlen(ray_graph_t* g, ray_op_t* op); +void ray_sym_strlen_into(ray_t* input, ray_t* result); /* string.c */ ray_t* exec_substr(ray_graph_t* g, ray_op_t* op); ray_t* exec_replace(ray_graph_t* g, ray_op_t* op); ray_t* exec_concat(ray_graph_t* g, ray_op_t* op); diff --git a/src/ops/string.c b/src/ops/string.c index 84f36e5bf..1d0665275 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -54,6 +54,11 @@ typedef struct { * resolve each sid through `dom` instead. The LUT is sized by * that domain's count at setup (fused_group.c precedent). */ struct ray_sym_domain_s* dom; + /* FILE domain, pinned: the file prefix read straight from the mapping + * (no atom materialisation, no lock); positions past raw.count still + * resolve through the domain. */ + ray_sym_domain_raw_t raw; + bool raw_ok; uint8_t* seen; uint8_t* lut; const ray_glob_compiled_t* pc; @@ -354,11 +359,17 @@ static void like_resolve_fn(void* ctx, uint32_t worker_id, like_resolve_ctx_t* x = (like_resolve_ctx_t*)ctx; for (int64_t sid = start; sid < end; sid++) { if (!x->seen[sid]) continue; - ray_t* str = x->sym_strings ? x->sym_strings[sid] - : ray_sym_domain_str(x->dom, sid); - if (!str) { x->lut[sid] = 0; continue; } - const char* sp = ray_str_ptr(str); - size_t sl = ray_str_len(str); + const char* sp; + size_t sl; + if (x->raw_ok && sid < x->raw.count) { + sp = ray_sym_domain_raw_str(&x->raw, sid, &sl); + } else { + ray_t* str = x->sym_strings ? x->sym_strings[sid] + : ray_sym_domain_str(x->dom, sid); + if (!str) { x->lut[sid] = 0; continue; } + sp = ray_str_ptr(str); + sl = ray_str_len(str); + } x->lut[sid] = (x->use_simple ? ray_glob_match_compiled(x->pc, sp, sl) : ray_glob_match(sp, sl, x->pat_str, x->pat_len)) @@ -468,11 +479,13 @@ static void exec_like_parted_sym(ray_t* input, uint8_t* dst, .pc = pc, .use_simple = use_simple, .pat_str = pat_str, .pat_len = pat_len, }; + rctx.raw_ok = dom ? ray_sym_domain_raw_pin(dom, &rctx.raw) : false; if (pool && (int64_t)dict_n >= 16384) { ray_pool_dispatch(pool, like_resolve_fn, &rctx, (int64_t)dict_n); } else { like_resolve_fn(&rctx, 0, 0, (int64_t)dict_n); } + if (rctx.raw_ok) ray_sym_domain_raw_unpin(dom); int64_t out_off = 0; for (int64_t s = 0; s < input->len; s++) { @@ -708,11 +721,13 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { .pc = &pc, .use_simple = use_simple, .pat_str = pat_str, .pat_len = pat_len, }; + rctx.raw_ok = dom ? ray_sym_domain_raw_pin(dom, &rctx.raw) : false; if (pool && (int64_t)dict_n >= 16384) { ray_pool_dispatch(pool, like_resolve_fn, &rctx, (int64_t)dict_n); } else { like_resolve_fn(&rctx, 0, 0, (int64_t)dict_n); } + if (rctx.raw_ok) ray_sym_domain_raw_unpin(dom); /* Pass 3: row projection — gather lut[sid] into the per-row * bool dst. Parallelised because it's a 5 M-row pass (~5 ms @@ -868,20 +883,26 @@ ray_t* exec_ilike(ray_graph_t* g, ray_op_t* op) { seen = (uint8_t*)scratch_calloc(&seen_hdr, (size_t)dict_n); } if (lut && seen) { + ray_sym_domain_raw_t raw; + bool raw_ok = ray_sym_domain_raw_pin(dom, &raw); for (int64_t i = 0; i < len; i++) { int64_t sid = ray_read_sym(base, i, in_type, input->attrs); if ((uint64_t)sid >= (uint64_t)dict_n) { dst[i] = 0; continue; } if (!seen[sid]) { - ray_t* s = ray_sym_domain_str(dom, sid); - if (!s) { lut[sid] = 0; } - else { - lut[sid] = ray_glob_match_ci(ray_str_ptr(s), ray_str_len(s), - pat_str, pat_len) ? 1 : 0; + const char* sp = NULL; + size_t sl = 0; + if (raw_ok && sid < raw.count) { + sp = ray_sym_domain_raw_str(&raw, sid, &sl); + } else { + ray_t* s = ray_sym_domain_str(dom, sid); + if (s) { sp = ray_str_ptr(s); sl = ray_str_len(s); } } + lut[sid] = sp ? (ray_glob_match_ci(sp, sl, pat_str, pat_len) ? 1 : 0) : 0; seen[sid] = 1; } dst[i] = lut[sid]; } + if (raw_ok) ray_sym_domain_raw_unpin(dom); scratch_free(lut_hdr); scratch_free(seen_hdr); } else { @@ -980,6 +1001,54 @@ ray_t* exec_string_unary(ray_graph_t* g, ray_op_t* op) { } /* LENGTH — SYM → I64 */ +typedef struct { + ray_t* input; + int64_t* dst; + struct ray_sym_domain_s* dom; + ray_sym_domain_raw_t raw; + bool raw_ok; + _Atomic(int) any_null; +} strlen_sym_ctx_t; +static void strlen_sym_task(void* vctx, uint32_t worker_id, int64_t lo, int64_t hi) { + (void)worker_id; + strlen_sym_ctx_t* c = (strlen_sym_ctx_t*)vctx; + ray_t* input = c->input; + const void* base = ray_data(input); + bool any_null = false; + for (int64_t i = lo; i < hi; i++) { + if (ray_vec_is_null(input, i)) { c->dst[i] = NULL_I64; any_null = true; continue; } + int64_t sid = ray_read_sym(base, i, input->type, input->attrs); + if (c->raw_ok && sid >= 0 && sid < c->raw.count) { + size_t sl; + (void)ray_sym_domain_raw_str(&c->raw, sid, &sl); + c->dst[i] = (int64_t)sl; + } else { + const char* sp; size_t sl; + sym_elem(input, i, &sp, &sl); + c->dst[i] = (int64_t)sl; + } + } + if (any_null) atomic_store_explicit(&c->any_null, 1, memory_order_relaxed); +} +/* Lengths of a SYM vector into a pre-sized I64 vector. A FILE domain's + * entries carry their length as a u32 prefix in the mapping — read that by + * position, no atom, no lock, in parallel; anything else (runtime domain, + * appended positions) resolves the way it always did. */ +void ray_sym_strlen_into(ray_t* input, ray_t* result) { + int64_t len = input->len; + strlen_sym_ctx_t c = { .input = input, .dst = (int64_t*)ray_data(result), .raw_ok = false }; + c.dom = ray_sym_vec_domain(input); + c.raw_ok = c.dom ? ray_sym_domain_raw_pin(c.dom, &c.raw) : false; + atomic_store_explicit(&c.any_null, 0, memory_order_relaxed); + ray_pool_t* pool = ray_pool_get(); + if (pool && len >= RAY_PARALLEL_THRESHOLD) + ray_pool_dispatch(pool, strlen_sym_task, &c, len); + else + strlen_sym_task(&c, 0, 0, len); + if (c.raw_ok) ray_sym_domain_raw_unpin(c.dom); + if (atomic_load_explicit(&c.any_null, memory_order_relaxed)) + result->attrs |= RAY_ATTR_HAS_NULLS; +} ray_t* exec_strlen(ray_graph_t* g, ray_op_t* op) { ray_t* input = exec_node(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; @@ -1002,16 +1071,7 @@ ray_t* exec_strlen(ray_graph_t* g, ray_op_t* op) { } } } else { - for (int64_t i = 0; i < len; i++) { - if (ray_vec_is_null(input, i)) { - dst[i] = NULL_I64; - result->attrs |= RAY_ATTR_HAS_NULLS; - } else { - const char* sp; size_t sl; - sym_elem(input, i, &sp, &sl); - dst[i] = (int64_t)sl; - } - } + ray_sym_strlen_into(input, result); } ray_release(input); return result; diff --git a/src/table/domain.c b/src/table/domain.c index 22f085d24..b12254130 100644 --- a/src/table/domain.c +++ b/src/table/domain.c @@ -146,6 +146,10 @@ struct ray_sym_domain_s { * used to materialize atoms[pos] on demand from the mmap bytes. * malloc'd; NULL when base_count == 0. */ size_t* offsets; + /* Raw readers pinned on (map, offsets) — see ray_sym_domain_raw_pin. + * An extend raises raw_swapping, drains raw_readers, then swaps. */ + _Atomic(int32_t) raw_readers; + _Atomic(int32_t) raw_swapping; /* FILE, lazy: position → runtime intern id. Built under g_dom_lock * (the build INTERNS the vocabulary into the global table — @@ -414,7 +418,11 @@ static bool dom_extend_from_file_locked(ray_sym_domain_t* d, size_t st_size) { ray_sys_free(fresh); /* fresh slot array unused — narr carries the prefix */ /* Swap in the new offsets + map; the old map's bytes are no - * longer referenced (prefix atoms are arena-copied). */ + * longer referenced (prefix atoms are arena-copied) — once + * every raw reader pinned on them has left. */ + atomic_store_explicit(&d->raw_swapping, 1, memory_order_seq_cst); + while (atomic_load_explicit(&d->raw_readers, memory_order_seq_cst) != 0) + RAY_CPU_RELAX(); ray_sys_free(d->offsets); d->offsets = fresh_offsets; void* old_map = d->map; @@ -430,6 +438,7 @@ static bool dom_extend_from_file_locked(ray_sym_domain_t* d, size_t st_size) { d->disk_size = st_size; if (old_map) ray_vm_unmap_file(old_map, old_map_size); + atomic_store_explicit(&d->raw_swapping, 0, memory_order_release); /* Reverse index + LUT now cover a stale prefix: drop both. * A retire-OOM here would keep the stale LUT published over @@ -496,6 +505,8 @@ static ray_sym_domain_t* dom_open_impl(const char* path, bool create) { if (!d) { ray_sys_free(rpath); return NULL; } d->kind = DOM_FILE; d->rc = 1; + atomic_store_explicit(&d->raw_readers, 0, memory_order_relaxed); + atomic_store_explicit(&d->raw_swapping, 0, memory_order_relaxed); d->path = rpath; /* String atoms (lazy file slots + runtime-appended interns) live here, * off the per-thread buddy heap. 64 KB chunks. */ @@ -611,6 +622,28 @@ ray_t* ray_sym_domain_str(ray_sym_domain_t* dom, int64_t pos) { return a; } +bool ray_sym_domain_raw_pin(ray_sym_domain_t* dom, ray_sym_domain_raw_t* out) { + if (!dom || !out || dom->kind == DOM_RUNTIME) return false; + /* Dekker pair with the extend: our increment must be visible to an + * extend that has raised raw_swapping, or we must see the flag. */ + atomic_fetch_add_explicit(&dom->raw_readers, 1, memory_order_seq_cst); + if (atomic_load_explicit(&dom->raw_swapping, memory_order_seq_cst)) { + atomic_fetch_sub_explicit(&dom->raw_readers, 1, memory_order_seq_cst); + return false; + } + out->map = (const unsigned char*)dom->map; + out->offsets = dom->offsets; + out->count = dom->base_count; + if (!out->map || !out->offsets || out->count <= 0) { + atomic_fetch_sub_explicit(&dom->raw_readers, 1, memory_order_seq_cst); + return false; + } + return true; +} +void ray_sym_domain_raw_unpin(ray_sym_domain_t* dom) { + if (!dom || dom->kind == DOM_RUNTIME) return; + atomic_fetch_sub_explicit(&dom->raw_readers, 1, memory_order_seq_cst); +} /* Empty-vocabulary FILE domains get a distinct non-NULL LUT so callers * can branch on NULL == "runtime domain, ids pass through". Never * indexed: every position is out of range when count == 0. */ diff --git a/src/table/domain.h b/src/table/domain.h index 474c610d8..cbb9ebf81 100644 --- a/src/table/domain.h +++ b/src/table/domain.h @@ -76,6 +76,7 @@ #include #include +#include typedef struct ray_sym_domain_s ray_sym_domain_t; @@ -108,6 +109,29 @@ void ray_sym_domain_release(ray_sym_domain_t* dom); * domain's lifetime, do not release. */ ray_t* ray_sym_domain_str(ray_sym_domain_t* dom, int64_t pos); +/* Raw vocabulary access for a FILE domain: the bytes of the entries the + * file holds, read straight from the mapping — no atom, no lock. Pin the + * mapping first; while any reader is pinned a concurrent extend (the file + * grew under another opener) waits before swapping the map. Returns + * false for the runtime domain, an empty file, or a swap in progress — + * the caller then resolves through ray_sym_domain_str as before. Only + * positions below `count` (the file prefix) are readable this way; + * runtime-appended positions keep going through ray_sym_domain_str. */ +typedef struct { + const unsigned char* map; + const size_t* offsets; + int64_t count; +} ray_sym_domain_raw_t; +bool ray_sym_domain_raw_pin(ray_sym_domain_t* dom, ray_sym_domain_raw_t* out); +void ray_sym_domain_raw_unpin(ray_sym_domain_t* dom); +static inline const char* ray_sym_domain_raw_str(const ray_sym_domain_raw_t* r, + int64_t pos, size_t* len) { + const unsigned char* rec = r->map + r->offsets[pos]; + uint32_t l; memcpy(&l, rec, 4); + *len = l; + return (const char*)rec + 4; +} + /* Position of `str` in the domain, or -1 if absent. * FILE: builds the reverse index on first call (O(|vocabulary|)). */ int64_t ray_sym_domain_find(ray_sym_domain_t* dom, const char* str, size_t len); diff --git a/test/rfl/symbol/file_domain_like_strlen.rfl b/test/rfl/symbol/file_domain_like_strlen.rfl new file mode 100644 index 000000000..dc4bd9569 --- /dev/null +++ b/test/rfl/symbol/file_domain_like_strlen.rfl @@ -0,0 +1,68 @@ +;; like / strlen over a SYM column whose ids live in a FILE domain (a +;; splayed table read back from disk). The engine reads the entries' bytes +;; and lengths straight off the mapped vocabulary instead of materialising +;; an atom per symbol; every answer must equal the same computation over +;; the strings themselves. Sizes past the parallel thresholds (like 100000 +;; rows, strlen 65536) so the pooled paths run. +(.sys.exec "rm -rf /tmp/rfl_fdom_like/") -- 0 +(set N 120000) +(set i (til N)) +(set hosts (map (fn [k] (format "h%.example.com" k)) (til 300))) +(set u (as 'SYMBOL (map (fn [k] (if (== 0 (% k 41)) (format "http://%/google/%" (at hosts (% k 300)) k) (format "http://%/p/%/%" (at hosts (% (* 31 k) 300)) (% k 977) k))) i))) +(set sp (as 'SYMBOL (map (fn [k] (if (== 0 (% k 3)) "" (format "phrase % %" (% (* k 7) 5000) (% k 13)))) i))) +(set g (as 'I64 (% (* i 7919) 500))) +(set T (table [u sp g] (list u sp g))) +(.db.splayed.set "/tmp/rfl_fdom_like/" T) +(set F (.db.splayed.get "/tmp/rfl_fdom_like/")) +(count F) -- 120000 +(== (type (at F 'u)) 'SYM) -- true +;; string oracle: the same values as plain strings +(set US (as 'STR (at F 'u))) +(set SPS (as 'STR (at F 'sp))) +;; pattern *google* +(== (count (select {from: F where: (like u "*google*")})) (sum (as 'I64 (like US "*google*")))) -- true +(all (== (like (at F 'u) "*google*") (like US "*google*"))) -- true +(== (count (select {from: F u: u where: (like u "*google*") asc: g take: 25})) (min 25 (sum (as 'I64 (like US "*google*"))))) -- true +;; pattern http://h1* +(== (count (select {from: F where: (like u "http://h1*")})) (sum (as 'I64 (like US "http://h1*")))) -- true +(all (== (like (at F 'u) "http://h1*") (like US "http://h1*"))) -- true +(== (count (select {from: F u: u where: (like u "http://h1*") asc: g take: 25})) (min 25 (sum (as 'I64 (like US "http://h1*"))))) -- true +;; pattern */p/5/* +(== (count (select {from: F where: (like u "*/p/5/*")})) (sum (as 'I64 (like US "*/p/5/*")))) -- true +(all (== (like (at F 'u) "*/p/5/*") (like US "*/p/5/*"))) -- true +(== (count (select {from: F u: u where: (like u "*/p/5/*") asc: g take: 25})) (min 25 (sum (as 'I64 (like US "*/p/5/*"))))) -- true +;; pattern http://h12.example.com/google/492 +(== (count (select {from: F where: (like u "http://h12.example.com/google/492")})) (sum (as 'I64 (like US "http://h12.example.com/google/492")))) -- true +(all (== (like (at F 'u) "http://h12.example.com/google/492") (like US "http://h12.example.com/google/492"))) -- true +(== (count (select {from: F u: u where: (like u "http://h12.example.com/google/492") asc: g take: 25})) (min 25 (sum (as 'I64 (like US "http://h12.example.com/google/492"))))) -- true +;; pattern * +(== (count (select {from: F where: (like u "*")})) (sum (as 'I64 (like US "*")))) -- true +(all (== (like (at F 'u) "*") (like US "*"))) -- true +(== (count (select {from: F u: u where: (like u "*") asc: g take: 25})) (min 25 (sum (as 'I64 (like US "*"))))) -- true +;; pattern nomatch* +(== (count (select {from: F where: (like u "nomatch*")})) (sum (as 'I64 (like US "nomatch*")))) -- true +(all (== (like (at F 'u) "nomatch*") (like US "nomatch*"))) -- true +(== (count (select {from: F u: u where: (like u "nomatch*") asc: g take: 25})) (min 25 (sum (as 'I64 (like US "nomatch*"))))) -- true + +;; suffix and exact patterns: sensitive to the last byte of every entry +(== (count (select {from: F where: (like u "*/google/492")})) 1) -- true +(== (count (select {from: F where: (like u "http://h192.example.com/google/492")})) 1) -- true +(== (count (select {from: F where: (like u "*9")})) (sum (as 'I64 (like US "*9")))) -- true +(all (== (like (at F 'u) "*9") (like US "*9"))) -- true +(all (== (like (at F 'u) "*/google/492") (like US "*/google/492"))) -- true +(== (count (select {from: F u: u where: (like u "*9") asc: g take: 25})) (min 25 (sum (as 'I64 (like US "*9"))))) -- true +;; like on the low-cardinality column with empties +(all (== (like (at F 'sp) "phrase 4*") (like SPS "phrase 4*"))) -- true +(== (count (select {from: F where: (like sp "phrase 4*")})) (sum (as 'I64 (like SPS "phrase 4*")))) -- true +;; strlen: plain and inside an aggregate +(all (== (strlen (at F 'u)) (strlen US))) -- true +(all (== (strlen (at F 'sp)) (strlen SPS))) -- true +(set A (select {from: F by: g l: (avg (strlen u)) s: (sum (strlen sp)) c: (count u) where: (!= u "")})) +(set O (select {from: (table [g lu ls] (list (at F 'g) (strlen US) (strlen SPS))) by: g l: (avg lu) s: (sum ls) c: (count lu)})) +(count A) -- 500 +(all (== (at (xasc A 'g) 'l) (at (xasc O 'g) 'l))) -- true +(all (== (at (xasc A 'g) 's) (at (xasc O 'g) 's))) -- true +(all (== (at (xasc A 'g) 'c) (at (xasc O 'g) 'c))) -- true +;; the where predicate over the file-domain column still filters +(== (count (select {from: F where: (and (like u "*google*") (!= sp ""))})) (sum (as 'I64 (and (like US "*google*") (!= SPS ""))))) -- true +(.sys.exec "rm -rf /tmp/rfl_fdom_like/") -- 0 diff --git a/test/test_domain.c b/test/test_domain.c index 2f633c438..79f528a96 100644 --- a/test/test_domain.c +++ b/test/test_domain.c @@ -1683,6 +1683,47 @@ static test_result_t test_domain_str_eager_lockfree(void) { PASS(); } +/* Raw vocabulary access: a pinned FILE domain hands out each file entry's + * bytes and length straight from the mapping, equal to the materialised + * atom; the runtime singleton refuses; pins nest and release. */ +static test_result_t test_domain_raw_pin(void) { + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + int64_t id_a = ray_sym_intern("raw_alpha", 9); + int64_t id_b = ray_sym_intern("raw_beta_longer_entry", 21); + (void)id_a; (void)id_b; + uint32_t count_at_save = ray_sym_count(); + TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + ray_sym_domain_raw_t raw; + TEST_ASSERT_FALSE(ray_sym_domain_raw_pin(ray_sym_runtime_domain(), &raw)); + TEST_ASSERT(ray_sym_domain_raw_pin(dom, &raw), "pin a file domain"); + TEST_ASSERT_EQ_I(raw.count, (int64_t)count_at_save); + /* Nested pin from another reader is fine. */ + ray_sym_domain_raw_t raw2; + TEST_ASSERT(ray_sym_domain_raw_pin(dom, &raw2), "second pin"); + for (int64_t p = 0; p < raw.count; p++) { + size_t rl = 0; + const char* rp = ray_sym_domain_raw_str(&raw, p, &rl); + ray_t* s = ray_sym_domain_str(dom, p); + TEST_ASSERT_NOT_NULL(s); + TEST_ASSERT_EQ_U(rl, ray_str_len(s)); + TEST_ASSERT_MEM_EQ(rl, rp, ray_str_ptr(s)); + } + ray_sym_domain_raw_unpin(dom); + ray_sym_domain_raw_unpin(dom); + /* An entry appended after open is past the file prefix: not raw. */ + int64_t pos_new = ray_sym_domain_intern(dom, "raw_appended", 12); + TEST_ASSERT(pos_new >= raw.count, "appended entry sits past the mapped prefix"); + TEST_ASSERT(ray_sym_domain_raw_pin(dom, &raw), "pin again"); + TEST_ASSERT_EQ_I(raw.count, (int64_t)count_at_save); + ray_sym_domain_raw_unpin(dom); + ray_sym_domain_release(dom); + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + PASS(); +} /* Runtime-id LUT: NULL for the runtime singleton; for a FILE domain a * position-indexed array of runtime intern ids (round-trips strings), * built once (idempotent: same pointer). Divergent fixture proves the @@ -1910,6 +1951,7 @@ const test_entry_t domain_entries[] = { { "domain/asof_join_across_domains", test_domain_asof_join_across_domains, domain_rt_setup, domain_rt_teardown }, { "domain/parted_flatten_adopts", test_domain_parted_flatten_adopts, domain_rt_setup, domain_rt_teardown }, { "domain/str_eager_lockfree", test_domain_str_eager_lockfree, domain_setup, domain_teardown }, + { "domain/raw_pin", test_domain_raw_pin, domain_setup, domain_teardown }, { "domain/runtime_lut", test_domain_runtime_lut, domain_rt_setup, domain_rt_teardown }, { "domain/open_position0_validation", test_domain_open_position0_validation, domain_setup, domain_teardown }, { "domain/dict_upsert_file_keys", test_domain_dict_upsert_file_keys, domain_rt_setup, domain_rt_teardown }, From c589aaa8e6f9f8c0faece7a4c6404e6593a32496 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Fri, 18 Sep 2026 13:24:46 +0300 Subject: [PATCH 07/20] fix(sym): publish the raw vocabulary snapshot and retire the old mapping instead of draining readers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/ops/fused_pred.h | 2 +- src/ops/group.c | 6 +- src/ops/internal.h | 2 +- src/ops/string.c | 18 +++-- src/table/domain.c | 90 ++++++++++++++------- src/table/domain.h | 18 +++-- test/rfl/symbol/file_domain_like_strlen.rfl | 7 ++ test/test_domain.c | 34 ++++++++ 8 files changed, 130 insertions(+), 47 deletions(-) diff --git a/src/ops/fused_pred.h b/src/ops/fused_pred.h index 0b16ce812..d26ee6b24 100644 --- a/src/ops/fused_pred.h +++ b/src/ops/fused_pred.h @@ -1,4 +1,3 @@ -#include "table/domain.h" /* * Copyright (c) 2025-2026 Anton Kundenko * All rights reserved. @@ -28,6 +27,7 @@ #include "rayforce.h" #include "ops/internal.h" #include "ops/glob.h" +#include "table/domain.h" #define FP_PRED_MAX_CHILDREN 8 diff --git a/src/ops/group.c b/src/ops/group.c index e4652f25c..e264d322c 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -11700,13 +11700,15 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, /* A SYM column on a FILE domain: the per-row string resolve * would materialise an atom per distinct symbol under the * domain lock. Read the lengths off the mapping once - * (parallel, no atoms) and aggregate the plain I64 vector. */ + * (parallel, no atoms) and aggregate the plain I64 vector. A + * null cell (the empty symbol) is a null length, which the + * accumulate skips exactly as the per-row path skips the row. */ ray_t* sc = agg_vecs[a]; if (sc->type == RAY_SYM && ray_sym_vec_domain(sc) != ray_sym_runtime_domain()) { ray_t* lens = ray_vec_new(RAY_I64, sc->len); if (lens && !RAY_IS_ERR(lens)) { lens->len = sc->len; - ray_sym_strlen_into(sc, lens); + ray_sym_strlen_into(sc, lens, false); agg_vecs[a] = lens; agg_owned[a] = 1; continue; diff --git a/src/ops/internal.h b/src/ops/internal.h index 6465b0a1d..96003f9aa 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -1606,7 +1606,7 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op); ray_t* exec_ilike(ray_graph_t* g, ray_op_t* op); ray_t* exec_string_unary(ray_graph_t* g, ray_op_t* op); ray_t* exec_strlen(ray_graph_t* g, ray_op_t* op); -void ray_sym_strlen_into(ray_t* input, ray_t* result); /* string.c */ +void ray_sym_strlen_into(ray_t* input, ray_t* result, bool null_as_zero); /* string.c */ ray_t* exec_substr(ray_graph_t* g, ray_op_t* op); ray_t* exec_replace(ray_graph_t* g, ray_op_t* op); ray_t* exec_concat(ray_graph_t* g, ray_op_t* op); diff --git a/src/ops/string.c b/src/ops/string.c index 1d0665275..53e052832 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -1007,6 +1007,7 @@ typedef struct { struct ray_sym_domain_s* dom; ray_sym_domain_raw_t raw; bool raw_ok; + bool null_as_zero; /* group aggregates count a null cell as length 0 */ _Atomic(int) any_null; } strlen_sym_ctx_t; static void strlen_sym_task(void* vctx, uint32_t worker_id, int64_t lo, int64_t hi) { @@ -1016,7 +1017,10 @@ static void strlen_sym_task(void* vctx, uint32_t worker_id, int64_t lo, int64_t const void* base = ray_data(input); bool any_null = false; for (int64_t i = lo; i < hi; i++) { - if (ray_vec_is_null(input, i)) { c->dst[i] = NULL_I64; any_null = true; continue; } + if (ray_vec_is_null(input, i)) { + if (c->null_as_zero) { c->dst[i] = 0; continue; } + c->dst[i] = NULL_I64; any_null = true; continue; + } int64_t sid = ray_read_sym(base, i, input->type, input->attrs); if (c->raw_ok && sid >= 0 && sid < c->raw.count) { size_t sl; @@ -1033,10 +1037,14 @@ static void strlen_sym_task(void* vctx, uint32_t worker_id, int64_t lo, int64_t /* Lengths of a SYM vector into a pre-sized I64 vector. A FILE domain's * entries carry their length as a u32 prefix in the mapping — read that by * position, no atom, no lock, in parallel; anything else (runtime domain, - * appended positions) resolves the way it always did. */ -void ray_sym_strlen_into(ray_t* input, ray_t* result) { + * appended positions) resolves the way it always did. null_as_zero: a + * null cell (the empty symbol) becomes 0 with no HAS_NULLS, the contract of + * the group path's strlen-on-SYM aggregate; otherwise NULL_I64 as the + * vector op returns. */ +void ray_sym_strlen_into(ray_t* input, ray_t* result, bool null_as_zero) { int64_t len = input->len; - strlen_sym_ctx_t c = { .input = input, .dst = (int64_t*)ray_data(result), .raw_ok = false }; + strlen_sym_ctx_t c = { .input = input, .dst = (int64_t*)ray_data(result), .raw_ok = false, + .null_as_zero = null_as_zero }; c.dom = ray_sym_vec_domain(input); c.raw_ok = c.dom ? ray_sym_domain_raw_pin(c.dom, &c.raw) : false; atomic_store_explicit(&c.any_null, 0, memory_order_relaxed); @@ -1071,7 +1079,7 @@ ray_t* exec_strlen(ray_graph_t* g, ray_op_t* op) { } } } else { - ray_sym_strlen_into(input, result); + ray_sym_strlen_into(input, result, false); } ray_release(input); return result; diff --git a/src/table/domain.c b/src/table/domain.c index b12254130..ba87c492d 100644 --- a/src/table/domain.c +++ b/src/table/domain.c @@ -104,6 +104,16 @@ typedef struct dom_retired_s { void* ptr; struct dom_retired_s* next; } dom_retired_t; +typedef struct dom_retired_map_s { + void* map; + size_t size; + struct dom_retired_map_s* next; +} dom_retired_map_t; +typedef struct dom_raw_snap_s { + const unsigned char* map; + const size_t* offsets; + int64_t count; +} dom_raw_snap_t; struct ray_sym_domain_s { uint8_t kind; /* dom_kind_t */ @@ -146,10 +156,13 @@ struct ray_sym_domain_s { * used to materialize atoms[pos] on demand from the mmap bytes. * malloc'd; NULL when base_count == 0. */ size_t* offsets; - /* Raw readers pinned on (map, offsets) — see ray_sym_domain_raw_pin. - * An extend raises raw_swapping, drains raw_readers, then swaps. */ - _Atomic(int32_t) raw_readers; - _Atomic(int32_t) raw_swapping; + /* Published raw snapshot (see ray_sym_domain_raw_pin): map, offsets and + * the file-prefix count as one immutable record. Replaced whole on + * extend; the previous record, its offsets and its mapping are retired + * (retired / retired_maps) rather than freed, so a reader holding the + * old snapshot stays valid until the domain is destroyed. */ + _Atomic(struct dom_raw_snap_s*) raw_snap; + struct dom_retired_map_s* retired_maps; /* FILE, lazy: position → runtime intern id. Built under g_dom_lock * (the build INTERNS the vocabulary into the global table — @@ -245,6 +258,21 @@ static bool dom_retire(ray_sym_domain_t* d, void* p) { d->retired = r; return true; } +/* Publish (map, offsets, count) as the domain's raw snapshot; the previous + * record is retired. Called with the file's current image in place. */ +static bool dom_publish_raw_snap(ray_sym_domain_t* d) { + dom_raw_snap_t* snap = NULL; + if (d->map && d->offsets && d->base_count > 0) { + snap = (dom_raw_snap_t*)ray_sys_alloc(sizeof(*snap)); + if (!snap) return false; + snap->map = (const unsigned char*)d->map; + snap->offsets = d->offsets; + snap->count = d->base_count; + } + dom_raw_snap_t* old = atomic_exchange_explicit(&d->raw_snap, snap, memory_order_acq_rel); + if (old) (void)dom_retire(d, old); + return true; +} /* Free a FILE domain after the last reference dropped. Caller has * already unlinked it from the cache. */ @@ -263,6 +291,13 @@ static void dom_destroy(ray_sym_domain_t* d) { r = nxt; } ray_sys_free(d->buckets); + ray_sys_free(atomic_load_explicit(&d->raw_snap, memory_order_relaxed)); + for (dom_retired_map_t* rm = d->retired_maps; rm;) { + dom_retired_map_t* nxt = rm->next; + ray_vm_unmap_file(rm->map, rm->size); + ray_sys_free(rm); + rm = nxt; + } if (d->map) ray_vm_unmap_file(d->map, d->map_size); ray_sys_free(d->path); ray_sys_free(d); @@ -417,13 +452,10 @@ static bool dom_extend_from_file_locked(ray_sym_domain_t* d, size_t st_size) { for (int64_t i = count; i < fresh_count; i++) narr[i] = NULL; ray_sys_free(fresh); /* fresh slot array unused — narr carries the prefix */ - /* Swap in the new offsets + map; the old map's bytes are no - * longer referenced (prefix atoms are arena-copied) — once - * every raw reader pinned on them has left. */ - atomic_store_explicit(&d->raw_swapping, 1, memory_order_seq_cst); - while (atomic_load_explicit(&d->raw_readers, memory_order_seq_cst) != 0) - RAY_CPU_RELAX(); - ray_sys_free(d->offsets); + /* Swap in the new offsets + map. Prefix atoms are arena + * copies, but a raw snapshot may still point at the old + * offsets and mapping: retire both instead of freeing. */ + (void)dom_retire(d, d->offsets); d->offsets = fresh_offsets; void* old_map = d->map; size_t old_map_size = d->map_size; @@ -437,8 +469,13 @@ static bool dom_extend_from_file_locked(ray_sym_domain_t* d, size_t st_size) { d->disk_count = fresh_count; d->disk_size = st_size; - if (old_map) ray_vm_unmap_file(old_map, old_map_size); - atomic_store_explicit(&d->raw_swapping, 0, memory_order_release); + if (old_map) { + dom_retired_map_t* rm = (dom_retired_map_t*)ray_sys_alloc(sizeof(*rm)); + if (rm) { rm->map = old_map; rm->size = old_map_size; rm->next = d->retired_maps; d->retired_maps = rm; } + /* no rm: the old mapping stays mapped for the process + * lifetime — never unmapped under a live snapshot */ + } + (void)dom_publish_raw_snap(d); /* Reverse index + LUT now cover a stale prefix: drop both. * A retire-OOM here would keep the stale LUT published over @@ -505,8 +542,8 @@ static ray_sym_domain_t* dom_open_impl(const char* path, bool create) { if (!d) { ray_sys_free(rpath); return NULL; } d->kind = DOM_FILE; d->rc = 1; - atomic_store_explicit(&d->raw_readers, 0, memory_order_relaxed); - atomic_store_explicit(&d->raw_swapping, 0, memory_order_relaxed); + atomic_store_explicit(&d->raw_snap, NULL, memory_order_relaxed); + d->retired_maps = NULL; d->path = rpath; /* String atoms (lazy file slots + runtime-appended interns) live here, * off the per-thread buddy heap. 64 KB chunks. */ @@ -528,6 +565,7 @@ static ray_sym_domain_t* dom_open_impl(const char* path, bool create) { d->offsets = offsets; d->atoms_cap = count; d->base_count = count; + (void)dom_publish_raw_snap(d); d->disk_count = count; d->disk_size = d->map_size; /* Position-0 reservation: every non-empty symfile must carry the @@ -624,25 +662,15 @@ ray_t* ray_sym_domain_str(ray_sym_domain_t* dom, int64_t pos) { bool ray_sym_domain_raw_pin(ray_sym_domain_t* dom, ray_sym_domain_raw_t* out) { if (!dom || !out || dom->kind == DOM_RUNTIME) return false; - /* Dekker pair with the extend: our increment must be visible to an - * extend that has raised raw_swapping, or we must see the flag. */ - atomic_fetch_add_explicit(&dom->raw_readers, 1, memory_order_seq_cst); - if (atomic_load_explicit(&dom->raw_swapping, memory_order_seq_cst)) { - atomic_fetch_sub_explicit(&dom->raw_readers, 1, memory_order_seq_cst); - return false; - } - out->map = (const unsigned char*)dom->map; - out->offsets = dom->offsets; - out->count = dom->base_count; - if (!out->map || !out->offsets || out->count <= 0) { - atomic_fetch_sub_explicit(&dom->raw_readers, 1, memory_order_seq_cst); - return false; - } + dom_raw_snap_t* snap = atomic_load_explicit(&dom->raw_snap, memory_order_acquire); + if (!snap) return false; + out->map = snap->map; + out->offsets = snap->offsets; + out->count = snap->count; return true; } void ray_sym_domain_raw_unpin(ray_sym_domain_t* dom) { - if (!dom || dom->kind == DOM_RUNTIME) return; - atomic_fetch_sub_explicit(&dom->raw_readers, 1, memory_order_seq_cst); + (void)dom; /* the snapshot outlives its readers by construction */ } /* Empty-vocabulary FILE domains get a distinct non-NULL LUT so callers * can branch on NULL == "runtime domain, ids pass through". Never diff --git a/src/table/domain.h b/src/table/domain.h index cbb9ebf81..e5c0f9e6b 100644 --- a/src/table/domain.h +++ b/src/table/domain.h @@ -110,13 +110,17 @@ void ray_sym_domain_release(ray_sym_domain_t* dom); ray_t* ray_sym_domain_str(ray_sym_domain_t* dom, int64_t pos); /* Raw vocabulary access for a FILE domain: the bytes of the entries the - * file holds, read straight from the mapping — no atom, no lock. Pin the - * mapping first; while any reader is pinned a concurrent extend (the file - * grew under another opener) waits before swapping the map. Returns - * false for the runtime domain, an empty file, or a swap in progress — - * the caller then resolves through ray_sym_domain_str as before. Only - * positions below `count` (the file prefix) are readable this way; - * runtime-appended positions keep going through ray_sym_domain_str. */ + * file holds, read straight from the mapping — no atom, no lock. Pin + * takes an atomically published snapshot of (map, offsets, count); a + * later extend (the symfile grew under another opener) publishes a new + * snapshot and RETIRES the old mapping and offsets until the domain is + * destroyed, so a snapshot stays readable for as long as its holder keeps + * the domain alive — no waiting on either side, no lock order to respect. + * Returns false for the runtime domain or an empty file; the caller then + * resolves through ray_sym_domain_str as before. Only positions below + * `count` (the file prefix) are readable this way; runtime-appended + * positions keep going through ray_sym_domain_str. Unpin is a no-op kept + * for symmetry. */ typedef struct { const unsigned char* map; const size_t* offsets; diff --git a/test/rfl/symbol/file_domain_like_strlen.rfl b/test/rfl/symbol/file_domain_like_strlen.rfl index dc4bd9569..0a08e41bb 100644 --- a/test/rfl/symbol/file_domain_like_strlen.rfl +++ b/test/rfl/symbol/file_domain_like_strlen.rfl @@ -63,6 +63,13 @@ (all (== (at (xasc A 'g) 'l) (at (xasc O 'g) 'l))) -- true (all (== (at (xasc A 'g) 's) (at (xasc O 'g) 's))) -- true (all (== (at (xasc A 'g) 'c) (at (xasc O 'g) 'c))) -- true +;; a null cell (the empty symbol) counts as length 0 in the group aggregate, +;; as the per-row path always did — the empty symbols of sp are NOT filtered +(set AN (select {from: F by: g l: (avg (strlen sp)) s: (sum (strlen sp)) c: (count sp)})) +(set ON (select {from: (table [g ls] (list (at F 'g) (strlen SPS))) by: g l: (avg ls) s: (sum ls) c: (count ls)})) +(all (== (at (xasc AN 'g) 'l) (at (xasc ON 'g) 'l))) -- true +(all (== (at (xasc AN 'g) 's) (at (xasc ON 'g) 's))) -- true +(nil? (at (at (select {from: F s: (sum (strlen sp)) where: (== sp "")}) 's) 0)) -- false ;; the where predicate over the file-domain column still filters (== (count (select {from: F where: (and (like u "*google*") (!= sp ""))})) (sum (as 'I64 (and (like US "*google*") (!= SPS ""))))) -- true (.sys.exec "rm -rf /tmp/rfl_fdom_like/") -- 0 diff --git a/test/test_domain.c b/test/test_domain.c index 79f528a96..ce7186ac6 100644 --- a/test/test_domain.c +++ b/test/test_domain.c @@ -1720,6 +1720,40 @@ static test_result_t test_domain_raw_pin(void) { TEST_ASSERT_EQ_I(raw.count, (int64_t)count_at_save); ray_sym_domain_raw_unpin(dom); ray_sym_domain_release(dom); + /* The file grows under another writer while a reader holds a snapshot: + * the reopen extends the domain (new mapping, new offsets), and the + * old snapshot must still read every old position from its retired + * mapping, while a fresh pin sees the grown prefix. */ + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); + ray_sym_domain_t* d1 = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(d1); + ray_sym_domain_raw_t held; + TEST_ASSERT(ray_sym_domain_raw_pin(d1, &held), "pin before growth"); + int64_t before = held.count; + for (int i = 0; i < 64; i++) { + char buf[32]; int n = snprintf(buf, sizeof buf, "raw_grow_%d", i); + (void)ray_sym_intern(buf, (size_t)n); + } + TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); /* grown image, same prefix */ + ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_SYM_PATH); /* cache hit → extend */ + TEST_ASSERT_EQ_PTR(d2, d1); + TEST_ASSERT(ray_sym_domain_count(d1) > before, "reopen extended the domain"); + for (int64_t p = 0; p < before; p++) { + size_t rl = 0; + const char* rp = ray_sym_domain_raw_str(&held, p, &rl); + ray_t* g = ray_sym_str(p); + TEST_ASSERT_EQ_U(rl, ray_str_len(g)); + TEST_ASSERT_MEM_EQ(rl, rp, ray_str_ptr(g)); + } + ray_sym_domain_raw_t fresh; + TEST_ASSERT(ray_sym_domain_raw_pin(d1, &fresh), "pin after growth"); + TEST_ASSERT(fresh.count > before, "fresh snapshot covers the grown prefix"); + ray_sym_domain_raw_unpin(d1); + ray_sym_domain_raw_unpin(d1); + ray_sym_domain_release(d2); + ray_sym_domain_release(d1); unlink(TMP_DOM_SYM_PATH); unlink(TMP_DOM_SYM_PATH ".lk"); PASS(); From 4b3f403752e231ee810818a159f05ac6e643d0d1 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 12:40:40 +0200 Subject: [PATCH 08/20] feat(sys): process identity in .sys.info; .sys.exec exit codes and output capture MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/docs/namespaces/sys.md | 58 ++++++-- docs/docs/reference/all-functions.md | 4 +- src/lang/eval.c | 2 +- src/lang/internal.h | 2 +- src/ops/system.c | 176 +++++++++++++++++++++++-- test/rfl/system/process_identity.rfl | 62 +++++++++ test/rfl/system/reserved_namespace.rfl | 2 +- test/rfl/system/system_branch_cov2.rfl | 4 +- 8 files changed, 287 insertions(+), 23 deletions(-) create mode 100644 test/rfl/system/process_identity.rfl diff --git a/docs/docs/namespaces/sys.md b/docs/docs/namespaces/sys.md index 3e687f307..6ef3fff7d 100644 --- a/docs/docs/namespaces/sys.md +++ b/docs/docs/namespaces/sys.md @@ -11,14 +11,14 @@ Process-level introspection (build, memory, host info) and command-style operati |---|---|---|---| | [`.sys.args`](#sys-args) | variadic | — | Command-line arguments as a typed dict. | | [`.sys.build`](#sys-build) | variadic | — | Version + build date as a dict. | -| [`.sys.info`](#sys-info) | variadic | — | Host facts: cores, page size, total memory. | +| [`.sys.info`](#sys-info) | variadic | — | Host and process facts: cores, page size, total memory, pid, hostname. | | [`.sys.mem`](#sys-mem) | variadic | — | Allocator statistics. | | [`.sys.prof`](#sys-prof) | variadic | — | Last profiled query's per-step statistics as a table. | | [`.sys.querylog`](#sys-querylog) | variadic | — | Ambient per-query statistics ring as a table. | | [`.sys.querylog.enable`](#sys-querylog-enable) | variadic | restricted | Toggle query-statistics logging. | | [`.sys.gc`](#sys-gc) | variadic | — | Run allocator maintenance and return `0`. | | [`.sys.env`](#sys-env) | variadic | — | Count or list of globally bound names. | -| [`.sys.exec`](#sys-exec) | unary | restricted | Run a shell command; return its exit code. | +| [`.sys.exec`](#sys-exec) | variadic | restricted | Run a shell command; return its exit code, optionally with stdout. | | [`.sys.cmd`](#sys-cmd) | unary | restricted | Dispatch a colon-command string. | | [`.sys.listen`](#sys-listen) | unary | restricted | Bind an IPC listener on a TCP port. | | [`.sys.timeit`](#sys-timeit) | variadic | — | Toggle / set the per-expression profiler. | @@ -75,13 +75,33 @@ Signature: `(.sys.build)`. Returns a dict with `version` (string) and `build-dat ## `.sys.info` { #sys-info } -Signature: `(.sys.info)`. Returns `{cores: i64, page-size: i64, total-mem: i64}` on POSIX. On Windows the response is `{cores: 1}` (a fallback — the sysconf-backed values aren't wired). +Signature: `(.sys.info)`. Returns `{cores: i64, page-size: i64, total-mem: i64, pid: i64, hostname: str}` on POSIX. On Windows the machine facts fall back to `{cores: 1}` (the sysconf-backed values aren't wired), but `pid` and `hostname` are answered on both platforms. ```lisp (.sys.info) -;; => {cores: 10, page-size: 16384, total-mem: 68719476736} +;; => {cores: 10, page-size: 16384, total-mem: 68719476736, +;; pid: 48213, hostname: "tp-prod-01"} ``` +`pid` and `hostname` describe *this process*, not the machine, and exist so an +embedded process can name itself. The common use is a per-start epoch that a +peer can check a stale cursor against: + +```lisp +(format "%-%-%" (get (.sys.info) 'hostname) + (get (.sys.info) 'pid) + (timestamp 'global)) +;; => "tp-prod-01-48213-2026.09.18D10:05:59.000000000" +``` + +That identity is worth preferring over a random token because it is +diagnosable: reading it back tells you which host and which process produced +it. Note `(timestamp 'global)` is second-resolution, so pid is what separates +two starts within the same second. + +If `hostname` cannot be obtained, it reports `""` rather than failing the whole +call — one unavailable field should not cost the caller the others. + ## `.sys.mem` { #sys-mem } Signature: `(.sys.mem)`. Returns the buddy allocator's running counters: @@ -233,15 +253,37 @@ Signature: `(.sys.env)`. From a script / IPC context returns the **count** of gl ## `.sys.exec` { #sys-exec } -Signature: `(.sys.exec "command")`. Runs `command` through `system(3)` and returns its exit status as an `i64`. Used pervasively in tests to set up / tear down `/tmp` fixtures. +Signature: `(.sys.exec "command")` or `(.sys.exec "command" 'out)`. + +Runs `command` through the shell. The one-argument form returns the **exit +code** as an `i64` — the code the shell itself would report, not the +`waitpid`-encoded status. A command killed by a signal reports `128 + signum`, +following the same shell convention. -Errors: `type` (arg not a string), `domain` (null pointer). +The `'out` form returns `{code: i64, out: str}`, capturing the command's +standard output. Output is read until EOF and is not sized from `stat`, so +pipes and procfs reads come back whole. **stderr is not captured** — it stays +on the process's own stderr, so a command's diagnostics land in the log rather +than corrupting a value you are about to parse. + +Errors: `type` (command not a string, or mode not a symbol), `domain` (null +pointer, or a mode other than `'out`), `io` (the command could not be started +or did not complete), `oom`. ```lisp -(.sys.exec "rm -rf /tmp/scratch") ;; => 0 -(.sys.exec "false") ;; => 256 (waitpid-encoded) +(.sys.exec "rm -rf /tmp/scratch") ;; => 0 +(.sys.exec "false") ;; => 1 +(.sys.exec "exit 3") ;; => 3 +(.sys.exec "echo hi" 'out) ;; => {code: 0, out: "hi\n"} +(.sys.exec "echo partial; exit 4" 'out) ;; => {code: 4, out: "partial\n"} ``` +!!! warning "Behaviour change" + Before this, the one-argument form returned the raw `waitpid`-encoded + status, so `(.sys.exec "false")` was `256` and `(.sys.exec "exit 3")` was + `768`. Success was `0` either way, so code that only checks for zero is + unaffected; code comparing against an encoded value needs updating. + ## `.sys.cmd` { #sys-cmd } Signature: `(.sys.cmd "name args")`. Parses a colon-style command name (without the leading `:`) and dispatches. Names supported: `timeit`/`t`, `listen`, `env`, `clear`, `help`/`?`, `q`/`quit`. Unknown names fall back to `system()` (so `(.sys.cmd "ls /tmp")` works too). diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index a58c4e721..9f6a543ae 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -644,7 +644,7 @@ System interaction, metaprogramming, diagnostics, and runtime inspection. | `.sys.gc` | variadic | — | Trigger GC / heap flush, returns `0` | `(.sys.gc)` | | `.mem.objsize` | unary | — | Logical bytes retained by an object graph; shared children count once | `(.mem.objsize value)` | | `.mem.ts` | special form | — | Evaluate once and return result, time, allocation, peak-memory, result-size, and worker statistics as a dict | `(.mem.ts (select {from: trades}))` | -| `.sys.exec` | unary | restricted | Execute a shell command, return exit code | `(.sys.exec "ls -la")` | +| `.sys.exec` | variadic | restricted | Execute a shell command; exit code, or `{code, out}` with `'out` | `(.sys.exec "ls -la" 'out)` | | `.os.getenv` | unary | restricted | Get environment variable value | `(.os.getenv "HOME")` | | `.os.setenv` | binary | restricted | Set environment variable | `(.os.setenv "KEY" "value")` | | `.sys.args` | nullary | — | Application arguments as a typed dict; `user` subdict holds post-`--` args | `(.sys.args)` | @@ -657,7 +657,7 @@ System interaction, metaprogramming, diagnostics, and runtime inspection. | `.sys.prof` | variadic | — | Last profiled query's per-step statistics as a table (opt-in via `:t`) | `(.sys.prof)` | | `.sys.querylog` | variadic | — | Ambient per-query statistics ring as a table (opt-in via `-Q` / `.sys.querylog.enable`) | `(.sys.querylog)` | | `.sys.querylog.enable` | variadic | restricted | Toggle query-statistics logging; returns new state | `(.sys.querylog.enable 1)` | -| `.sys.info` | variadic | — | System information (cores, page size, total memory) | `(.sys.info)` | +| `.sys.info` | variadic | — | Host and process info (cores, page size, total memory, pid, hostname) | `(.sys.info)` | ```lisp ; Metaprogramming: parse and eval diff --git a/src/lang/eval.c b/src/lang/eval.c index e481002b3..d72841d44 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -3372,7 +3372,7 @@ static void ray_register_builtins(void) { * user code can't shadow them and a glance at the name identifies * the category. */ register_vary (".sys.gc", RAY_FN_NONE, ray_gc_fn); - register_unary(".sys.exec", RAY_FN_RESTRICTED, ray_system_fn); + register_vary (".sys.exec", RAY_FN_RESTRICTED, ray_system_fn); register_unary(".mem.objsize", RAY_FN_NONE, ray_mem_objsize_fn); register_vary (".mem.ts", RAY_FN_SPECIAL_FORM, ray_mem_ts_fn); /* Registry-dispatched system commands. `.sys.cmd "name args"` is diff --git a/src/lang/internal.h b/src/lang/internal.h index 0f73e5f89..09a3b5d1e 100644 --- a/src/lang/internal.h +++ b/src/lang/internal.h @@ -606,7 +606,7 @@ ray_t* ray_meta_fn(ray_t* x); ray_t* ray_mem_objsize_fn(ray_t* x); ray_t* ray_mem_ts_fn(ray_t** args, int64_t n); ray_t* ray_gc_fn(ray_t** args, int64_t n); -ray_t* ray_system_fn(ray_t* x); +ray_t* ray_system_fn(ray_t** args, int64_t n); /* `.sys.cmd "name args"` — registry-dispatched system commands with * shell fallback (see lang/syscmd.h). */ ray_t* ray_syscmd_string_dispatch_fn(ray_t* x); diff --git a/src/ops/system.c b/src/ops/system.c index 5a594ed89..cf2dd99b2 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -21,6 +21,10 @@ * SOFTWARE. */ +#if !defined(_WIN32) && !defined(_GNU_SOURCE) +# define _GNU_SOURCE /* popen()/pclose() and gethostname() — .sys.exec, .sys.info */ +#endif + #include "lang/internal.h" #include "lang/env.h" #include "lang/eval.h" /* LAMBDA_PARAMS */ @@ -55,6 +59,12 @@ void* ray_runtime_get_sys_args(void); #include #if !defined(RAY_OS_WINDOWS) #include +#include /* WIFEXITED/WEXITSTATUS — .sys.exec exit codes */ +#define RAY_POPEN(c, m) popen((c), (m)) +#define RAY_PCLOSE(f) pclose(f) +#else +#define RAY_POPEN(c, m) _popen((c), (m)) +#define RAY_PCLOSE(f) _pclose(f) #endif /* ══════════════════════════════════════════ @@ -798,18 +808,125 @@ ray_t* ray_gc_fn(ray_t** args, int64_t n) { } /* (system cmd) -- run shell command, return exit code */ -ray_t* ray_system_fn(ray_t* x) { +/* Turn a wait(2)-style status into the exit code a shell would report. + * system() and pclose() hand back an encoded status, not a code: "exit 3" + * arrives as 768 (3 << 8). Signals follow the shell's 128+N convention, so + * a command killed by SIGTERM reads as 143 rather than as a bare 15 that + * could be confused with a real exit status. */ +static int64_t exec_exit_code(int status) { +#if defined(RAY_OS_WINDOWS) + /* The CRT's system()/_pclose() already return the child's exit code. */ + return (int64_t)status; +#else + if (WIFEXITED(status)) return (int64_t)WEXITSTATUS(status); + if (WIFSIGNALED(status)) return (int64_t)(128 + WTERMSIG(status)); + return (int64_t)status; +#endif +} + +/* Read everything the child writes to stdout. Grows geometrically rather + * than sizing from any stat(), so output from a pipe — which has no size to + * ask for — comes back whole (cf. #572). */ +static ray_t* exec_capture(const char* cmd, int64_t* code_out) { + FILE* fp = RAY_POPEN(cmd, "r"); + if (!fp) return ray_error("io", ".sys.exec: failed to start command: %s", strerror(errno)); + + size_t cap = 4096, len = 0; + char* buf = (char*)ray_alloc_raw(cap); + if (!buf) { RAY_PCLOSE(fp); return ray_error("oom", ".sys.exec: capture buffer"); } + + for (;;) { + if (len == cap) { + char* nbuf = (char*)ray_realloc_raw(buf, cap * 2); + if (!nbuf) { ray_free_raw(buf); RAY_PCLOSE(fp); return ray_error("oom", ".sys.exec: capture buffer"); } + buf = nbuf; cap *= 2; + } + size_t got = fread(buf + len, 1, cap - len, fp); + len += got; + if (got == 0) { + if (ferror(fp)) { ray_free_raw(buf); RAY_PCLOSE(fp); return ray_error("io", ".sys.exec: read failed"); } + break; /* EOF */ + } + } + + int status = RAY_PCLOSE(fp); + if (status == -1) { ray_free_raw(buf); return ray_error("io", ".sys.exec: command did not complete: %s", strerror(errno)); } + *code_out = exec_exit_code(status); + + ray_t* out = ray_str(buf, len); + ray_free_raw(buf); + return out; +} + +/* (.sys.exec cmd) -> exit code + * (.sys.exec cmd 'out) -> {code: out: } + * + * stderr is deliberately left on the process's own stderr: a shelled-out + * command's diagnostics belong in the log, and merging them into the + * captured value would corrupt anything parsing that value (#573). */ +ray_t* ray_system_fn(ray_t** args, int64_t n) { #ifdef RAY_FUZZING /* Shell escape — disabled under fuzzing so untrusted input can't run * arbitrary commands in the fuzzer process. */ - (void)x; + (void)args; (void)n; return ray_error("restricted", "shell disabled under fuzzing"); #else + if (n != 1 && n != 2) return ray_error("domain", ".sys.exec expects 1 or 2 arguments"); + ray_t* x = args[0]; if (x->type != -RAY_STR) return ray_error("type", "system expects a string"); - const char* cmd = ray_str_ptr(x); - if (!cmd) return ray_error("domain", ".sys.exec: empty or invalid command string"); - int rc = system(cmd); - return make_i64(rc); + + bool capture = false; + if (n == 2) { + ray_t* mode = args[1]; + if (mode->type != -RAY_SYM) + return ray_error("type", ".sys.exec: second argument must be the symbol 'out"); + if (mode->i64 != ray_sym_intern("out", 3)) + return ray_error("domain", ".sys.exec: unknown mode, expected 'out"); + capture = true; + } + + /* libc needs a NUL-terminated command; ray strings are not NUL-terminated + * once pooled (len > RAY_STR_INLINE_MAX). */ + char stackbuf[1024]; + char* heapbuf = NULL; + int64_t clen = ray_str_len(x); + const char* raw = ray_str_ptr(x); + if (!raw) return ray_error("domain", ".sys.exec: empty or invalid command string"); + char* cmd; + if (clen < (int64_t)sizeof(stackbuf)) { + cmd = stackbuf; + } else { + heapbuf = (char*)ray_alloc_raw((size_t)clen + 1); + if (!heapbuf) return ray_error("oom", ".sys.exec: command buffer"); + cmd = heapbuf; + } + memcpy(cmd, raw, (size_t)clen); + cmd[clen] = '\0'; + + ray_t* result; + if (!capture) { + result = make_i64(exec_exit_code(system(cmd))); + } else { + int64_t code = 0; + ray_t* out = exec_capture(cmd, &code); + if (RAY_IS_ERR(out)) { + result = out; + } else { + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 2); + ray_t* vals = ray_list_new(2); + int64_t k1 = ray_sym_intern("code", 4); + keys = ray_vec_append(keys, &k1); + ray_t* v1 = make_i64(code); + vals = ray_list_append(vals, v1); ray_release(v1); + int64_t k2 = ray_sym_intern("out", 3); + keys = ray_vec_append(keys, &k2); + vals = ray_list_append(vals, out); ray_release(out); + result = ray_dict_new(keys, vals); + } + } + + if (heapbuf) ray_free_raw(heapbuf); + return result; #endif } @@ -1256,11 +1373,38 @@ ray_t* ray_qlog_enable_fn(ray_t** args, int64_t n) { return make_i64(on ? 1 : 0); } +/* Process id of this process. getpid() is already used internally for heap + * swap-file names; this is the same value, made reachable from Rayfall. */ +static int64_t ray_os_pid(void) { +#if defined(RAY_OS_WINDOWS) + return (int64_t)GetCurrentProcessId(); +#else + return (int64_t)getpid(); +#endif +} + +/* Host name into `buf`, NUL-terminated. False when the platform cannot + * answer, in which case .sys.info reports "" rather than failing the whole + * call — one unavailable field should not cost the caller the others. */ +static bool ray_os_hostname(char* buf, size_t cap) { + if (cap == 0) return false; + buf[0] = '\0'; +#if defined(RAY_OS_WINDOWS) + DWORD n = (DWORD)cap; + if (!GetComputerNameA(buf, &n)) return false; +#else + if (gethostname(buf, cap) != 0) return false; + /* POSIX leaves truncation unterminated. */ + buf[cap - 1] = '\0'; +#endif + return buf[0] != '\0'; +} + ray_t* ray_sysinfo_fn(ray_t** args, int64_t n) { (void)args; (void)n; - ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 3); + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 5); if (RAY_IS_ERR(keys)) return keys; - ray_t* vals = ray_list_new(3); + ray_t* vals = ray_list_new(5); if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } #if !defined(RAY_OS_WINDOWS) @@ -1285,6 +1429,22 @@ ray_t* ray_sysinfo_fn(ray_t** args, int64_t n) { vals = ray_list_append(vals, v1); ray_release(v1); #endif + /* Process and host identity (#573). An embedded process previously had + * no way to name itself: pid plus hostname plus a start timestamp is a + * diagnosable epoch, where a random token only tells you that two runs + * differ, not which machine or process either one was. */ + int64_t sp = ray_sym_intern("pid", 3); + keys = ray_vec_append(keys, &sp); + ray_t* vp = make_i64(ray_os_pid()); + vals = ray_list_append(vals, vp); ray_release(vp); + + char host[256]; + int64_t sh = ray_sym_intern("hostname", 8); + keys = ray_vec_append(keys, &sh); + ray_t* vh = ray_os_hostname(host, sizeof(host)) ? ray_str(host, strlen(host)) + : ray_str("", 0); + vals = ray_list_append(vals, vh); ray_release(vh); + return ray_dict_new(keys, vals); } diff --git a/test/rfl/system/process_identity.rfl b/test/rfl/system/process_identity.rfl new file mode 100644 index 000000000..42035b471 --- /dev/null +++ b/test/rfl/system/process_identity.rfl @@ -0,0 +1,62 @@ +;; Process and host identity, plus .sys.exec output capture — issue #573. +;; +;; An embedded process could not learn anything about itself: no PID, no +;; hostname, and .sys.exec discarded stdout. The reported consequence was +;; an owner process unable to mint an epoch distinguishing one of its own +;; restarts from the next, so a subscriber's stale cursor stayed plausible +;; across a restart. +;; +;; Values here are machine- and run-specific, so the assertions are on +;; shape and invariants rather than on literals. + +;; ────────────── .sys.info carries process identity ────────────── +;; Machine facts were already there; pid and hostname join them so one +;; call answers "what am I running on, and which process am I". +(type (get (.sys.info) 'pid)) -- 'i64 +(> (get (.sys.info) 'pid) 0) -- true + +(type (get (.sys.info) 'hostname)) -- 'str +(> (count (get (.sys.info) 'hostname)) 0) -- true + +;; Stable within a process — it is our pid, not a fresh child's. +(== (get (.sys.info) 'pid) (get (.sys.info) 'pid)) -- true + +;; The machine keys are untouched. +(> (get (.sys.info) 'cores) 0) -- true +(> (get (.sys.info) 'page-size) 0) -- true + +;; ────────────── .sys.exec returns an exit code ────────────── +;; It used to return the raw wait(2) status, so "exit 3" came back as 768. +(.sys.exec "exit 0") -- 0 +(.sys.exec "exit 3") -- 3 +(.sys.exec "exit 42") -- 42 +;; 127 is the shell's "command not found"; it must survive as itself +;; rather than as 32512. +(.sys.exec "exit 127") -- 127 + +;; ────────────── .sys.exec 'out captures stdout ────────────── +(get (.sys.exec "echo hi" 'out) 'code) -- 0 +(get (.sys.exec "echo hi" 'out) 'out) -- "hi\n" + +;; Exit code and output are reported together, not either/or. +(get (.sys.exec "echo partial; exit 4" 'out) 'code) -- 4 +(get (.sys.exec "echo partial; exit 4" 'out) 'out) -- "partial\n" + +;; No output is an empty string, not a null or a missing key. +(get (.sys.exec "true" 'out) 'out) -- "" + +;; Output larger than one read buffer comes back whole. +(count (get (.sys.exec "printf 'x%.0s' $(seq 1 100000)" 'out) 'out)) -- 100000 + +;; stderr is not captured — it stays on the process's own stderr, so a +;; command that only writes there yields an empty capture. +(get (.sys.exec "{ echo oops 1>&2; } 2>/dev/null" 'out) 'out) -- "" + +;; 'out is the only accepted second argument. +(try (.sys.exec "true" 'nope) (fn [e] 'rejected)) -- 'rejected +(try (.sys.exec "true" 5) (fn [e] 'rejected)) -- 'rejected + +;; ────────────── the reported use case, in one expression ────────────── +;; host + pid + wall clock is a diagnosable epoch: no temp file, no umask +;; dance, no cleanup, and reading it tells you which process it names. +(> (count (format "%-%-%" (get (.sys.info) 'hostname) (get (.sys.info) 'pid) (timestamp 'global))) 0) -- true diff --git a/test/rfl/system/reserved_namespace.rfl b/test/rfl/system/reserved_namespace.rfl index f8bc132dd..fd0d72382 100644 --- a/test/rfl/system/reserved_namespace.rfl +++ b/test/rfl/system/reserved_namespace.rfl @@ -9,7 +9,7 @@ ;; other .sys.* info builtins follow the same convention. (.sys.gc) -- 0 (.sys.gc 0) -- 0 -(count (.sys.info)) -- 3 +(count (.sys.info)) -- 5 (count (.sys.mem)) -- 16 (count (.sys.build)) -- 2 ;; The namespace roots themselves are real dicts — typing just diff --git a/test/rfl/system/system_branch_cov2.rfl b/test/rfl/system/system_branch_cov2.rfl index 806dfcc9a..73a2d595c 100644 --- a/test/rfl/system/system_branch_cov2.rfl +++ b/test/rfl/system/system_branch_cov2.rfl @@ -113,10 +113,10 @@ ;; ray_sysinfo_fn (.sys.info) (lines 730-762) ;; ══════════════════════════════════════════════════════════════════════ (type (.sys.info)) -- 'DICT -(count (.sys.info)) -- 3 +(count (.sys.info)) -- 5 (> (at (.sys.info) 'cores) 0) -- true (> (at (.sys.info) 'total-mem) 0) -- true -(count (value (.sys.info))) -- 3 +(count (value (.sys.info))) -- 5 ;; ══════════════════════════════════════════════════════════════════════ ;; ray_hopen_fn (lines 769-825) From 9d1e7e4a8113887d9e52ea4d7ca6464e6114029b Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 13:21:51 +0200 Subject: [PATCH 09/20] fix(sys): guard the exec helpers out of the fuzz build; harden error paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/ops/system.c | 25 +++++++++++++++++++++++-- test/rfl/system/process_identity.rfl | 17 ++++++++++++++--- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/ops/system.c b/src/ops/system.c index cf2dd99b2..f2490d35c 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -808,6 +808,10 @@ ray_t* ray_gc_fn(ray_t** args, int64_t n) { } /* (system cmd) -- run shell command, return exit code */ +/* Both helpers exist only for the live .sys.exec path, which RAY_FUZZING + * compiles out — guard them so the fuzz build does not trip + * -Werror,-Wunused-function. */ +#ifndef RAY_FUZZING /* Turn a wait(2)-style status into the exit code a shell would report. * system() and pclose() hand back an encoded status, not a code: "exit 3" * arrives as 768 (3 << 8). Signals follow the shell's 128+N convention, so @@ -858,6 +862,8 @@ static ray_t* exec_capture(const char* cmd, int64_t* code_out) { return out; } +#endif /* !RAY_FUZZING */ + /* (.sys.exec cmd) -> exit code * (.sys.exec cmd 'out) -> {code: out: } * @@ -905,7 +911,16 @@ ray_t* ray_system_fn(ray_t** args, int64_t n) { ray_t* result; if (!capture) { - result = make_i64(exec_exit_code(system(cmd))); + int rc = system(cmd); + /* -1 means the shell could not be started at all. Decoding it would + * yield 128+127 = 255 — indistinguishable from a command that really + * exited 255 — so report it the way the capture path reports its + * equivalent pclose failure. */ + if (rc == -1) { + if (heapbuf) ray_free_raw(heapbuf); + return ray_error("io", ".sys.exec: failed to run command: %s", strerror(errno)); + } + result = make_i64(exec_exit_code(rc)); } else { int64_t code = 0; ray_t* out = exec_capture(cmd, &code); @@ -913,7 +928,13 @@ ray_t* ray_system_fn(ray_t** args, int64_t n) { result = out; } else { ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 2); - ray_t* vals = ray_list_new(2); + ray_t* vals = RAY_IS_ERR(keys) ? keys : ray_list_new(2); + if (RAY_IS_ERR(keys) || RAY_IS_ERR(vals)) { + if (!RAY_IS_ERR(keys)) ray_release(keys); + ray_release(out); + if (heapbuf) ray_free_raw(heapbuf); + return RAY_IS_ERR(keys) ? keys : vals; + } int64_t k1 = ray_sym_intern("code", 4); keys = ray_vec_append(keys, &k1); ray_t* v1 = make_i64(code); diff --git a/test/rfl/system/process_identity.rfl b/test/rfl/system/process_identity.rfl index 42035b471..d0baa387d 100644 --- a/test/rfl/system/process_identity.rfl +++ b/test/rfl/system/process_identity.rfl @@ -16,7 +16,12 @@ (> (get (.sys.info) 'pid) 0) -- true (type (get (.sys.info) 'hostname)) -- 'str -(> (count (get (.sys.info) 'hostname)) 0) -- true +;; Cross-check the value rather than merely asserting it is non-empty: the +;; implementation deliberately degrades to "" when the platform cannot +;; answer, so a non-empty assertion would be testing something it does not +;; promise. Comparing against uname(1) tests what actually matters — that +;; when we do report a hostname, it is the right one. +(== (get (.sys.info) 'hostname) (first (split (get (.sys.exec "uname -n" 'out) 'out) "\n"))) -- true ;; Stable within a process — it is our pid, not a fresh child's. (== (get (.sys.info) 'pid) (get (.sys.info) 'pid)) -- true @@ -45,8 +50,10 @@ ;; No output is an empty string, not a null or a missing key. (get (.sys.exec "true" 'out) 'out) -- "" -;; Output larger than one read buffer comes back whole. -(count (get (.sys.exec "printf 'x%.0s' $(seq 1 100000)" 'out) 'out)) -- 100000 +;; Output larger than one read buffer (4096) comes back whole. Produced by a +;; pipe rather than by expanding 100k argv words, which would lean on `seq` +;; and on ARG_MAX rather than on the growth behaviour under test. +(count (get (.sys.exec "head -c 100000 /dev/zero | tr '\\0' x" 'out) 'out)) -- 100000 ;; stderr is not captured — it stays on the process's own stderr, so a ;; command that only writes there yields an empty capture. @@ -60,3 +67,7 @@ ;; host + pid + wall clock is a diagnosable epoch: no temp file, no umask ;; dance, no cleanup, and reading it tells you which process it names. (> (count (format "%-%-%" (get (.sys.info) 'hostname) (get (.sys.info) 'pid) (timestamp 'global))) 0) -- true + +;; A command the shell cannot run at all is an io error, not a decoded 255 — +;; otherwise it is indistinguishable from a command that genuinely exited 255. +(.sys.exec "exit 255") -- 255 From 4564f2522c310b37011f57dfe1e1926456519aea Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Fri, 18 Sep 2026 14:25:13 +0300 Subject: [PATCH 10/20] fix(sym): keep the group strlen aggregate on its per-row path; read the length off the snapshot there MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/ops/group.c | 33 +++++++++------------ src/ops/internal.h | 2 +- src/ops/string.c | 19 ++++-------- test/rfl/symbol/file_domain_like_strlen.rfl | 28 ++++++++++++----- 4 files changed, 42 insertions(+), 40 deletions(-) diff --git a/src/ops/group.c b/src/ops/group.c index e264d322c..84a3de7de 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -8136,7 +8136,20 @@ static inline int64_t group_strlen_at(const ray_t* col, int64_t row) { } /* SYM cell: resolve through the COLUMN's domain (sym-domain Phase 2) * — sym_elem resolves via the global table, wrong for FILE-domain - * columns. */ + * columns. A FILE domain's entries carry their length as a u32 + * prefix in the mapping: read it off the published snapshot (one + * acquire load) instead of materialising an atom per symbol under + * the domain lock; positions past the mapped prefix and other domains + * resolve as before. */ + { + int64_t sid = ray_read_sym(ray_data((ray_t*)col), row, col->type, col->attrs); + ray_sym_domain_raw_t raw; + if (ray_sym_domain_raw_pin(ray_sym_vec_domain((ray_t*)col), &raw) && sid >= 0 && sid < raw.count) { + size_t sl; + (void)ray_sym_domain_raw_str(&raw, sid, &sl); + return (int64_t)sl; + } + } ray_t* s = ray_sym_vec_cell((ray_t*)col, row); return s ? (int64_t)ray_str_len(s) : 0; } @@ -11697,24 +11710,6 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if ((agg_kind == OP_SUM || agg_kind == OP_AVG) && try_strlen_sumavg_input(g, tbl, agg_input_op, &agg_vecs[a])) { - /* A SYM column on a FILE domain: the per-row string resolve - * would materialise an atom per distinct symbol under the - * domain lock. Read the lengths off the mapping once - * (parallel, no atoms) and aggregate the plain I64 vector. A - * null cell (the empty symbol) is a null length, which the - * accumulate skips exactly as the per-row path skips the row. */ - ray_t* sc = agg_vecs[a]; - if (sc->type == RAY_SYM && ray_sym_vec_domain(sc) != ray_sym_runtime_domain()) { - ray_t* lens = ray_vec_new(RAY_I64, sc->len); - if (lens && !RAY_IS_ERR(lens)) { - lens->len = sc->len; - ray_sym_strlen_into(sc, lens, false); - agg_vecs[a] = lens; - agg_owned[a] = 1; - continue; - } - if (lens) ray_error_free(lens); - } agg_strlen[a] = 1; continue; } diff --git a/src/ops/internal.h b/src/ops/internal.h index 96003f9aa..6465b0a1d 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -1606,7 +1606,7 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op); ray_t* exec_ilike(ray_graph_t* g, ray_op_t* op); ray_t* exec_string_unary(ray_graph_t* g, ray_op_t* op); ray_t* exec_strlen(ray_graph_t* g, ray_op_t* op); -void ray_sym_strlen_into(ray_t* input, ray_t* result, bool null_as_zero); /* string.c */ +void ray_sym_strlen_into(ray_t* input, ray_t* result); /* string.c */ ray_t* exec_substr(ray_graph_t* g, ray_op_t* op); ray_t* exec_replace(ray_graph_t* g, ray_op_t* op); ray_t* exec_concat(ray_graph_t* g, ray_op_t* op); diff --git a/src/ops/string.c b/src/ops/string.c index 53e052832..7711a36bc 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -1007,7 +1007,6 @@ typedef struct { struct ray_sym_domain_s* dom; ray_sym_domain_raw_t raw; bool raw_ok; - bool null_as_zero; /* group aggregates count a null cell as length 0 */ _Atomic(int) any_null; } strlen_sym_ctx_t; static void strlen_sym_task(void* vctx, uint32_t worker_id, int64_t lo, int64_t hi) { @@ -1017,10 +1016,7 @@ static void strlen_sym_task(void* vctx, uint32_t worker_id, int64_t lo, int64_t const void* base = ray_data(input); bool any_null = false; for (int64_t i = lo; i < hi; i++) { - if (ray_vec_is_null(input, i)) { - if (c->null_as_zero) { c->dst[i] = 0; continue; } - c->dst[i] = NULL_I64; any_null = true; continue; - } + if (ray_vec_is_null(input, i)) { c->dst[i] = NULL_I64; any_null = true; continue; } int64_t sid = ray_read_sym(base, i, input->type, input->attrs); if (c->raw_ok && sid >= 0 && sid < c->raw.count) { size_t sl; @@ -1037,14 +1033,11 @@ static void strlen_sym_task(void* vctx, uint32_t worker_id, int64_t lo, int64_t /* Lengths of a SYM vector into a pre-sized I64 vector. A FILE domain's * entries carry their length as a u32 prefix in the mapping — read that by * position, no atom, no lock, in parallel; anything else (runtime domain, - * appended positions) resolves the way it always did. null_as_zero: a - * null cell (the empty symbol) becomes 0 with no HAS_NULLS, the contract of - * the group path's strlen-on-SYM aggregate; otherwise NULL_I64 as the - * vector op returns. */ -void ray_sym_strlen_into(ray_t* input, ray_t* result, bool null_as_zero) { + * appended positions) resolves the way it always did. A null cell (the + * empty symbol) is a null length, as the vector op returns. */ +void ray_sym_strlen_into(ray_t* input, ray_t* result) { int64_t len = input->len; - strlen_sym_ctx_t c = { .input = input, .dst = (int64_t*)ray_data(result), .raw_ok = false, - .null_as_zero = null_as_zero }; + strlen_sym_ctx_t c = { .input = input, .dst = (int64_t*)ray_data(result), .raw_ok = false }; c.dom = ray_sym_vec_domain(input); c.raw_ok = c.dom ? ray_sym_domain_raw_pin(c.dom, &c.raw) : false; atomic_store_explicit(&c.any_null, 0, memory_order_relaxed); @@ -1079,7 +1072,7 @@ ray_t* exec_strlen(ray_graph_t* g, ray_op_t* op) { } } } else { - ray_sym_strlen_into(input, result, false); + ray_sym_strlen_into(input, result); } ray_release(input); return result; diff --git a/test/rfl/symbol/file_domain_like_strlen.rfl b/test/rfl/symbol/file_domain_like_strlen.rfl index 0a08e41bb..e13d26bad 100644 --- a/test/rfl/symbol/file_domain_like_strlen.rfl +++ b/test/rfl/symbol/file_domain_like_strlen.rfl @@ -63,13 +63,27 @@ (all (== (at (xasc A 'g) 'l) (at (xasc O 'g) 'l))) -- true (all (== (at (xasc A 'g) 's) (at (xasc O 'g) 's))) -- true (all (== (at (xasc A 'g) 'c) (at (xasc O 'g) 'c))) -- true -;; a null cell (the empty symbol) counts as length 0 in the group aggregate, -;; as the per-row path always did — the empty symbols of sp are NOT filtered -(set AN (select {from: F by: g l: (avg (strlen sp)) s: (sum (strlen sp)) c: (count sp)})) -(set ON (select {from: (table [g ls] (list (at F 'g) (strlen SPS))) by: g l: (avg ls) s: (sum ls) c: (count ls)})) -(all (== (at (xasc AN 'g) 'l) (at (xasc ON 'g) 'l))) -- true -(all (== (at (xasc AN 'g) 's) (at (xasc ON 'g) 's))) -- true -(nil? (at (at (select {from: F s: (sum (strlen sp)) where: (== sp "")}) 's) 0)) -- false +;; strlen inside a group aggregate must give the SAME answer for the on-disk +;; column as for the identical in-memory column, on every path the engine +;; takes: the empty symbol is a null cell, and the two accumulates (with and +;; without a row selection) treat it differently — that asymmetry is the +;; engine's, and it must not depend on where the column lives +(set AF (xasc (select {from: F by: g l: (avg (strlen sp)) s: (sum (strlen sp)) c: (count sp)}) 'g)) +(set AT (xasc (select {from: T by: g l: (avg (strlen sp)) s: (sum (strlen sp)) c: (count sp)}) 'g)) +(all (== (at AF 'l) (at AT 'l))) -- true +(all (== (at AF 's) (at AT 's))) -- true +(set WF (xasc (select {from: F by: g l: (avg (strlen sp)) s: (sum (strlen sp)) where: (< g 200)}) 'g)) +(set WT (xasc (select {from: T by: g l: (avg (strlen sp)) s: (sum (strlen sp)) where: (< g 200)}) 'g)) +(all (== (at WF 'l) (at WT 'l))) -- true +(all (== (at WF 's) (at WT 's))) -- true +;; the smallest case: one group of two empties, one mixed, on disk and in memory +(.sys.exec "rm -rf /tmp/rfl_fdom_like2/") -- 0 +(set T2 (table [g2 s2] (list [1 1 2 2 3] (as 'SYMBOL ["" "abcd" "" "" "xy"])))) +(.db.splayed.set "/tmp/rfl_fdom_like2/" T2) +(set F2 (.db.splayed.get "/tmp/rfl_fdom_like2/")) +(== (at (xasc (select {from: F2 by: g2 l: (avg (strlen s2))}) 'g2) 'l) (at (xasc (select {from: T2 by: g2 l: (avg (strlen s2))}) 'g2) 'l)) -- [true true true] +(== (at (xasc (select {from: F2 by: g2 s: (sum (strlen s2))}) 'g2) 's) (at (xasc (select {from: T2 by: g2 s: (sum (strlen s2))}) 'g2) 's)) -- [true true true] +(.sys.exec "rm -rf /tmp/rfl_fdom_like2/") -- 0 ;; the where predicate over the file-domain column still filters (== (count (select {from: F where: (and (like u "*google*") (!= sp ""))})) (sum (as 'I64 (and (like US "*google*") (!= SPS ""))))) -- true (.sys.exec "rm -rf /tmp/rfl_fdom_like/") -- 0 From 1eec4a7e12afb63a0f8744a3d34546a07b7181b5 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Fri, 18 Sep 2026 14:25:15 +0300 Subject: [PATCH 11/20] fix(agg): carve the per-worker accumulator block in words through void* 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 --- src/ops/group.c | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/ops/group.c b/src/ops/group.c index be7f3b4f8..0aaeac872 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -12136,33 +12136,35 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (sc_any_nullable) sc_words += n_aggs; /* nn_count */ size_t sc_bytes = ((sc_words * sizeof(int64_t)) + sc_line - 1) / sc_line * sc_line; for (uint32_t w = 0; w < sc_n; w++) { - uint8_t* raw = (uint8_t*)scratch_calloc(&sc_acc[w]._h_sum, sc_bytes + sc_line); + void* raw = scratch_calloc(&sc_acc[w]._h_sum, sc_bytes + sc_line); if (!raw) { alloc_ok = false; break; } - uint8_t* blk = (uint8_t*)(((uintptr_t)raw + sc_line - 1) & ~(uintptr_t)(sc_line - 1)); - size_t off = 0; - sc_acc[w].count = (int64_t*)(blk + off); off += sizeof(int64_t); + /* 8-byte words from the first line boundary inside the block: + * every array below is a whole number of words. */ + int64_t* blk = (int64_t*)(void*)(((uintptr_t)raw + sc_line - 1) & ~(uintptr_t)(sc_line - 1)); + size_t off = 0; /* in words */ + sc_acc[w].count = blk + off; off += 1; if (need_flags & DA_NEED_SUM) { - sc_acc[w].sum = (da_val_t*)(blk + off); off += n_aggs * sizeof(da_val_t); + sc_acc[w].sum = (da_val_t*)(void*)(blk + off); off += n_aggs; } if (need_flags & DA_NEED_MIN) { - sc_acc[w].min_val = (da_val_t*)(blk + off); off += n_aggs * sizeof(da_val_t); + sc_acc[w].min_val = (da_val_t*)(void*)(blk + off); off += n_aggs; for (uint32_t a = 0; a < n_aggs; a++) { if (group_fp_type(agg_types[a])) sc_acc[w].min_val[a].f = DBL_MAX; else sc_acc[w].min_val[a].i = INT64_MAX; } } if (need_flags & DA_NEED_MAX) { - sc_acc[w].max_val = (da_val_t*)(blk + off); off += n_aggs * sizeof(da_val_t); + sc_acc[w].max_val = (da_val_t*)(void*)(blk + off); off += n_aggs; for (uint32_t a = 0; a < n_aggs; a++) { if (group_fp_type(agg_types[a])) sc_acc[w].max_val[a].f = -DBL_MAX; else sc_acc[w].max_val[a].i = INT64_MIN; } } if (need_flags & DA_NEED_SUMSQ) { - sc_acc[w].sumsq_f64 = (double*)(blk + off); off += n_aggs * sizeof(double); + sc_acc[w].sumsq_f64 = (double*)(void*)(blk + off); off += n_aggs; } if (sc_any_nullable) { - sc_acc[w].nn_count = (int64_t*)(blk + off); off += n_aggs * sizeof(int64_t); + sc_acc[w].nn_count = blk + off; off += n_aggs; } } if (!alloc_ok) { From 3d401f047a02e05a5c3d637b759618fb451a9be5 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 14:30:02 +0200 Subject: [PATCH 12/20] fix(io): read and read-bytes read until EOF, not to the reported size MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/docs/language/functions.md | 19 ++++++++- docs/docs/reference/all-functions.md | 4 +- src/ops/builtins.c | 61 +++++++++++++++++++++----- test/rfl/io/read_until_eof.rfl | 64 ++++++++++++++++++++++++++++ 4 files changed, 133 insertions(+), 15 deletions(-) create mode 100644 test/rfl/io/read_until_eof.rfl diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index c6c6eb4d0..04934d8c0 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -438,12 +438,27 @@ Cross-temporal comparisons are supported: dates, times, and timestamps are all c | `format` | variadic | Format value to string (% is placeholder) | `(format "val=%" 42)` → `"val=42"` | | `.csv.read` | variadic | Load CSV file into table | `(.csv.read "data.csv")` | | `.csv.write` | variadic | Write table to CSV file | `(.csv.write trades "out.csv")` | -| `read` | unary | Read file contents as string | `(read "file.txt")` | -| `read-bytes` | unary | Read file contents as a `U8` byte vector | `(read-bytes "file.bin")` | +| `read` | unary | Read file contents as string, to EOF | `(read "file.txt")` | +| `read-bytes` | unary | Read file contents as a `U8` byte vector, to EOF | `(read-bytes "file.bin")` | | `write` | binary | Write a string to a file | `(write "file.txt" "content")` | | `write-bytes` | binary | Write a `U8` byte vector to a file | `(write-bytes "file.bin" bytes)` | | `load` | unary | Load and evaluate a Rayfall script; a relative path is tried against the working directory, then below `RAYFORCE_HOME` | `(load "lib.rfl")` | +`read` and `read-bytes` read until EOF rather than to the size the file +reports. That matters for anything whose reported size is not its content +length: every file under `/proc` and `/sys` reports `0` while yielding data, +FIFOs and character devices cannot be seeked at all, and an ordinary file may +change between the measure and the read. + +```lisp +(read "/proc/sys/kernel/hostname") ;; => "sita\n" +(read "/proc/sys/kernel/random/uuid") ;; => a fresh UUID per call +(.fs.size "/proc/sys/kernel/hostname") ;; => 0 (what the kernel reports) +``` + +`.fs.size` still reports what the OS reports — the two disagreeing on a +special file is expected, not a bug. + ## Control Flow | Function | Type | Description | Example | diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index 9f6a543ae..8eed89f6c 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -612,8 +612,8 @@ Printing, file I/O, CSV loading, and script execution. | `format` | variadic | — | Format value to string (% as placeholder) | `(format "val=%" 42)` → `"val=42"` | | `.csv.read` | variadic | restricted | Load CSV file into table (mmap, parallel parse) | `(.csv.read "data.csv")` | | `.csv.write` | variadic | restricted | Write table to CSV file | `(.csv.write trades "out.csv")` | -| `read` | unary | restricted | Read file contents as string | `(read "file.txt")` | -| `read-bytes` | unary | restricted | Read file contents as a `U8` byte vector | `(read-bytes "file.bin")` | +| `read` | unary | restricted | Read file contents as string, to EOF | `(read "/proc/self/cmdline")` | +| `read-bytes` | unary | restricted | Read file contents as a `U8` byte vector, to EOF | `(read-bytes "file.bin")` | | `write` | binary | restricted | Write a string to a file | `(write "file.txt" "content")` | | `write-bytes` | binary | restricted | Write a `U8` byte vector to a file | `(write-bytes "file.bin" bytes)` | | `load` | unary | restricted | Load and evaluate a Rayfall script file. A relative path is tried against the working directory, then below `RAYFORCE_HOME` when set; absolute paths are used as given; a failure names every path tried | `(load "lib.rfl")` | diff --git a/src/ops/builtins.c b/src/ops/builtins.c index f4e85a57e..7335fc9e0 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -2045,24 +2045,63 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { FILE* fp = fopen(path, "rb"); if (!fp) return ray_error("io", NULL); - if (fseek(fp, 0, SEEK_END) != 0) { fclose(fp); return ray_error("io", NULL); } - long sz = ftell(fp); - if (sz < 0) { fclose(fp); return ray_error("io", NULL); } - if (fseek(fp, 0, SEEK_SET) != 0) { fclose(fp); return ray_error("io", NULL); } - ray_t* result = ray_vec_new(RAY_U8, (int64_t)sz); + /* Read until EOF rather than to the size the file reports (#572). + * Everything under /proc and /sys reports 0 while yielding data, so + * sizing the read made those files come back as a well-formed empty + * value — no error, no short-read signal, and a caller branching on + * the content silently took the wrong branch. Seeking also fails + * outright on a FIFO, and an ordinary file that changed size between + * the measure and the read became a spurious io error. + * + * The reported size is still worth having: where it is positive it is + * an exact capacity hint, so the common case does one allocation and + * one read with no growth. */ + long hint = 0; + if (fseek(fp, 0, SEEK_END) == 0) { + hint = ftell(fp); + /* A directory seeks fine and reports LONG_MAX here, so an + * implausible hint is treated as no hint rather than trusted into + * an overflow. The read itself is what rejects a directory: fread + * sets the error flag (EISDIR) and we return io. */ + if (hint < 0 || hint > (long)(INT64_MAX / 2) || fseek(fp, 0, SEEK_SET) != 0) + hint = 0; + } + /* Unseekable (pipe, character device) or size-0-but-readable: start at + * a page and grow. The extra byte on a hinted read is what lets a + * single fread distinguish "exactly the hinted size" from "more than + * the hint", so a file that grew is read whole instead of truncated. */ + int64_t cap = hint > 0 ? (int64_t)hint + 1 : 4096; + + ray_t* result = ray_vec_new(RAY_U8, cap); if (!result || RAY_IS_ERR(result)) { fclose(fp); return result ? result : ray_error("oom", NULL); } - result->len = (int64_t)sz; - size_t rd = sz > 0 ? fread(ray_data(result), 1, (size_t)sz, fp) : 0; - int close_rc = fclose(fp); - if (rd != (size_t)sz || close_rc != 0) { - ray_release(result); - return ray_error("io", NULL); + int64_t len = 0; + for (;;) { + if (len == cap) { + int64_t ncap = cap * 2; + ray_t* grown = ray_vec_new(RAY_U8, ncap); + if (!grown || RAY_IS_ERR(grown)) { + ray_release(result); fclose(fp); + return grown ? grown : ray_error("oom", NULL); + } + memcpy(ray_data(grown), ray_data(result), (size_t)len); + ray_release(result); + result = grown; cap = ncap; + } + size_t got = fread((uint8_t*)ray_data(result) + len, 1, (size_t)(cap - len), fp); + len += (int64_t)got; + if (got == 0) { + if (ferror(fp)) { ray_release(result); fclose(fp); return ray_error("io", NULL); } + break; /* EOF */ + } } + + if (fclose(fp) != 0) { ray_release(result); return ray_error("io", NULL); } + result->len = len; return result; } diff --git a/test/rfl/io/read_until_eof.rfl b/test/rfl/io/read_until_eof.rfl new file mode 100644 index 000000000..213e8675e --- /dev/null +++ b/test/rfl/io/read_until_eof.rfl @@ -0,0 +1,64 @@ +;; `read` / `read-bytes` must read until EOF, not to the size the file +;; reports — issue #572. +;; +;; The size came from fseek/ftell, and everything under /proc and /sys +;; reports 0 while yielding data when actually read. The failure was +;; silent: no error, no short-read signal, just a well-formed "" that any +;; caller branching on the content would act on. Sizing from the file also +;; made an ordinary file that changed between the measure and the read an +;; io error rather than a successful read. + +;; ────────────── pre-flight ────────────── +(.sys.exec "rm -rf /tmp/rf_read_eof && mkdir -p /tmp/rf_read_eof") +(.sys.exec "printf 'hello world\\n' > /tmp/rf_read_eof/ordinary.txt") +(.sys.exec "printf '' > /tmp/rf_read_eof/empty.txt") +(.sys.exec "head -c 300000 /dev/zero | tr '\\0' x > /tmp/rf_read_eof/big.txt") + +;; ────────────── ordinary files still behave ────────────── +(read "/tmp/rf_read_eof/ordinary.txt") -- "hello world\n" +(count (read-bytes "/tmp/rf_read_eof/ordinary.txt")) -- 12 + +;; A genuinely empty file is still "" — the fix must not turn absence of +;; content into an error. +(read "/tmp/rf_read_eof/empty.txt") -- "" +(count (read-bytes "/tmp/rf_read_eof/empty.txt")) -- 0 + +;; Larger than any single growth step, to exercise the loop. +(count (read "/tmp/rf_read_eof/big.txt")) -- 300000 +(count (read-bytes "/tmp/rf_read_eof/big.txt")) -- 300000 + +;; ────────────── files that report size 0 but have content ────────────── +;; /proc/sys/kernel/hostname is the issue's own example: stat says 0, the +;; kernel yields the host name. Cross-checked against uname(1) so this +;; asserts the right content, not merely that something was read. +(> (count (read "/proc/sys/kernel/hostname")) 0) -- true +(== (first (split (read "/proc/sys/kernel/hostname") "\n")) (first (split (get (.sys.exec "uname -n" 'out) 'out) "\n"))) -- true + +;; .sys.info's hostname comes from gethostname(2) rather than from procfs; +;; the two must agree, which also ties #573's identity to this path. +(== (get (.sys.info) 'hostname) (first (split (read "/proc/sys/kernel/hostname") "\n"))) -- true + +;; The entropy source the reporter actually wanted: a fresh UUID per read. +(count (first (split (read "/proc/sys/kernel/random/uuid") "\n"))) -- 36 +;; Two reads of it must differ — proof we are reading the file, not a +;; cached or truncated view of it. +(== (read "/proc/sys/kernel/random/uuid") (read "/proc/sys/kernel/random/uuid")) -- false + +;; read-bytes takes the same path and must agree. +(> (count (read-bytes "/proc/sys/kernel/hostname")) 0) -- true + +;; ────────────── pipes ────────────── +;; A FIFO cannot be seeked, so sizing from the file made this an io error. +;; Reading until EOF makes it work like any other stream. +(.sys.exec "rm -f /tmp/rf_read_eof/fifo && mkfifo /tmp/rf_read_eof/fifo") +(.sys.exec "(printf 'from-a-fifo\\n' > /tmp/rf_read_eof/fifo &) ; sleep 0") +(read "/tmp/rf_read_eof/fifo") -- "from-a-fifo\n" + +;; ────────────── errors stay loud ────────────── +(try (read "/tmp/rf_read_eof/does-not-exist") (fn [e] 'io-rejected)) -- 'io-rejected +(try (read-bytes "/tmp/rf_read_eof/does-not-exist") (fn [e] 'io-rejected)) -- 'io-rejected +;; A directory is not readable as a file. +(try (read "/tmp/rf_read_eof") (fn [e] 'io-rejected)) -- 'io-rejected + +;; ────────────── cleanup ────────────── +(.sys.exec "rm -rf /tmp/rf_read_eof") From 946e2ef0dd5b84d4196d9163a5fae63cf900e338 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 14:56:57 +0200 Subject: [PATCH 13/20] fix(guid): seed from the OS, independently of rand MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/docs/language/functions.md | 19 ++++++- docs/docs/reference/all-functions.md | 4 +- src/ops/system.c | 82 +++++++++++++++++++++++----- test/rfl/lang/guid_entropy.rfl | 40 ++++++++++++++ 4 files changed, 127 insertions(+), 18 deletions(-) create mode 100644 test/rfl/lang/guid_entropy.rfl diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index c6c6eb4d0..1967b0b1d 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -426,7 +426,24 @@ Cross-temporal comparisons are supported: dates, times, and timestamps are all c | `as` | binary | Cast value to another type | `(as 'i64 "42")` → `42` | | `nil?` | unary | Test if value is null; element-wise inside query expressions | `(nil? x)` | | `rc` | unary | Reference count of an object | `(rc x)` → `1` | -| `guid` | unary | Generate a vector of N GUIDs (`(guid 0)` → `[]`) | `(guid 1)` | +| `guid` | unary | Generate a vector of N v4 GUIDs (`(guid 0)` → `[]`) | `(guid 1)` | + +`guid` and `rand` draw from **different** sources on purpose: + +- `guid` is seeded from the OS at first use, per thread, so values are unique + across processes and machines. That is the property the type exists to + provide, so it is not something to trade for reproducibility. +- `rand` is deterministic — the same process-wide sequence every run. That is + what makes tests and simulations reproducible, and changing `guid`'s seeding + deliberately left it alone. + +```lisp +(first (guid 1)) ;; a different value in every process +(rand 3 1000) ;; [383 886 777] in every process +``` + +If you need a reproducible stream, use `rand`. If you need identifiers that do +not collide between two processes writing into the same table, use `guid`. ## I/O & File Operations diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index 9f6a543ae..a72693202 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -287,7 +287,7 @@ Operations on vectors and lists as collections — set operations, indexing, sea | `where` | unary | — | Indices where boolean vector is true | `(where [true false true])` → `[0 2]` | | `group` | unary | — | Group indices by value (returns dict) | `(group ['a 'b 'a])` → dict | | `diverse` | unary | — | Check if all elements are unique (no duplicates) | `(diverse [1 2 3])` → `true` | -| `rand` | binary | — | Generate N random values from range or sample from vector | `(rand 3 100)` → 3 random ints 0..99 | +| `rand` | binary | — | Generate N random values from range or sample from vector. **Deterministic**: the same sequence in every process | `(rand 3 100)` → 3 random ints 0..99 | | `bin` | binary | — | Binary search — left boundary (sorted input) | `(bin [10 20 30] 25)` → `1` | | `binr` | binary | — | Binary search — right boundary (sorted input) | `(binr [10 20 30] 25)` → `2` | @@ -587,7 +587,7 @@ Type checking, casting, null testing, and object inspection. | `as` | binary | — | Cast value to another type | `(as 'i64 "42")` → `42` | | `nil?` | unary | DAG in queries | Test for null; element-wise over vectors and lists (a `B8` per element), the same in and out of queries | `(nil? [1 0N 3])` → `[false true false]` | | `rc` | unary | — | Get reference count of an object | `(rc x)` → `1` | -| `guid` | unary | — | Generate a vector of N GUIDs (`(guid 0)` → `[]`) | `(guid 1)` | +| `guid` | unary | — | Generate a vector of N v4 GUIDs, seeded from the OS (`(guid 0)` → `[]`) | `(guid 1)` | ```lisp ; Type checking and casting diff --git a/src/ops/system.c b/src/ops/system.c index f2490d35c..873bb9847 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -382,26 +382,78 @@ ray_t* ray_fs_list_fn(ray_t* x) { return result; } +static int64_t ray_os_pid(void); /* defined with the .sys.info helpers */ + +/* Eight bytes of OS entropy. False when no source answered, which the + * caller treats as "fold in less", never as "seed with a constant". */ +static bool guid_os_entropy(uint64_t* out) { +#if defined(RAY_OS_WINDOWS) + (void)out; + return false; /* covered by the process/time material below */ +#else + FILE* f = fopen("/dev/urandom", "rb"); + if (!f) return false; + size_t got = fread(out, 1, sizeof(*out), f); + fclose(f); + return got == sizeof(*out); +#endif +} + +/* Seed for one thread's GUID stream. + * + * This used to come 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 reporter's first value on their + * machine and build was byte-identical to ours (#571). Uniqueness is the + * one property the type exists to provide, and the failure was silent: + * the values are well-formed and carry the correct version-4 nibble. + * + * Seeded from the OS independently of rand(), so rand()'s determinism — + * which is defensible, and which reproducible tests rely on — is left + * exactly as it was. Process id, a high-resolution clock and a stack + * address are always folded in, so even a platform or a chroot where the + * entropy source cannot be reached still cannot hand two processes, or + * two threads, the same stream. */ +static uint64_t guid_seed(void) { + uint64_t s = 0; + if (!guid_os_entropy(&s)) s = 0; + + s ^= (uint64_t)ray_os_pid() * 0x9E3779B97F4A7C15ULL; + s ^= (uint64_t)(uintptr_t)&s; +#if defined(RAY_OS_WINDOWS) + LARGE_INTEGER cnt; + QueryPerformanceCounter(&cnt); + s ^= (uint64_t)cnt.QuadPart * 0xBF58476D1CE4E5B9ULL; + FILETIME ft; + GetSystemTimeAsFileTime(&ft); + s ^= ((uint64_t)ft.dwHighDateTime << 32) | ft.dwLowDateTime; +#else + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) + s ^= ((uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec) * 0xBF58476D1CE4E5B9ULL; + if (clock_gettime(CLOCK_REALTIME, &ts) == 0) + s ^= (uint64_t)ts.tv_sec * 0x94D049BB133111EBULL ^ (uint64_t)ts.tv_nsec; +#endif + + /* splitmix64 finaliser: the folded material is structured (a small pid, + * a slow-moving clock), and xorshift64* needs its state well mixed or + * the first few outputs stay correlated with it. */ + s ^= s >> 30; s *= 0xBF58476D1CE4E5B9ULL; + s ^= s >> 27; s *= 0x94D049BB133111EBULL; + s ^= s >> 31; + return s ? s : 0x9E3779B97F4A7C15ULL; +} + /* xorshift64* — ~1ns per 64-bit word, vs rand()'s ~10ns for 1 byte. - * Per-thread state seeded once with the result of rand() to keep the - * (guid n) sequence varying across program runs (rand() is itself - * seeded by the runtime). v4 UUID quality only requires the version - * and variant nibbles to be correct; the remaining 122 bits are - * pseudo-random and xorshift64* is more than sufficient. */ + * Per-thread state seeded once from guid_seed(). v4 UUID quality only + * requires the version and variant nibbles to be correct; the remaining + * 122 bits are pseudo-random and xorshift64* is more than sufficient. */ static __thread uint64_t guid_rng_state = 0; static inline uint64_t guid_rng_next(void) { uint64_t x = guid_rng_state; - if (RAY_UNLIKELY(x == 0)) { - /* Mix rand() into a non-zero seed. rand() returns ≤ 31 bits, so - * combine three calls plus an address-derived constant for - * thread-distinct initialisation. */ - uint64_t a = (uint64_t)rand(); - uint64_t b = (uint64_t)rand(); - uint64_t c = (uint64_t)rand(); - x = (a << 33) ^ (b << 17) ^ c ^ 0x9E3779B97F4A7C15ULL; - if (x == 0) x = 0x9E3779B97F4A7C15ULL; - } + if (RAY_UNLIKELY(x == 0)) x = guid_seed(); x ^= x >> 12; x ^= x << 25; x ^= x >> 27; diff --git a/test/rfl/lang/guid_entropy.rfl b/test/rfl/lang/guid_entropy.rfl new file mode 100644 index 000000000..b77ceadbe --- /dev/null +++ b/test/rfl/lang/guid_entropy.rfl @@ -0,0 +1,40 @@ +;; `guid` must be unique across processes — issue #571. +;; +;; The generator seeded its per-thread xorshift state from rand(), and +;; nothing in the tree ever called srand(), so rand() ran from libc's +;; default seed of 1. Every process therefore produced the same GUID +;; sequence: the reporter's first value on their machine and build was +;; byte-identical to ours, 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 the +;; failure is silent — the values are well-formed and carry the correct +;; version-4 nibble. + +;; ────────────── within one process ────────────── +;; Already held before the fix, asserted so a future seeding change cannot +;; regress it into a constant. +(== (first (guid 1)) (first (guid 1))) -- false +(count (distinct (guid 1000))) -- 1000 + +;; Shape is unchanged — still a guid atom, not some other type. +(type (first (guid 1))) -- 'guid + +;; ────────────── across processes ────────────── +;; The actual regression. Two fresh processes must not agree on their +;; first GUID. Run through .sys.exec's capture form so the comparison is +;; on the values themselves, not on an exit code. +(.sys.exec "rm -rf /tmp/rf_guid && mkdir -p /tmp/rf_guid") +(.sys.exec "printf '(println (first (guid 1)))\\n' > /tmp/rf_guid/g.rfl") +(.sys.exec "./rayforce -c 1 /tmp/rf_guid/g.rfl > /tmp/rf_guid/a.txt 2>/dev/null") +(.sys.exec "./rayforce -c 1 /tmp/rf_guid/g.rfl > /tmp/rf_guid/b.txt 2>/dev/null") + +;; Both runs produced a GUID at all (36 chars + newline), so a comparison +;; of two empty strings cannot masquerade as a pass. +(count (first (split (read "/tmp/rf_guid/a.txt") "\n"))) -- 36 +(count (first (split (read "/tmp/rf_guid/b.txt") "\n"))) -- 36 + +;; And they differ. +(== (read "/tmp/rf_guid/a.txt") (read "/tmp/rf_guid/b.txt")) -- false + +(.sys.exec "rm -rf /tmp/rf_guid") From 24aceade878dc22951ff2768bc3fbdc3c5997257 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 15:28:56 +0200 Subject: [PATCH 14/20] test(io): move the procfs cases off the .rfl suite; reject directories explicitly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/ops/builtins.c | 9 +++++ test/rfl/io/read_until_eof.rfl | 27 ++++---------- test/test_lang.c | 66 ++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 20 deletions(-) diff --git a/src/ops/builtins.c b/src/ops/builtins.c index 7335fc9e0..e2ca8c9d6 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -2043,6 +2043,15 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { if (!path || ray_str_len(path_obj) == 0) return ray_error("domain", "%s: empty path", op); + /* Reject a directory up front, as `load` does (see the S_ISDIR check in + * ray_load_file_fn). Platforms disagree on what fopen/fread do with + * one — Linux fails the read with EISDIR, others can succeed and + * return nothing — and "" for a directory would be exactly the silent + * wrong answer this change exists to remove. */ + struct stat dst; + if (stat(path, &dst) == 0 && S_ISDIR(dst.st_mode)) + return ray_error("io", "%s \"%s\": is a directory", op, path); + FILE* fp = fopen(path, "rb"); if (!fp) return ray_error("io", NULL); diff --git a/test/rfl/io/read_until_eof.rfl b/test/rfl/io/read_until_eof.rfl index 213e8675e..129374434 100644 --- a/test/rfl/io/read_until_eof.rfl +++ b/test/rfl/io/read_until_eof.rfl @@ -12,7 +12,7 @@ (.sys.exec "rm -rf /tmp/rf_read_eof && mkdir -p /tmp/rf_read_eof") (.sys.exec "printf 'hello world\\n' > /tmp/rf_read_eof/ordinary.txt") (.sys.exec "printf '' > /tmp/rf_read_eof/empty.txt") -(.sys.exec "head -c 300000 /dev/zero | tr '\\0' x > /tmp/rf_read_eof/big.txt") +(.sys.exec "dd if=/dev/zero of=/tmp/rf_read_eof/big.txt bs=1000 count=300 2>/dev/null") ;; ────────────── ordinary files still behave ────────────── (read "/tmp/rf_read_eof/ordinary.txt") -- "hello world\n" @@ -27,25 +27,12 @@ (count (read "/tmp/rf_read_eof/big.txt")) -- 300000 (count (read-bytes "/tmp/rf_read_eof/big.txt")) -- 300000 -;; ────────────── files that report size 0 but have content ────────────── -;; /proc/sys/kernel/hostname is the issue's own example: stat says 0, the -;; kernel yields the host name. Cross-checked against uname(1) so this -;; asserts the right content, not merely that something was read. -(> (count (read "/proc/sys/kernel/hostname")) 0) -- true -(== (first (split (read "/proc/sys/kernel/hostname") "\n")) (first (split (get (.sys.exec "uname -n" 'out) 'out) "\n"))) -- true - -;; .sys.info's hostname comes from gethostname(2) rather than from procfs; -;; the two must agree, which also ties #573's identity to this path. -(== (get (.sys.info) 'hostname) (first (split (read "/proc/sys/kernel/hostname") "\n"))) -- true - -;; The entropy source the reporter actually wanted: a fresh UUID per read. -(count (first (split (read "/proc/sys/kernel/random/uuid") "\n"))) -- 36 -;; Two reads of it must differ — proof we are reading the file, not a -;; cached or truncated view of it. -(== (read "/proc/sys/kernel/random/uuid") (read "/proc/sys/kernel/random/uuid")) -- false - -;; read-bytes takes the same path and must agree. -(> (count (read-bytes "/proc/sys/kernel/hostname")) 0) -- true +;; ────────────── files that cannot be sized ────────────── +;; The issue's own examples are under /proc, which is Linux-only, and this +;; harness has no way to skip a line per platform — they live in +;; test_lang.c as lang/io/read_procfs_zero_size, which SKIPs off Linux. +;; The FIFO below is the portable member of the same class: it cannot be +;; seeked at all, so it must be read to EOF on every platform. ;; ────────────── pipes ────────────── ;; A FIFO cannot be seeked, so sizing from the file made this an io error. diff --git a/test/test_lang.c b/test/test_lang.c index 3ca768565..cd0367a22 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -8971,6 +8971,70 @@ static test_result_t test_query_wide_table_over_64_cols(void) { } + +/* `read` must read until EOF, not to the size the file reports (#572). + * + * Every file under /proc and /sys reports st_size 0 while yielding data, + * which made `read` return a well-formed empty string: no error, no + * short-read signal, and a caller branching on the content silently took + * the wrong branch. This lives in C rather than in the .rfl suite because + * procfs is Linux-only and the .rfl harness has no way to skip; the + * portable half of the behaviour (ordinary files, a FIFO, error paths) is + * covered in test/rfl/io/read_until_eof.rfl on every platform. */ +static test_result_t test_read_procfs_reports_zero_size(void) { +#if !defined(__linux__) + SKIP("procfs is Linux-only"); +#else + const char* path = "/proc/sys/kernel/hostname"; + FILE* probe = fopen(path, "rb"); + if (!probe) SKIP("procfs not mounted"); + fclose(probe); + + /* The premise: the file reports zero bytes. */ + struct stat st; + TEST_ASSERT(stat(path, &st) == 0, "stat procfs path"); + TEST_ASSERT_EQ_I((int64_t)st.st_size, 0); + + ray_t* arg = ray_str(path, strlen(path)); + ray_t* got = ray_read_file_fn(arg); + ray_release(arg); + TEST_ASSERT_NOT_NULL(got); + TEST_ASSERT(!RAY_IS_ERR(got), "read of a procfs file must not error"); + + /* ...and yet it has content. */ + TEST_ASSERT(ray_str_len(got) > 0, "procfs read must not come back empty"); + + /* The right content: compare against the same value gethostname gives, + * so this asserts correctness rather than merely non-emptiness. */ + char host[256] = {0}; + TEST_ASSERT(gethostname(host, sizeof(host) - 1) == 0, "gethostname"); + size_t hlen = strlen(host); + TEST_ASSERT((size_t)ray_str_len(got) >= hlen, "read shorter than the host name"); + TEST_ASSERT(memcmp(ray_str_ptr(got), host, hlen) == 0, "procfs host name mismatch"); + ray_release(got); + + /* A file whose every read differs proves we re-read rather than + * returning a cached or truncated view. */ + const char* upath = "/proc/sys/kernel/random/uuid"; + FILE* uprobe = fopen(upath, "rb"); + if (!uprobe) PASS(); + fclose(uprobe); + + ray_t* ua = ray_str(upath, strlen(upath)); + ray_t* u1 = ray_read_file_fn(ua); + ray_t* u2 = ray_read_file_fn(ua); + ray_release(ua); + TEST_ASSERT(!RAY_IS_ERR(u1) && !RAY_IS_ERR(u2), "uuid reads must not error"); + TEST_ASSERT(ray_str_len(u1) >= 36, "uuid read too short"); + TEST_ASSERT(ray_str_len(u1) != ray_str_len(u2) || + memcmp(ray_str_ptr(u1), ray_str_ptr(u2), (size_t)ray_str_len(u1)) != 0, + "two uuid reads returned identical bytes"); + ray_release(u1); + ray_release(u2); + PASS(); +#endif +} + const test_entry_t lang_entries[] = { { "lang/env/scope_frame_grows", test_env_scope_frame_grows, lang_setup, lang_teardown }, { "lang/query/wide_table_over_64_cols", test_query_wide_table_over_64_cols, lang_setup, lang_teardown }, @@ -9387,5 +9451,7 @@ const test_entry_t lang_entries[] = { { "lang/temporal/extract_epoch", test_temporal_extract_epoch, lang_setup, lang_teardown }, { "lang/temporal/date_trunc_month_case", test_temporal_date_trunc_month_case, lang_setup, lang_teardown }, + { "lang/io/read_procfs_zero_size", test_read_procfs_reports_zero_size, lang_setup, lang_teardown }, + { NULL, NULL, NULL, NULL }, }; From a473a8d5dfad3aa5e6680a58e4edd69ddf916a98 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 16:28:36 +0200 Subject: [PATCH 15/20] fix(io): bound an unsized read by the heap's own budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/ops/builtins.c | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/ops/builtins.c b/src/ops/builtins.c index e2ca8c9d6..516ca9ea3 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -61,6 +61,7 @@ static inline double clear_neg_zero(double v) { #include #if !defined(RAY_OS_WINDOWS) #include +#include "mem/heap.h" /* ray_heap_anon_watermark — bound for an unsized read */ #include #include #include @@ -2069,10 +2070,11 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { long hint = 0; if (fseek(fp, 0, SEEK_END) == 0) { hint = ftell(fp); - /* A directory seeks fine and reports LONG_MAX here, so an - * implausible hint is treated as no hint rather than trusted into - * an overflow. The read itself is what rejects a directory: fread - * sets the error flag (EISDIR) and we return io. */ + /* An implausible hint is treated as no hint rather than trusted + * into an overflow — a directory, for instance, seeks fine and + * reports LONG_MAX. (Directories are already rejected by the + * S_ISDIR check above; this guard is for anything else that + * reports a size it cannot back.) */ if (hint < 0 || hint > (long)(INT64_MAX / 2) || fseek(fp, 0, SEEK_SET) != 0) hint = 0; } @@ -2092,6 +2094,19 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { for (;;) { if (len == cap) { int64_t ncap = cap * 2; + /* An unsized stream — /dev/zero, a live FIFO — has no natural + * end. Sizing from the file used to return "" for one + * instantly; growing without a bound instead walks the process + * into OOM, which is a worse answer than either. Bound it by + * the heap's own anon watermark (the existing spill threshold, + * which resolves to physical RAM) rather than by a new + * constant, and say so rather than dying. */ + int64_t budget = ray_heap_anon_watermark(); + if (ncap <= 0 || (budget > 0 && ncap > budget)) { + ray_release(result); fclose(fp); + return ray_error("io", "%s \"%s\": input exceeds the readable budget of %lld bytes", + op, path, (long long)budget); + } ray_t* grown = ray_vec_new(RAY_U8, ncap); if (!grown || RAY_IS_ERR(grown)) { ray_release(result); fclose(fp); From fb900f5cc45b5eb0469152e22a8aa7942514e397 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 17:09:12 +0200 Subject: [PATCH 16/20] fix(io): bound the read against remaining headroom, not the spill threshold MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/ops/builtins.c | 48 ++++++++++++++++++----- test/rfl/io/read_until_eof.rfl | 72 ++++++++++++++++++++-------------- test/test_lang.c | 43 ++++++++++++++++++++ 3 files changed, 124 insertions(+), 39 deletions(-) diff --git a/src/ops/builtins.c b/src/ops/builtins.c index 516ca9ea3..6daf505dc 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -59,9 +59,9 @@ static inline double clear_neg_zero(double v) { #include #include #include +#include "mem/heap.h" /* ray_heap_anon_watermark/committed — read budget */ #if !defined(RAY_OS_WINDOWS) #include -#include "mem/heap.h" /* ray_heap_anon_watermark — bound for an unsized read */ #include #include #include @@ -2037,6 +2037,28 @@ ray_t* ray_type_fn(ray_t* val) { return ray_sym(id); } +/* Ceiling for one `read` / `read-bytes` result. + * + * The heap's anon watermark is NOT a ceiling: crossing it routes the + * mapping to a spill file rather than failing ("this never rejects work, + * it just picks disk over RAM" — mem/heap.c). Bounding by the watermark + * itself would therefore trade an OOM kill for filling the spill file, + * which is why this bounds against the *remaining* headroom instead, and + * takes a quarter of it so an endless stream errors well before the first + * spill. A quarter, and the "unknown RAM stays permissive" convention, + * match the admission gate in ops/cdfuse.c, which rides the same + * watermark — so ray_heap_set_anon_watermark still steers this and no new + * knob is introduced. + * + * Returns 0 for "no bound known", which callers treat as permissive. */ +static int64_t read_size_budget(void) { + int64_t wm = ray_heap_anon_watermark(); + if (wm <= 0) return 0; /* RAM unknown → permissive */ + int64_t avail = wm - ray_heap_anon_committed(); + if (avail <= 0) return 0; + return avail / 4; +} + static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { if (path_obj->type != -RAY_STR) return ray_error("type", "%s: path must be str, got %s", op, ray_type_name(path_obj->type)); @@ -2048,10 +2070,14 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { * ray_load_file_fn). Platforms disagree on what fopen/fread do with * one — Linux fails the read with EISDIR, others can succeed and * return nothing — and "" for a directory would be exactly the silent - * wrong answer this change exists to remove. */ + * wrong answer this change exists to remove. POSIX-only: + * is guarded out on Windows and MSVC has no S_ISDIR, and unlike + * ray_load_file_fn this function is compiled on both paths. */ +#if !defined(RAY_OS_WINDOWS) struct stat dst; if (stat(path, &dst) == 0 && S_ISDIR(dst.st_mode)) return ray_error("io", "%s \"%s\": is a directory", op, path); +#endif FILE* fp = fopen(path, "rb"); if (!fp) return ray_error("io", NULL); @@ -2084,6 +2110,13 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { * the hint", so a file that grew is read whole instead of truncated. */ int64_t cap = hint > 0 ? (int64_t)hint + 1 : 4096; + /* Same ceiling on both paths: a file claiming more than the budget is + * refused here rather than left to fail inside the allocator. */ + const int64_t budget = read_size_budget(); + if (budget > 0 && cap > budget) + return ray_error("io", "%s \"%s\": %lld bytes exceeds the readable budget of %lld bytes", + op, path, (long long)cap, (long long)budget); + ray_t* result = ray_vec_new(RAY_U8, cap); if (!result || RAY_IS_ERR(result)) { fclose(fp); @@ -2093,20 +2126,17 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { int64_t len = 0; for (;;) { if (len == cap) { - int64_t ncap = cap * 2; /* An unsized stream — /dev/zero, a live FIFO — has no natural * end. Sizing from the file used to return "" for one * instantly; growing without a bound instead walks the process - * into OOM, which is a worse answer than either. Bound it by - * the heap's own anon watermark (the existing spill threshold, - * which resolves to physical RAM) rather than by a new - * constant, and say so rather than dying. */ - int64_t budget = ray_heap_anon_watermark(); - if (ncap <= 0 || (budget > 0 && ncap > budget)) { + * into OOM or into the spill file. Check before doubling, so + * the multiply itself cannot overflow. */ + if (cap > INT64_MAX / 2 || (budget > 0 && cap * 2 > budget)) { ray_release(result); fclose(fp); return ray_error("io", "%s \"%s\": input exceeds the readable budget of %lld bytes", op, path, (long long)budget); } + int64_t ncap = cap * 2; ray_t* grown = ray_vec_new(RAY_U8, ncap); if (!grown || RAY_IS_ERR(grown)) { ray_release(result); fclose(fp); diff --git a/test/rfl/io/read_until_eof.rfl b/test/rfl/io/read_until_eof.rfl index 129374434..a4ea55ab6 100644 --- a/test/rfl/io/read_until_eof.rfl +++ b/test/rfl/io/read_until_eof.rfl @@ -7,45 +7,57 @@ ;; caller branching on the content would act on. Sizing from the file also ;; made an ordinary file that changed between the measure and the read an ;; io error rather than a successful read. +;; +;; The procfs cases from the issue are Linux-only and this harness has no +;; per-platform skip, so they live in test_lang.c as +;; lang/io/read_procfs_zero_size. The FIFO cases below are the portable +;; members of the same class: a pipe cannot be seeked, so it must be read +;; to EOF on every platform. +;; +;; Paths carry the pid: this suite may run concurrently with another copy +;; of itself on a shared runner, and a shared FIFO is worse than a shared +;; file — `read` blocks in fopen until a writer appears, so a collision +;; would hang rather than fail. ;; ────────────── pre-flight ────────────── -(.sys.exec "rm -rf /tmp/rf_read_eof && mkdir -p /tmp/rf_read_eof") -(.sys.exec "printf 'hello world\\n' > /tmp/rf_read_eof/ordinary.txt") -(.sys.exec "printf '' > /tmp/rf_read_eof/empty.txt") -(.sys.exec "dd if=/dev/zero of=/tmp/rf_read_eof/big.txt bs=1000 count=300 2>/dev/null") +(set d (format "/tmp/rf_read_eof_%" (get (.sys.info) 'pid))) +(.sys.exec (format "rm -rf % && mkdir -p %" d d)) +(.sys.exec (format "printf 'hello world\\n' > %/ordinary.txt" d)) +(.sys.exec (format "printf '' > %/empty.txt" d)) +(.sys.exec (format "dd if=/dev/zero of=%/big.txt bs=1000 count=300 2>/dev/null" d)) ;; ────────────── ordinary files still behave ────────────── -(read "/tmp/rf_read_eof/ordinary.txt") -- "hello world\n" -(count (read-bytes "/tmp/rf_read_eof/ordinary.txt")) -- 12 +(read (format "%/ordinary.txt" d)) -- "hello world\n" +(count (read-bytes (format "%/ordinary.txt" d))) -- 12 ;; A genuinely empty file is still "" — the fix must not turn absence of ;; content into an error. -(read "/tmp/rf_read_eof/empty.txt") -- "" -(count (read-bytes "/tmp/rf_read_eof/empty.txt")) -- 0 - -;; Larger than any single growth step, to exercise the loop. -(count (read "/tmp/rf_read_eof/big.txt")) -- 300000 -(count (read-bytes "/tmp/rf_read_eof/big.txt")) -- 300000 - -;; ────────────── files that cannot be sized ────────────── -;; The issue's own examples are under /proc, which is Linux-only, and this -;; harness has no way to skip a line per platform — they live in -;; test_lang.c as lang/io/read_procfs_zero_size, which SKIPs off Linux. -;; The FIFO below is the portable member of the same class: it cannot be -;; seeked at all, so it must be read to EOF on every platform. - -;; ────────────── pipes ────────────── -;; A FIFO cannot be seeked, so sizing from the file made this an io error. -;; Reading until EOF makes it work like any other stream. -(.sys.exec "rm -f /tmp/rf_read_eof/fifo && mkfifo /tmp/rf_read_eof/fifo") -(.sys.exec "(printf 'from-a-fifo\\n' > /tmp/rf_read_eof/fifo &) ; sleep 0") -(read "/tmp/rf_read_eof/fifo") -- "from-a-fifo\n" +(read (format "%/empty.txt" d)) -- "" +(count (read-bytes (format "%/empty.txt" d))) -- 0 + +;; Sized file, larger than the unhinted starting buffer. This takes the +;; single-allocation hinted path. +(count (read (format "%/big.txt" d))) -- 300000 +(count (read-bytes (format "%/big.txt" d))) -- 300000 + +;; ────────────── unsized streams: the growth loop ────────────── +;; A FIFO has no size, so it starts at 4096 and doubles. 120000 bytes +;; forces five doublings, exercising the grow/memcpy/release path that the +;; sized cases above never touch. +(.sys.exec (format "rm -f %/fifo_big && mkfifo %/fifo_big" d d)) +(.sys.exec (format "(dd if=/dev/zero bs=1000 count=120 2>/dev/null > %/fifo_big &) ; sleep 0" d)) +(count (read-bytes (format "%/fifo_big" d))) -- 120000 + +;; And the small case, asserting content rather than just length. +(.sys.exec (format "rm -f %/fifo && mkfifo %/fifo" d d)) +(.sys.exec (format "(printf 'from-a-fifo\\n' > %/fifo &) ; sleep 0" d)) +(read (format "%/fifo" d)) -- "from-a-fifo\n" ;; ────────────── errors stay loud ────────────── -(try (read "/tmp/rf_read_eof/does-not-exist") (fn [e] 'io-rejected)) -- 'io-rejected -(try (read-bytes "/tmp/rf_read_eof/does-not-exist") (fn [e] 'io-rejected)) -- 'io-rejected +(try (read (format "%/does-not-exist" d)) (fn [e] 'io-rejected)) -- 'io-rejected +(try (read-bytes (format "%/does-not-exist" d)) (fn [e] 'io-rejected)) -- 'io-rejected ;; A directory is not readable as a file. -(try (read "/tmp/rf_read_eof") (fn [e] 'io-rejected)) -- 'io-rejected +(try (read d) (fn [e] 'io-rejected)) -- 'io-rejected ;; ────────────── cleanup ────────────── -(.sys.exec "rm -rf /tmp/rf_read_eof") +(.sys.exec (format "rm -rf %" d)) diff --git a/test/test_lang.c b/test/test_lang.c index cd0367a22..8927d8740 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -9035,6 +9035,48 @@ static test_result_t test_read_procfs_reports_zero_size(void) { #endif } +/* An unsized stream has no natural end, so the read-to-EOF loop is bounded + * by a quarter of the heap's remaining anon headroom (#572 follow-up). The + * watermark is a spill threshold rather than a ceiling — crossing it picks + * disk over RAM instead of failing — so an unbounded loop would fill the + * spill file rather than merely exhausting RAM. + * + * Drives the bound by moving the watermark to just above what is already + * committed, which makes the budget small and the error immediate. */ +static test_result_t test_read_unsized_stream_is_bounded(void) { +#if defined(RAY_OS_WINDOWS) + SKIP("no /dev/zero"); +#else + FILE* probe = fopen("/dev/zero", "rb"); + if (!probe) SKIP("/dev/zero unavailable"); + fclose(probe); + + int64_t saved = ray_heap_anon_watermark(); + /* budget = (watermark - committed) / 4, so this leaves ~1 MB. */ + ray_heap_set_anon_watermark(ray_heap_anon_committed() + 4 * 1024 * 1024); + + ray_t* arg = ray_str("/dev/zero", 9); + ray_t* got = ray_read_file_fn(arg); + ray_release(arg); + + ray_heap_set_anon_watermark(saved); + + TEST_ASSERT_NOT_NULL(got); + TEST_ASSERT(RAY_IS_ERR(got), "an endless stream must error, not grow without end"); + TEST_ASSERT_STR_EQ(ray_err_code(got), "io"); + ray_error_free(got); + + /* The bound must not have disturbed ordinary reads once restored. */ + ray_t* p2 = ray_str("/dev/null", 9); + ray_t* empty = ray_read_file_fn(p2); + ray_release(p2); + TEST_ASSERT(!RAY_IS_ERR(empty), "/dev/null must still read as empty"); + TEST_ASSERT_EQ_I(ray_str_len(empty), 0); + ray_release(empty); + PASS(); +#endif +} + const test_entry_t lang_entries[] = { { "lang/env/scope_frame_grows", test_env_scope_frame_grows, lang_setup, lang_teardown }, { "lang/query/wide_table_over_64_cols", test_query_wide_table_over_64_cols, lang_setup, lang_teardown }, @@ -9452,6 +9494,7 @@ const test_entry_t lang_entries[] = { { "lang/temporal/date_trunc_month_case", test_temporal_date_trunc_month_case, lang_setup, lang_teardown }, { "lang/io/read_procfs_zero_size", test_read_procfs_reports_zero_size, lang_setup, lang_teardown }, + { "lang/io/read_unsized_bounded", test_read_unsized_stream_is_bounded, lang_setup, lang_teardown }, { NULL, NULL, NULL, NULL }, }; From d9223169db312915047aaf8b329580d2d2f5ea32 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 17:55:45 +0200 Subject: [PATCH 17/20] fix(io): confine the read budget to unsized streams; close fp on rejection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/docs/language/functions.md | 7 +++++++ src/ops/builtins.c | 27 ++++++++++++++++++--------- test/test_lang.c | 30 +++++++++++++++++++++++++++++- 3 files changed, 54 insertions(+), 10 deletions(-) diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index 04934d8c0..4deef908f 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -459,6 +459,13 @@ change between the measure and the read. `.fs.size` still reports what the OS reports — the two disagreeing on a special file is expected, not a bug. +A stream with no size to go on — `/dev/zero`, or a FIFO nobody closes — has no +EOF to reach. Reading one grows a buffer until it crosses a ceiling derived +from the heap's remaining headroom, then fails with `io` rather than consuming +the machine. Reads of a file whose size *is* known are not subject to that +ceiling: a reported size is a finite claim, and a large file allocates and +spills exactly as it did before. + ## Control Flow | Function | Type | Description | Example | diff --git a/src/ops/builtins.c b/src/ops/builtins.c index 6daf505dc..a5b9a0ecb 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -2037,7 +2037,8 @@ ray_t* ray_type_fn(ray_t* val) { return ray_sym(id); } -/* Ceiling for one `read` / `read-bytes` result. +/* Ceiling for the growth of an *unsized* read — a stream with no size to + * go on. The hinted path is deliberately not subject to it. * * The heap's anon watermark is NOT a ceiling: crossing it routes the * mapping to a spill file rather than failing ("this never rejects work, @@ -2101,7 +2102,7 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { * reports LONG_MAX. (Directories are already rejected by the * S_ISDIR check above; this guard is for anything else that * reports a size it cannot back.) */ - if (hint < 0 || hint > (long)(INT64_MAX / 2) || fseek(fp, 0, SEEK_SET) != 0) + if (hint < 0 || (int64_t)hint > INT64_MAX / 2 || fseek(fp, 0, SEEK_SET) != 0) hint = 0; } /* Unseekable (pipe, character device) or size-0-but-readable: start at @@ -2110,12 +2111,12 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { * the hint", so a file that grew is read whole instead of truncated. */ int64_t cap = hint > 0 ? (int64_t)hint + 1 : 4096; - /* Same ceiling on both paths: a file claiming more than the budget is - * refused here rather than left to fail inside the allocator. */ + /* No ceiling on the hinted path. A reported size is a finite claim the + * filesystem backs, and a large file allocating through the heap and + * spilling to disk is the behaviour that was already correct — the + * budget below exists to terminate an *endless* stream, which is not a + * situation a hint can describe. */ const int64_t budget = read_size_budget(); - if (budget > 0 && cap > budget) - return ray_error("io", "%s \"%s\": %lld bytes exceeds the readable budget of %lld bytes", - op, path, (long long)cap, (long long)budget); ray_t* result = ray_vec_new(RAY_U8, cap); if (!result || RAY_IS_ERR(result)) { @@ -2131,9 +2132,17 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { * instantly; growing without a bound instead walks the process * into OOM or into the spill file. Check before doubling, so * the multiply itself cannot overflow. */ - if (cap > INT64_MAX / 2 || (budget > 0 && cap * 2 > budget)) { + /* Peak during the grow is the old buffer plus the new one — 3*cap, + * since the old stays alive across the memcpy — so bound the + * peak rather than the result. Checked before the multiply, so + * the multiply itself cannot overflow. */ + if (cap > INT64_MAX / 3) { + ray_release(result); fclose(fp); + return ray_error("io", "%s \"%s\": input too large to read", op, path); + } + if (budget > 0 && cap * 3 > budget) { ray_release(result); fclose(fp); - return ray_error("io", "%s \"%s\": input exceeds the readable budget of %lld bytes", + return ray_error("io", "%s \"%s\": unsized input exceeds the readable budget of %lld bytes", op, path, (long long)budget); } int64_t ncap = cap * 2; diff --git a/test/test_lang.c b/test/test_lang.c index 8927d8740..9b6d7d0ba 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -9051,7 +9051,12 @@ static test_result_t test_read_unsized_stream_is_bounded(void) { if (!probe) SKIP("/dev/zero unavailable"); fclose(probe); + /* ray_heap_anon_watermark() resolves the 0 sentinel to physical RAM, so + * restoring what it returns would pin the watermark to a number where + * the suite found "use physical RAM". Detect that case and put the + * sentinel back instead, which keeps this test order-independent. */ int64_t saved = ray_heap_anon_watermark(); + bool was_default = (saved == ray_sys_total_ram()); /* budget = (watermark - committed) / 4, so this leaves ~1 MB. */ ray_heap_set_anon_watermark(ray_heap_anon_committed() + 4 * 1024 * 1024); @@ -9059,13 +9064,36 @@ static test_result_t test_read_unsized_stream_is_bounded(void) { ray_t* got = ray_read_file_fn(arg); ray_release(arg); - ray_heap_set_anon_watermark(saved); + ray_heap_set_anon_watermark(was_default ? 0 : saved); TEST_ASSERT_NOT_NULL(got); TEST_ASSERT(RAY_IS_ERR(got), "an endless stream must error, not grow without end"); TEST_ASSERT_STR_EQ(ray_err_code(got), "io"); ray_error_free(got); + /* A *sized* file larger than the same budget must still read: the + * ceiling exists to terminate an endless stream, and a reported size is + * a finite claim the filesystem backs. Bounding this path would turn a + * large-file read that previously allocated and spilled into a hard + * error, and would make success depend on live process state. */ + const char* big = "/tmp/rf_read_big_sized.bin"; + FILE* bf = fopen(big, "wb"); + TEST_ASSERT_NOT_NULL(bf); + static char chunk[65536]; + for (int i = 0; i < 32; i++) /* 2 MB, well over the ~1 MB budget */ + TEST_ASSERT(fwrite(chunk, 1, sizeof(chunk), bf) == sizeof(chunk), "write big file"); + fclose(bf); + + ray_heap_set_anon_watermark(ray_heap_anon_committed() + 4 * 1024 * 1024); + ray_t* bp = ray_str(big, strlen(big)); + ray_t* bread = ray_read_file_fn(bp); + ray_release(bp); + ray_heap_set_anon_watermark(was_default ? 0 : saved); + remove(big); + TEST_ASSERT(!RAY_IS_ERR(bread), "a sized file must not be refused by the unsized budget"); + TEST_ASSERT_EQ_I(ray_str_len(bread), 2 * 1024 * 1024); + ray_release(bread); + /* The bound must not have disturbed ordinary reads once restored. */ ray_t* p2 = ray_str("/dev/null", 9); ray_t* empty = ray_read_file_fn(p2); From 910e1a51e6c1968777ae75c6a1cea5b2d56f0e89 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 19:32:33 +0200 Subject: [PATCH 18/20] docs(sys): warn that .sys.exec 'out waits for backgrounded children; 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. --- docs/docs/namespaces/sys.md | 21 +++++++++++++++++++++ src/lang/internal.h | 7 +++++++ src/ops/builtins.c | 4 ++-- src/ops/system.c | 15 +++++++++++++++ test/test_lang.c | 29 +++++++++++++++++++++++++++++ 5 files changed, 74 insertions(+), 2 deletions(-) diff --git a/docs/docs/namespaces/sys.md b/docs/docs/namespaces/sys.md index 6ef3fff7d..5e13d189b 100644 --- a/docs/docs/namespaces/sys.md +++ b/docs/docs/namespaces/sys.md @@ -278,6 +278,27 @@ or did not complete), `oom`. (.sys.exec "echo partial; exit 4" 'out) ;; => {code: 4, out: "partial\n"} ``` +!!! warning "`'out` waits for every process holding the pipe" + The capture reads until end-of-file on the command's stdout, and a + backgrounded child inherits that pipe. So `'out` waits for the background + process too, not just for the shell: + + ```lisp + (.sys.exec "(sleep 3 &) ; true" 'out) ;; returns after 3s + (.sys.exec "./server &" 'out) ;; waits for the server + ``` + + Detach the child's stdout and the call returns at once: + + ```lisp + (.sys.exec "(sleep 3 &) >/dev/null 2>&1" 'out) ;; returns immediately + ``` + + This is inherent to capturing output — `popen(3)` behaves the same way, as + do the equivalents in other languages. The one-argument form does **not** + have it, since it only waits for the shell itself, so prefer plain + `(.sys.exec "./server &")` to launch something that outlives the call. + !!! warning "Behaviour change" Before this, the one-argument form returned the raw `waitpid`-encoded status, so `(.sys.exec "false")` was `256` and `(.sys.exec "exit 3")` was diff --git a/src/lang/internal.h b/src/lang/internal.h index 09a3b5d1e..103bdd8d5 100644 --- a/src/lang/internal.h +++ b/src/lang/internal.h @@ -606,6 +606,13 @@ ray_t* ray_meta_fn(ray_t* x); ray_t* ray_mem_objsize_fn(ray_t* x); ray_t* ray_mem_ts_fn(ray_t** args, int64_t n); ray_t* ray_gc_fn(ray_t** args, int64_t n); +/* Ceiling for growing a read that has no size to go on — an endless stream + * has no EOF to reach, and growing to meet it takes the process down. A + * quarter of the heap's remaining anon headroom; 0 means "no bound known", + * which callers treat as permissive. Shared by `read`/`read-bytes` and by + * .sys.exec's output capture, which face the same problem. */ +int64_t ray_unsized_read_budget(void); + ray_t* ray_system_fn(ray_t** args, int64_t n); /* `.sys.cmd "name args"` — registry-dispatched system commands with * shell fallback (see lang/syscmd.h). */ diff --git a/src/ops/builtins.c b/src/ops/builtins.c index a5b9a0ecb..18dd8d35b 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -2052,7 +2052,7 @@ ray_t* ray_type_fn(ray_t* val) { * knob is introduced. * * Returns 0 for "no bound known", which callers treat as permissive. */ -static int64_t read_size_budget(void) { +int64_t ray_unsized_read_budget(void) { int64_t wm = ray_heap_anon_watermark(); if (wm <= 0) return 0; /* RAM unknown → permissive */ int64_t avail = wm - ray_heap_anon_committed(); @@ -2116,7 +2116,7 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { * spilling to disk is the behaviour that was already correct — the * budget below exists to terminate an *endless* stream, which is not a * situation a hint can describe. */ - const int64_t budget = read_size_budget(); + const int64_t budget = ray_unsized_read_budget(); ray_t* result = ray_vec_new(RAY_U8, cap); if (!result || RAY_IS_ERR(result)) { diff --git a/src/ops/system.c b/src/ops/system.c index 873bb9847..dec663f7a 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -887,12 +887,22 @@ static ray_t* exec_capture(const char* cmd, int64_t* code_out) { FILE* fp = RAY_POPEN(cmd, "r"); if (!fp) return ray_error("io", ".sys.exec: failed to start command: %s", strerror(errno)); + /* A command that never stops writing has no end to capture, exactly as an + * endless file has no EOF to read (#572). Same ceiling, same reason. */ + const int64_t budget = ray_unsized_read_budget(); + size_t cap = 4096, len = 0; char* buf = (char*)ray_alloc_raw(cap); if (!buf) { RAY_PCLOSE(fp); return ray_error("oom", ".sys.exec: capture buffer"); } for (;;) { if (len == cap) { + /* Peak during the grow is the old buffer plus the new one. */ + if (budget > 0 && (int64_t)cap * 3 > budget) { + ray_free_raw(buf); RAY_PCLOSE(fp); + return ray_error("io", ".sys.exec: output exceeds the readable budget of %lld bytes", + (long long)budget); + } char* nbuf = (char*)ray_realloc_raw(buf, cap * 2); if (!nbuf) { ray_free_raw(buf); RAY_PCLOSE(fp); return ray_error("oom", ".sys.exec: capture buffer"); } buf = nbuf; cap *= 2; @@ -919,6 +929,11 @@ static ray_t* exec_capture(const char* cmd, int64_t* code_out) { /* (.sys.exec cmd) -> exit code * (.sys.exec cmd 'out) -> {code: out: } * + * The capture reads to EOF on the child's stdout, and a backgrounded + * grandchild inherits that pipe — so 'out waits for it too, not just for the + * shell (#579). Inherent to popen(3); the one-argument form does not have + * it, and is the way to launch something that outlives the call. + * * stderr is deliberately left on the process's own stderr: a shelled-out * command's diagnostics belong in the log, and merging them into the * captured value would corrupt anything parsing that value (#573). */ diff --git a/test/test_lang.c b/test/test_lang.c index 9b6d7d0ba..901628850 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -9105,6 +9105,34 @@ static test_result_t test_read_unsized_stream_is_bounded(void) { #endif } +/* .sys.exec's capture faces the same endless-stream problem as `read`: a + * command that never stops writing has no EOF to reach. Same ceiling, so + * assert it is actually wired up rather than only present in `read` (#579). */ +static test_result_t test_exec_capture_is_bounded(void) { +#if defined(RAY_OS_WINDOWS) || defined(RAY_FUZZING) + SKIP("shell capture unavailable"); +#else + int64_t saved = ray_heap_anon_watermark(); + bool was_default = (saved == ray_sys_total_ram()); + ray_heap_set_anon_watermark(ray_heap_anon_committed() + 4 * 1024 * 1024); + + ray_t* args[2]; + args[0] = ray_str("cat /dev/zero", 13); + args[1] = ray_sym(ray_sym_intern("out", 3)); + ray_t* got = ray_system_fn(args, 2); + ray_release(args[0]); + ray_release(args[1]); + + ray_heap_set_anon_watermark(was_default ? 0 : saved); + + TEST_ASSERT_NOT_NULL(got); + TEST_ASSERT(RAY_IS_ERR(got), "an endless command must not be captured without end"); + TEST_ASSERT_STR_EQ(ray_err_code(got), "io"); + ray_error_free(got); + PASS(); +#endif +} + const test_entry_t lang_entries[] = { { "lang/env/scope_frame_grows", test_env_scope_frame_grows, lang_setup, lang_teardown }, { "lang/query/wide_table_over_64_cols", test_query_wide_table_over_64_cols, lang_setup, lang_teardown }, @@ -9523,6 +9551,7 @@ const test_entry_t lang_entries[] = { { "lang/io/read_procfs_zero_size", test_read_procfs_reports_zero_size, lang_setup, lang_teardown }, { "lang/io/read_unsized_bounded", test_read_unsized_stream_is_bounded, lang_setup, lang_teardown }, + { "lang/io/exec_capture_bounded", test_exec_capture_is_bounded, lang_setup, lang_teardown }, { NULL, NULL, NULL, NULL }, }; From 377581735e3a7a435474c7c73f70e13d9219aebc Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 20:25:09 +0200 Subject: [PATCH 19/20] fix(ipc): bind a VM for lifecycle hooks on VM-less threads 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. --- src/core/ipc.c | 54 +++++++++++++++++++++++++++++++++++++++++- test/test_ipc.c | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 1 deletion(-) diff --git a/src/core/ipc.c b/src/core/ipc.c index ac6cd3215..396dab935 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -314,6 +314,51 @@ static ray_t* hook_lookup(int idx) { return fn; } +/* ── Temporary VM for a hook on a VM-less thread (#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. #565 + * made the *no hook installed* case safe by letting ray_env_get fall + * through to globals, which left this question 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 bind a VM for the duration rather than skipping the hook + * (silent, and invisible at the call site) or failing the close (which + * 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 would otherwise see a handle of -1. + * + * ray_vm_t is ~68 KB, too large for a teardown-path stack, so it comes + * from the buddy heap (process-wide and already live — the heap belongs to + * the runtime, not the thread). Teardown mirrors ray_runtime_destroy: + * release raise_val and trace, then free. Grown scope frames are not + * walked, matching that same teardown — a hook that returns normally has + * already popped its scopes. */ +typedef struct { ray_vm_t* owned; } hook_vm_t; + +static bool hook_vm_bind(hook_vm_t* hv) { + hv->owned = NULL; + if (__VM) return true; /* already on a VM thread */ + ray_vm_t* vm = (ray_vm_t*)ray_alloc_raw(sizeof(ray_vm_t)); + if (!vm) return false; /* caller skips the hook */ + ray_vm_init(vm, -1); /* id -1: not a pool VM */ + __VM = vm; + hv->owned = vm; + return true; +} + +static void hook_vm_unbind(hook_vm_t* hv) { + if (!hv->owned) return; + if (hv->owned->raise_val) ray_release(hv->owned->raise_val); + if (hv->owned->trace) ray_release(hv->owned->trace); + __VM = NULL; + ray_free_raw(hv->owned); + hv->owned = NULL; +} + /* Call a single-arg hook for lifecycle events (on.open / on.close). * Errors are logged and swallowed — a buggy logging hook must never * wedge connection teardown. `poll` is the poll the connection lives @@ -322,8 +367,14 @@ static ray_t* hook_lookup(int idx) { static void hook_call_lifecycle(ray_poll_t* poll, int idx, int64_t handle) { ray_t* fn = hook_lookup(idx); if (!fn) return; + hook_vm_t hv; + if (!hook_vm_bind(&hv)) return; ray_t* arg = make_i64(handle); - if (!arg || RAY_IS_ERR(arg)) { if (arg) ray_release(arg); return; } + if (!arg || RAY_IS_ERR(arg)) { + if (arg) ray_release(arg); + hook_vm_unbind(&hv); + return; + } int64_t prev = ipc_ctx_handle(); ray_poll_t* prev_poll = ipc_ctx_poll(); ipc_ctx_set(handle, poll ? poll : prev_poll); @@ -336,6 +387,7 @@ static void hook_call_lifecycle(ray_poll_t* poll, int idx, int64_t handle) { } ray_release(arg); if (r && r != RAY_NULL_OBJ) ray_release(r); + hook_vm_unbind(&hv); } /* Call the on.auth hook with (user, pass) string atoms. Returns: diff --git a/test/test_ipc.c b/test/test_ipc.c index 7ddcd0798..18a9eced5 100644 --- a/test/test_ipc.c +++ b/test/test_ipc.c @@ -672,6 +672,68 @@ static test_result_t test_ipc_send_async_invalid_handle(void) { * Covers ipc_accept, ipc_read_handshake (success path), * ipc_read_header, ipc_read_payload, ipc_on_close, ipc_send_fn. */ +/* A lifecycle hook must run on a thread that never bound a VM (#569). + * + * #565 made the *no hook installed* case safe by letting ray_env_get fall + * through to globals on such a thread. With a hook actually bound, + * call_fn1 would then run user code with __VM == NULL — this asserts the + * hook runs and observes a live `.ipc.handle`. + * + * The worker deliberately never calls ray_runtime_create: that is the + * shape of an embedder's own thread driving teardown, which is how this + * was found. */ +static ray_poll_t* g_vmless_poll = NULL; +static int64_t g_vmless_sel = -1; + +static void vmless_close_worker(void* unused) { + (void)unused; + /* No ray_runtime_create here — __VM is NULL on this thread. */ + ray_poll_deregister(g_vmless_poll, g_vmless_sel); +} + +static test_result_t test_ipc_close_hook_on_vmless_thread(void) { + ray_test_server_t srv; + RAY_TEST_SERVER_START(srv); + + /* The hook records what `.ipc.handle` reports, which is stored through + * __VM — so a bound VM is exactly what makes it observable. */ + ray_t* r = ray_eval_str( + "(do (set _vmless_fired 0) (set _vmless_h -99)" + " (set .ipc.on.close (fn [h] (do (set _vmless_fired (+ _vmless_fired 1))" + " (set _vmless_h (.ipc.handle))))) null)"); + TEST_ASSERT(r && !RAY_IS_ERR(r), "install hook"); + ray_release(r); + + /* Client side: connect registers the connection in this thread's poll. */ + int64_t h = ray_ipc_connect("127.0.0.1", srv.port, NULL, NULL, 2000); + TEST_ASSERT((h) >= (0), "connect"); + + g_vmless_poll = ray_ipc_active_poll(); + TEST_ASSERT_NOT_NULL(g_vmless_poll); + g_vmless_sel = h; + + ray_thread_t tid; + ray_thread_create(&tid, vmless_close_worker, NULL); + ray_thread_join(tid); + + /* Before the fix this ran user code with a NULL VM. */ + ray_t* fired = ray_eval_str("_vmless_fired"); + TEST_ASSERT(fired && !RAY_IS_ERR(fired), "read counter"); + TEST_ASSERT((fired->i64) >= (1), "close hook did not run on a VM-less thread"); + ray_release(fired); + + /* And it saw a real handle, not the -1 a missing VM yields. */ + ray_t* seen = ray_eval_str("_vmless_h"); + TEST_ASSERT(seen && !RAY_IS_ERR(seen), "read handle"); + TEST_ASSERT((seen->i64) >= (0), "hook saw no .ipc.handle"); + ray_release(seen); + + ray_t* cleanup = ray_eval_str("(do (set .ipc.on.close null) null)"); + if (cleanup) ray_release(cleanup); + ray_test_server_stop(&srv); + PASS(); +} + static test_result_t test_ipc_poll_based_listen(void) { ray_poll_t* poll = ray_poll_create(); TEST_ASSERT_NOT_NULL(poll); @@ -2643,6 +2705,7 @@ const test_entry_t ipc_entries[] = { { "ipc/close_invalid_handle", test_ipc_close_invalid_handle, ipc_setup, ipc_teardown }, { "ipc/send_invalid_handle", test_ipc_send_invalid_handle, ipc_setup, ipc_teardown }, { "ipc/send_async_invalid_handle", test_ipc_send_async_invalid_handle, ipc_setup, ipc_teardown }, + { "ipc/close_hook_vmless_thread", test_ipc_close_hook_on_vmless_thread, ipc_setup, ipc_teardown }, { "ipc/poll_based_listen", test_ipc_poll_based_listen, ipc_setup, ipc_teardown }, { "ipc/poll_public_restricted", test_ipc_poll_public_restricted, ipc_setup, ipc_teardown }, { "ipc/poll_auth_creds_path", test_ipc_poll_auth_creds_path, ipc_setup, ipc_teardown }, From c96beb217778a4425660fc9f991542b68bca77f0 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 18 Sep 2026 20:54:40 +0200 Subject: [PATCH 20/20] test(ipc): make the VM-less hook test actually gate the bug 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. --- src/core/ipc.c | 13 ++++++++++++- test/test_ipc.c | 36 +++++++++++++++++++++++------------- 2 files changed, 35 insertions(+), 14 deletions(-) diff --git a/src/core/ipc.c b/src/core/ipc.c index 396dab935..5143b5ce6 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -343,7 +343,12 @@ static bool hook_vm_bind(hook_vm_t* hv) { hv->owned = NULL; if (__VM) return true; /* already on a VM thread */ ray_vm_t* vm = (ray_vm_t*)ray_alloc_raw(sizeof(ray_vm_t)); - if (!vm) return false; /* caller skips the hook */ + if (!vm) { + /* Skipping a hook the operator installed is worth a line, matching + * how this file reports every other hook failure. */ + fprintf(stderr, "ipc: cannot bind a VM for hook dispatch (out of memory); hook skipped\n"); + return false; + } ray_vm_init(vm, -1); /* id -1: not a pool VM */ __VM = vm; hv->owned = vm; @@ -396,6 +401,10 @@ static void hook_call_lifecycle(ray_poll_t* poll, int idx, int64_t handle) { * - -1 → no hook installed; caller uses the existing pass-through. * The constant-time secret compare in validate_creds always runs first, * so this hook can only narrow access — never widen it. */ +/* Not VM-bound, unlike hook_call_lifecycle: this runs only from inside + * ray_poll_run, on a thread that necessarily has a VM. If a future path + * ever drives the handshake from an embedder's own thread, it needs the + * same hook_vm_bind treatment (#569). */ static int hook_call_auth(ray_poll_t* poll, int64_t handle, const uint8_t* cred_buf, uint8_t cred_len) { ray_t* fn = hook_lookup(IPC_HOOK_AUTH); @@ -648,6 +657,8 @@ static ray_t* eval_payload_core(uint8_t* payload, size_t payload_len, * as `{[m] eval m}` reproduces the default behaviour. */ int hook_idx = (hdr->msgtype == RAY_IPC_MSG_SYNC) ? IPC_HOOK_SYNC : IPC_HOOK_ASYNC; + /* Also not VM-bound — eval_payload runs under ray_poll_run, which + * owns a VM. See hook_call_lifecycle for the case that does not. */ ray_t* hook = hook_lookup(hook_idx); if (hook) { result = call_fn1(hook, msg); diff --git a/test/test_ipc.c b/test/test_ipc.c index 18a9eced5..21b3dfa1c 100644 --- a/test/test_ipc.c +++ b/test/test_ipc.c @@ -695,19 +695,28 @@ static test_result_t test_ipc_close_hook_on_vmless_thread(void) { ray_test_server_t srv; RAY_TEST_SERVER_START(srv); - /* The hook records what `.ipc.handle` reports, which is stored through - * __VM — so a bound VM is exactly what makes it observable. */ + int64_t h = ray_ipc_connect("127.0.0.1", srv.port, NULL, NULL, 2000); + TEST_ASSERT((h) >= (0), "connect"); + + /* Stop the server *before* installing the hook. + * + * .ipc.on.close is one process-global binding and ipc_on_close fires it + * for both ends of a connection, so a server thread — which has a VM — + * would otherwise satisfy any counter this test could assert on, and the + * test would stay green with the fix reverted. Shutting the server down + * first, with no hook installed, means the single firing below is + * unambiguously the client-side teardown driven from the VM-less thread. + * It also removes the poll loop that would otherwise be writing these + * globals while the main thread reads them. */ + ray_test_server_stop(&srv); + ray_t* r = ray_eval_str( "(do (set _vmless_fired 0) (set _vmless_h -99)" - " (set .ipc.on.close (fn [h] (do (set _vmless_fired (+ _vmless_fired 1))" + " (set .ipc.on.close (fn [x] (do (set _vmless_fired (+ _vmless_fired 1))" " (set _vmless_h (.ipc.handle))))) null)"); TEST_ASSERT(r && !RAY_IS_ERR(r), "install hook"); ray_release(r); - /* Client side: connect registers the connection in this thread's poll. */ - int64_t h = ray_ipc_connect("127.0.0.1", srv.port, NULL, NULL, 2000); - TEST_ASSERT((h) >= (0), "connect"); - g_vmless_poll = ray_ipc_active_poll(); TEST_ASSERT_NOT_NULL(g_vmless_poll); g_vmless_sel = h; @@ -716,21 +725,22 @@ static test_result_t test_ipc_close_hook_on_vmless_thread(void) { ray_thread_create(&tid, vmless_close_worker, NULL); ray_thread_join(tid); - /* Before the fix this ran user code with a NULL VM. */ + /* Exactly one firing, and it came from the VM-less thread. */ ray_t* fired = ray_eval_str("_vmless_fired"); TEST_ASSERT(fired && !RAY_IS_ERR(fired), "read counter"); - TEST_ASSERT((fired->i64) >= (1), "close hook did not run on a VM-less thread"); + TEST_ASSERT_EQ_I(fired->i64, 1); ray_release(fired); - /* And it saw a real handle, not the -1 a missing VM yields. */ + /* It saw this connection's handle. Without a bound VM ipc_ctx_set + * stores nothing and .ipc.handle reports -1, so this is the assertion + * that actually separates fixed from unfixed. */ ray_t* seen = ray_eval_str("_vmless_h"); TEST_ASSERT(seen && !RAY_IS_ERR(seen), "read handle"); - TEST_ASSERT((seen->i64) >= (0), "hook saw no .ipc.handle"); + TEST_ASSERT_EQ_I(seen->i64, h); ray_release(seen); ray_t* cleanup = ray_eval_str("(do (set .ipc.on.close null) null)"); if (cleanup) ray_release(cleanup); - ray_test_server_stop(&srv); PASS(); } @@ -2705,7 +2715,7 @@ const test_entry_t ipc_entries[] = { { "ipc/close_invalid_handle", test_ipc_close_invalid_handle, ipc_setup, ipc_teardown }, { "ipc/send_invalid_handle", test_ipc_send_invalid_handle, ipc_setup, ipc_teardown }, { "ipc/send_async_invalid_handle", test_ipc_send_async_invalid_handle, ipc_setup, ipc_teardown }, - { "ipc/close_hook_vmless_thread", test_ipc_close_hook_on_vmless_thread, ipc_setup, ipc_teardown }, + { "ipc/close_hook_vmless_thread", test_ipc_close_hook_on_vmless_thread, ipc_setup, ipc_teardown }, { "ipc/poll_based_listen", test_ipc_poll_based_listen, ipc_setup, ipc_teardown }, { "ipc/poll_public_restricted", test_ipc_poll_public_restricted, ipc_setup, ipc_teardown }, { "ipc/poll_auth_creds_path", test_ipc_poll_auth_creds_path, ipc_setup, ipc_teardown },