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/docs/language/functions.md b/docs/docs/language/functions.md index c6c6eb4d0..58f578b7e 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 @@ -438,12 +455,34 @@ 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. + +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/docs/docs/namespaces/sys.md b/docs/docs/namespaces/sys.md index 3e687f307..5e13d189b 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,58 @@ 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 "`'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 + `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..85975352c 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 @@ -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")` | @@ -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/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/include/rayforce.h b/include/rayforce.h index 2ab292714..7b23814f7 100644 --- a/include/rayforce.h +++ b/include/rayforce.h @@ -677,7 +677,28 @@ 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 ===== + * + * 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_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); ray_t* ray_table_add_col(ray_t* tbl, int64_t name_id, ray_t* col_vec); 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 diff --git a/src/core/ipc.c b/src/core/ipc.c index ac6cd3215..5143b5ce6 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -314,6 +314,56 @@ 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) { + /* 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; + 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 +372,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 +392,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: @@ -344,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); @@ -596,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/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++) { 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..103bdd8d5 100644 --- a/src/lang/internal.h +++ b/src/lang/internal.h @@ -606,7 +606,14 @@ 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); +/* 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). */ ray_t* ray_syscmd_string_dispatch_fn(ray_t* x); diff --git a/src/ops/builtins.c b/src/ops/builtins.c index f4e85a57e..18dd8d35b 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -59,6 +59,7 @@ 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 @@ -2036,6 +2037,29 @@ ray_t* ray_type_fn(ray_t* val) { return ray_sym(id); } +/* 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, + * 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. */ +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(); + 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)); @@ -2043,26 +2067,104 @@ 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. 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); - 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); + /* 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 || (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 + * 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; + + /* 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 = ray_unsized_read_budget(); + + 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) { + /* 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 or into the spill file. Check before doubling, so + * the multiply itself cannot overflow. */ + /* 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\": unsized 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); + 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/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..d26ee6b24 100644 --- a/src/ops/fused_pred.h +++ b/src/ops/fused_pred.h @@ -27,6 +27,7 @@ #include "rayforce.h" #include "ops/internal.h" #include "ops/glob.h" +#include "table/domain.h" #define FP_PRED_MAX_CHILDREN 8 @@ -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..b79276e2c 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; } @@ -12117,44 +12130,54 @@ 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++) { + void* raw = scratch_calloc(&sc_acc[w]._h_sum, sc_bytes + sc_line); + if (!raw) { alloc_ok = false; break; } + /* 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*)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*)(void*)(blk + off); off += n_aggs; } 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*)(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*)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*)(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*)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*)(void*)(blk + off); off += n_aggs; } - 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 = blk + off; off += n_aggs; } } if (!alloc_ok) { 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..7711a36bc 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,55 @@ 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. 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 }; + 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 +1072,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/ops/system.c b/src/ops/system.c index 5a594ed89..dec663f7a 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 /* ══════════════════════════════════════════ @@ -372,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; @@ -798,18 +860,161 @@ 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) { +/* 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 + * 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)); + + /* 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; + } + 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; +} + +#endif /* !RAY_FUZZING */ + +/* (.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). */ +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) { + 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); + if (RAY_IS_ERR(out)) { + result = out; + } else { + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 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); + 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 +1461,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 +1517,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/src/table/domain.c b/src/table/domain.c index 22f085d24..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,6 +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; + /* 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 — @@ -241,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. */ @@ -259,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); @@ -413,9 +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). */ - 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; @@ -429,7 +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); + 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 @@ -496,6 +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_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. */ @@ -517,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 @@ -611,6 +660,18 @@ 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; + 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) { + (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 * indexed: every position is out of range when count == 0. */ diff --git a/src/table/domain.h b/src/table/domain.h index 474c610d8..e5c0f9e6b 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,33 @@ 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 + * 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; + 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/src/table/table.c b/src/table/table.c index 10a6c09fb..10d39b6ef 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]; } @@ -118,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", @@ -189,7 +212,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 +229,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 +244,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 +263,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 +276,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 +292,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 +336,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/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/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 diff --git a/test/rfl/io/read_until_eof.rfl b/test/rfl/io/read_until_eof.rfl new file mode 100644 index 000000000..a4ea55ab6 --- /dev/null +++ b/test/rfl/io/read_until_eof.rfl @@ -0,0 +1,63 @@ +;; `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. +;; +;; 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 ────────────── +(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 (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 (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 (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 d) (fn [e] 'io-rejected)) -- 'io-rejected + +;; ────────────── cleanup ────────────── +(.sys.exec (format "rm -rf %" d)) 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") 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..e13d26bad --- /dev/null +++ b/test/rfl/symbol/file_domain_like_strlen.rfl @@ -0,0 +1,89 @@ +;; 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 +;; 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 diff --git a/test/rfl/system/process_identity.rfl b/test/rfl/system/process_identity.rfl new file mode 100644 index 000000000..d0baa387d --- /dev/null +++ b/test/rfl/system/process_identity.rfl @@ -0,0 +1,73 @@ +;; 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 +;; 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 + +;; 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 (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. +(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 + +;; 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 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) diff --git a/test/test_domain.c b/test/test_domain.c index 2f633c438..ce7186ac6 100644 --- a/test/test_domain.c +++ b/test/test_domain.c @@ -1683,6 +1683,81 @@ 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); + /* 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(); +} /* 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 +1985,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 }, diff --git a/test/test_ipc.c b/test/test_ipc.c index 7ddcd0798..21b3dfa1c 100644 --- a/test/test_ipc.c +++ b/test/test_ipc.c @@ -672,6 +672,78 @@ 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); + + 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 [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); + + 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); + + /* 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_EQ_I(fired->i64, 1); + ray_release(fired); + + /* 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_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); + 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 +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/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 }, diff --git a/test/test_lang.c b/test/test_lang.c index 3ca768565..901628850 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -8971,6 +8971,168 @@ 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 +} + +/* 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); + + /* 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); + + ray_t* arg = ray_str("/dev/zero", 9); + ray_t* got = ray_read_file_fn(arg); + ray_release(arg); + + 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); + 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 +} + +/* .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 }, @@ -9387,5 +9549,9 @@ 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 }, + { "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 }, }; diff --git a/test/test_table.c b/test/test_table.c index 97530cbe5..55d8415e0 100644 --- a/test/test_table.c +++ b/test/test_table.c @@ -564,6 +564,108 @@ 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(); +} + +/* 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. */ +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)); + 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(); +} + /* 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 +717,9 @@ 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/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 }, { NULL, NULL, NULL, NULL },