From 666b944a90059ace10b50359d42700ec2fb07c70 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Sat, 19 Sep 2026 19:55:16 +0300 Subject: [PATCH 01/29] fix(group): bound the tied groups the radix top-N selection keeps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The native top-N of the radix path kept every group at or beyond the threshold. Groups strictly beyond it number fewer than N, but the groups AT the threshold can be nearly all of them: a count-per-group top-10 over a near-unique key has a threshold of 1, every group ties it, and the "kept superset" is the whole grouping, heap-sorted by first row — a comparison sort over 100M pairs for a query whose answer is ten rows. The emitted prefix is the tied groups' first-seen order, so only the N tied groups with the smallest first row can ever be taken. The selection now keeps the strictly-better groups plus exactly those N, through a bounded max-heap, and sorts at most 2N entries. The rows emitted are the ones the full kept set produced. Tests: the pinned kept count of the radix native top-N case becomes N; a near-unique two-key grouping whose threshold every group ties, in both directions and under a row selection, against the full grouping. Co-Authored-By: Claude Fable 5.1 --- src/ops/agg_engine.c | 87 ++++++++++++++++++++++--- test/rfl/group/emit_filter_v2_route.rfl | 25 +++++++ test/test_agg_contract.c | 8 ++- 3 files changed, 109 insertions(+), 11 deletions(-) diff --git a/src/ops/agg_engine.c b/src/ops/agg_engine.c index e030b13c0..8f414c611 100644 --- a/src/ops/agg_engine.c +++ b/src/ops/agg_engine.c @@ -3724,20 +3724,91 @@ agg_radix_select_topn(ray_pool_t* pool, const agg_radix_part_t* parts, uint32_t int64_t kept = 0; for (uint32_t p = 0; p < n_parts; p++) kept += c.kept[p]; ray_free_raw(cand); ray_free_raw(cand_n); - agg_radix_order_t* sel = ray_alloc_raw((size_t)(kept > 0 ? kept : 1) * sizeof(agg_radix_order_t)); - int64_t* fr = ray_alloc_raw((size_t)(kept > 0 ? kept : 1) * sizeof(int64_t)); + /* The kept set is every group at or beyond the threshold. Groups + * strictly beyond it number fewer than N by construction, but the groups + * AT the threshold can be nearly all of them — a count-per-group top-10 + * over a near-unique key has a threshold of 1 and every group ties it — + * and sorting that set is a comparison sort over the whole grouping. + * The emitted prefix is the tied groups' first-seen order, so only the + * N tied groups with the smallest first_row can ever be taken: keep + * exactly those, through a bounded max-heap, and the sort below runs + * over at most 2N entries. Without a threshold every group is kept + * (the take exceeds the group count) and the set is small anyway. */ + int64_t take = c.have_thr ? ef->top_count_take : 0; + int64_t sel_cap = c.have_thr ? 2 * take : kept; + if (sel_cap <= 0) sel_cap = 1; + agg_radix_order_t* sel = ray_alloc_raw((size_t)sel_cap * sizeof(agg_radix_order_t)); + int64_t* fr = ray_alloc_raw((size_t)sel_cap * sizeof(int64_t)); if (!sel || !fr) { ray_free_raw(sel); ray_free_raw(fr); ray_free_raw(base); ray_free_raw(vals); ray_free_raw(keep); *rc = 1; return NULL; } int64_t k = 0; - for (uint32_t p = 0; p < n_parts; p++) - for (int64_t gg = 0; gg < parts[p].ng; gg++) - if (keep[base[p] + gg]) { - sel[k].idx = ((int64_t)p << 32) | (uint32_t)gg; - fr[k] = parts[p].first_row[gg]; - k++; + if (!c.have_thr) { + for (uint32_t p = 0; p < n_parts; p++) + for (int64_t gg = 0; gg < parts[p].ng; gg++) + if (keep[base[p] + gg]) { + sel[k].idx = ((int64_t)p << 32) | (uint32_t)gg; + fr[k] = parts[p].first_row[gg]; + k++; + } + } else { + /* strict groups fill sel[0..k); the tied heap lives in sel[take..) */ + agg_radix_order_t* hp = sel + take; + int64_t* hk = fr + take; + int64_t hn = 0; + bool overflow = false; + for (uint32_t p = 0; p < n_parts && !overflow; p++) { + const double* pv = vals + base[p]; + const uint8_t* pk = keep + base[p]; + const int64_t* pfr = parts[p].first_row; + for (int64_t gg = 0; gg < parts[p].ng; gg++) { + if (!pk[gg]) continue; + int64_t payload = ((int64_t)p << 32) | (uint32_t)gg; + if (pv[gg] != c.thr) { + if (k >= take) { overflow = true; break; } + sel[k].idx = payload; fr[k] = pfr[gg]; k++; + continue; + } + int64_t first = pfr[gg]; + if (hn < take) { + int64_t i = hn++; + hk[i] = first; hp[i].idx = payload; + while (i > 0) { /* sift up */ + int64_t par = (i - 1) / 2; + if (hk[par] >= hk[i]) break; + int64_t tk = hk[par]; hk[par] = hk[i]; hk[i] = tk; + int64_t tp = hp[par].idx; hp[par].idx = hp[i].idx; hp[i].idx = tp; + i = par; + } + } else if (first < hk[0]) { + hk[0] = first; hp[0].idx = payload; + int64_t i = 0; + for (;;) { /* sift down */ + int64_t l = 2 * i + 1, r = l + 1, m = i; + if (l < take && hk[l] > hk[m]) m = l; + if (r < take && hk[r] > hk[m]) m = r; + if (m == i) break; + int64_t tk = hk[m]; hk[m] = hk[i]; hk[i] = tk; + int64_t tp = hp[m].idx; hp[m].idx = hp[i].idx; hp[i].idx = tp; + i = m; + } + } } + } + if (overflow) { + /* more than N groups beyond the threshold: not a threshold this + * selection understands — let the caller take the full path */ + ray_free_raw(sel); ray_free_raw(fr); + ray_free_raw(base); ray_free_raw(vals); ray_free_raw(keep); *rc = 2; return NULL; + } + /* close the gap between the strict prefix and the tied heap */ + if (k < take) { + memmove(sel + k, hp, (size_t)hn * sizeof(agg_radix_order_t)); + memmove(fr + k, hk, (size_t)hn * sizeof(int64_t)); + } + k += hn; + } agg_sort_pairs_by_key(sel, fr, k); ray_free_raw(fr); ray_free_raw(base); ray_free_raw(vals); ray_free_raw(keep); *n_emit = k; diff --git a/test/rfl/group/emit_filter_v2_route.rfl b/test/rfl/group/emit_filter_v2_route.rfl index 54447a995..41a1ba01d 100644 --- a/test/rfl/group/emit_filter_v2_route.rfl +++ b/test/rfl/group/emit_filter_v2_route.rfl @@ -109,3 +109,28 @@ (set nested2 (select {from: (select {from: (select {from: tz by: k c: (count v)}) by: c n: (count c)}) where: (> n 100)})) (count nested2) -- 1 (at (at nested2 'n) 0) -- 1000 + +;; a threshold that every group ties: a near-unique two-key grouping where +;; almost every count is 1, so the N-th largest count is 1 and the kept set +;; would be the whole grouping. The result is still the first N tied groups +;; in first-seen order, and the selection must not scale with the group count. +(set n9 300000) +(set i9 (til n9)) +(set a9 (as 'I64 (+ (* i9 2654435761) (% (* i9 7) 3)))) +(set b9 (as 'I64 (% (* i9 40503) 150000))) +(set t9 (table [a b v] (list a9 b9 (% i9 5)))) +(set r9 (select {from: t9 by: [a b] c: (count v) s: (sum v) desc: c take: 10})) +(set f9 (select {from: t9 by: [a b] c: (count v) s: (sum v)})) +(count r9) -- 10 +(all (>= (at r9 'c) (at (at (xdesc f9 'c) 'c) 9))) -- true +(== (sum (at r9 'c)) (sum (take (at (xdesc f9 'c) 'c) 10))) -- true +(all (== (at r9 'a) (take (at (select {from: f9 where: (== c (max c))}) 'a) 10))) -- true +(all (== (at r9 's) (take (at (select {from: f9 where: (== c (max c))}) 's) 10))) -- true +;; the same shape under a row selection +(set r9w (select {from: t9 by: [a b] c: (count v) desc: c take: 10 where: (!= v 0)})) +(set f9w (select {from: t9 by: [a b] c: (count v) where: (!= v 0)})) +(count r9w) -- 10 +(all (== (at r9w 'a) (take (at (select {from: f9w where: (== c (max c))}) 'a) 10))) -- true +;; ascending: the smallest counts, again first-seen among the ties +(set r9a (select {from: t9 by: [a b] c: (count v) asc: c take: 10})) +(all (== (at r9a 'a) (take (at (select {from: f9 where: (== c (min c))}) 'a) 10))) -- true diff --git a/test/test_agg_contract.c b/test/test_agg_contract.c index c05e53ea7..2134755cf 100644 --- a/test/test_agg_contract.c +++ b/test/test_agg_contract.c @@ -1815,9 +1815,11 @@ static test_result_t test_radix_native_topn(void) { TEST_ASSERT_EQ_I(stats.routes[AGG_ROUTE_LEGACY], 0); TEST_ASSERT_EQ_I(stats.routes[AGG_ROUTE_V2_RADIX], 1); TEST_ASSERT_TRUE(stats.topn_native); - /* counts are 1 or 2: the top-10 superset is every count-2 group (500,000 - * of 1,500,000), not the full group set */ - TEST_ASSERT_EQ_I(stats.topn_kept, 500000); + /* counts are 1 or 2, so the threshold is 2 and every count-2 group + * (500,000 of 1,500,000) ties it: the selection keeps the ten of them + * with the smallest first row — the ones the emitted first-seen order + * would take — not the whole tie set */ + TEST_ASSERT_EQ_I(stats.topn_kept, 10); TEST_ASSERT_EQ_I(ray_table_nrows(r), 10); ray_t* check = ray_eval_str( "(== (at (at (select {from:rt_t by:[k j] c:(count v) desc:c take:10}) 'c) 0) " From bc350ddc04acd8874073508d8771d8a086acc43b Mon Sep 17 00:00:00 2001 From: Anton Date: Sat, 19 Sep 2026 18:57:43 +0200 Subject: [PATCH 02/29] feat(lang): add a `while` special form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rayfall had no way to stop iterating before the end of a sequence. Every iteration primitive — map, pmap, fold, fold-left/right, scan, scan-left/right, prior — consumes its whole input, and there was no loop construct, so a "repeat until done" loop had to be written as a fold over a fixed range whose full length was paid on every call however early the work finished. `return` did not help: it exits the lambda, not the iteration, so the fold kept calling the lambda for every remaining element. Recursion was not an alternative either, since there is no TCE and the stack tops out around 1-2k frames. (while cond body...) evaluates cond, and while it is truthy evaluates each body expression in order, then tests again. It always returns null — a statement form run for effect, and a never-taken loop has no last value to report. Zero body expressions is legal, so a condition with side effects can be the whole loop; that is the shape a drain wants, where there is no sequence to iterate over and the range was only ever scaffolding. Implemented on both evaluators, which must agree: - ray_while_fn (eval.c), registered beside `if` and `do`. - an sf_while case in the bytecode compiler emitting JMPF over a backward JMP — the first backward branch the compiler produces. The VM's op_jmp already checked for a pending interrupt when the displacement is negative (dormant until now), so a runaway loop is Ctrl-C-able for free. Compiling the body inline, rather than letting it fall through to the generic special-form path, is what keeps `return` working inside a loop: it reaches the sf_return case and unwinds the lambda instead of degrading to the tree walker's identity `return`. Neither path pushes a scope around the body. `let` binds only in the top frame (env_bind_local), so a per-iteration frame would discard loop-carried `let` state on the tree-walking path while the compiled path — whose `let` writes a function-level slot — kept it, and the two evaluators would disagree on the same source. A caller wanting a fresh frame per pass writes (while cond (do ...)), which composes. patch_jump and emit_jump_back now share write_jump_offset; an out-of-range displacement still sets c->error, dropping the lambda to the interpreter. Measured on the drain shape from the issue (4-step drain under a 4096 safety bound, release build, driver baseline subtracted): fold-left over (til 4096) 1420 us/batch, the nested 64x64 workaround 45.8 us/batch, `while` 3.8 us/batch — 374x over the original and 12x over the workaround. Closes #588 --- docs/docs/language/control-flow.md | 51 +++++++++++ docs/docs/reference/all-functions.md | 3 +- src/lang/compile.c | 60 ++++++++++++- src/lang/env.c | 2 +- src/lang/eval.c | 42 +++++++++ src/lang/eval.h | 1 + test/rfl/lang/while.rfl | 129 +++++++++++++++++++++++++++ 7 files changed, 283 insertions(+), 5 deletions(-) create mode 100644 test/rfl/lang/while.rfl diff --git a/docs/docs/language/control-flow.md b/docs/docs/language/control-flow.md index 23628d5ec..8cf4d7c69 100644 --- a/docs/docs/language/control-flow.md +++ b/docs/docs/language/control-flow.md @@ -30,6 +30,57 @@ Without an else branch, `if` returns `0`: 30 ``` +## Iteration: while + +`while` evaluates `cond`, and while it is truthy evaluates each body expression +in order, then tests again. It always returns null — it is a statement form, +run for effect. + +```text +‣ (set n 5) +‣ (set total 0) +‣ (while (> n 0) (set total (+ total n)) (set n (- n 1))) +‣ total +15 +``` + +It is the only iteration form that can stop early. `map`, `fold`, `scan` and +`prior` all consume their whole input, so a "repeat until done" loop written as +a fold over a fixed range pays that range's full length on every call, however +early the work finishes. `while` stops when the condition says stop, allocates +no range, and does not recurse — so it is not bounded by the stack depth a +recursive loop would hit. + +The body may be omitted, in which case a condition with side effects is the +whole loop. That is the natural shape when there is no sequence to iterate over +in the first place: + +```text +‣ (while (drain-one-batch)) +``` + +Unlike `do`, `while` pushes no scope of its own. A `let` in the body binds in +the enclosing frame and therefore survives the iteration, which is what makes a +`let` usable as a loop variable inside a lambda: + +```lisp +((fn [n] + (let i 0) + (let acc 0) + (while (< i n) (let acc (+ acc i)) (let i (+ i 1))) + acc) 4) ; => 6 +``` + +When a fresh binding per pass is wanted instead, wrap the body in `do`, which +does push a scope: + +```lisp +(while (< i 3) (do (let tmp (* i i)) (use tmp)) (set i (+ i 1))) +``` + +A loop whose condition never goes false runs until interrupted; Ctrl-C breaks +out of one at the REPL. + ## Variable Binding: set and let `set` creates a global binding. `let` creates a local binding scoped to the enclosing `do`: diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index 85975352c..fff747dea 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -12,7 +12,7 @@ |---|---|---| | [Arithmetic](#arithmetic) (24) | [Comparison](#comparison) (7) | [Logic](#logic) (3) | | [Aggregation](#aggregation) (25) | [Higher-Order](#higher-order) (13) | [Collection](#collection) (41) | -| [Sorting & Ordering](#sorting) (10) | [Control Flow & Special Forms](#control) (11) | [Table Operations](#table-ops) (20) | +| [Sorting & Ordering](#sorting) (10) | [Control Flow & Special Forms](#control) (12) | [Table Operations](#table-ops) (20) | | [Query](#query) (4) | [Joins](#joins) (7) | [Pivot](#pivot) (1) | | [String](#string-ops) (11) | [Temporal](#temporal) (3) | [Type & Introspection](#type-ops) (5) | | [I/O & Output](#io) (12) | [System & Utility](#system) (15) | [Serialization](#serialization) (2) | @@ -359,6 +359,7 @@ Special forms receive their arguments unevaluated. These are the core language p | `let` | binary | special | Bind value to local variable (lexical scope) | `(let y (+ x 1))` | | `if` | variadic | special | Conditional: (if cond then else) | `(if (> x 0) "pos" "neg")` | | `do` | variadic | special | Sequential execution, returns last value | `(do (set x 1) (set y 2) (+ x y))` | +| `while` | variadic | special | Iterate while cond is truthy; returns null | `(while (> n 0) (set n (- n 1)))` | | `fn` | variadic | special | Create lambda function | `(fn [x y] (+ x y))` | | `try` | binary | special | Error handling: (try expr handler-fn-or-fallback-value) | `(try (/ 1 0) (fn [e] 0))` | | `raise` | unary | — | Throw an error with message | `(raise "bad input")` | diff --git a/src/lang/compile.c b/src/lang/compile.c index 5384ff31f..a20ad8390 100644 --- a/src/lang/compile.c +++ b/src/lang/compile.c @@ -183,16 +183,39 @@ static int32_t emit_jump(compiler_t *c, uint8_t opcode) { return patch_pos; } -static void patch_jump(compiler_t *c, int32_t pos) { - int32_t raw = c->code_len - pos - 2; +/* Write a jump displacement into the 2-byte operand at `pos`, which is + * relative to the instruction's end (pos + 2). Out of int16_t range sets + * c->error, aborting bytecode emission so the lambda falls back to the + * tree-walking interpreter — the same graceful degradation as the other + * compile-time bailouts. */ +static void write_jump_offset(compiler_t *c, int32_t pos, int32_t target) { + int32_t raw = target - pos - 2; if (raw > 32767 || raw < -32768) { c->error = true; return; } int16_t offset = (int16_t)raw; c->code[pos] = (uint8_t)((uint16_t)offset >> 8); c->code[pos + 1] = (uint8_t)(offset & 0xFF); } +/* Resolve a forward jump emitted earlier, now that its target is here. */ +static void patch_jump(compiler_t *c, int32_t pos) { + write_jump_offset(c, pos, c->code_len); +} + +/* Emit an unconditional jump BACKWARD to an already-emitted address — the + * mirror of patch_jump, where the target is known up front and the + * displacement comes out negative. The VM's op_jmp checks for a pending + * interrupt whenever the offset is negative, so a runaway loop built from + * this stays Ctrl-C-able. */ +static void emit_jump_back(compiler_t *c, int32_t target) { + emit(c, OP_JMP); + int32_t pos = c->code_len; + emit(c, 0); + emit(c, 0); + write_jump_offset(c, pos, target); +} + /* Cached sym IDs for special forms */ -static _Thread_local int64_t sf_set = -1, sf_let = -1, sf_if = -1, sf_do = -1, sf_fn = -1, sf_self = -1, sf_try = -1, sf_return = -1, sf_null = -1; +static _Thread_local int64_t sf_set = -1, sf_let = -1, sf_if = -1, sf_do = -1, sf_while = -1, sf_fn = -1, sf_self = -1, sf_try = -1, sf_return = -1, sf_null = -1; static _Thread_local int64_t sf_eval = -1, sf_resolve = -1; static void init_sf_syms(void) { @@ -201,6 +224,7 @@ static void init_sf_syms(void) { sf_let = ray_sym_intern("let", 3); sf_if = ray_sym_intern("if", 2); sf_do = ray_sym_intern("do", 2); + sf_while= ray_sym_intern("while", 5); sf_fn = ray_sym_intern("fn", 2); sf_self = ray_sym_intern("self", 4); sf_try = ray_sym_intern("try", 3); @@ -369,6 +393,36 @@ static void compile_list(compiler_t *c, ray_t *ast) { return; } + /* (while cond body...) — the only backward branch the compiler + * emits. Body values are discarded (OP_POP each), and the form + * yields null however many times it iterated, matching + * ray_while_fn. No scope is pushed: `let` in the body writes this + * frame's local slot, so loop-carried state survives the pass + * exactly as it does on the tree-walking path. + * + * Compiling the body inline — rather than letting this fall through + * to the generic special-form path below — is what keeps `return` + * working inside a loop: it reaches the sf_return case and unwinds + * the lambda, instead of degrading to the tree walker's identity + * `return` (issue 588). */ + if (sym_id == sf_while && n >= 2) { + int32_t top = c->code_len; + compile_expr(c, elems[1]); + /* Truthiness belongs to the materialized value, not to the + * non-NULL lazy handle containing it — same rule as sf_if. */ + emit(c, OP_FORCE); + int32_t jmpf_pos = emit_jump(c, OP_JMPF); + for (int64_t i = 2; i < n; i++) { + compile_expr(c, elems[i]); + emit(c, OP_POP); + } + emit_jump_back(c, top); + patch_jump(c, jmpf_pos); + int32_t idx = add_constant(c, RAY_NULL_OBJ); + emit_const(c, idx); + return; + } + /* (fn [params] body...) — nested lambda via dynamic eval */ if (sym_id == sf_fn && n >= 3) { if (ast_refs_locals(c, ast)) { diff --git a/src/lang/env.c b/src/lang/env.c index a4356f630..886bbd47a 100644 --- a/src/lang/env.c +++ b/src/lang/env.c @@ -839,7 +839,7 @@ int32_t ray_env_list_user(int64_t* sym_ids, ray_t** vals, int32_t max_entries) { /* ---- Prefix lookup ---- */ static const char* s_keywords[] = { - "def", "do", "false", "fn", "if", "let", "set", "true", NULL + "def", "do", "false", "fn", "if", "let", "set", "true", "while", NULL }; /* Compare helper for qsort on const char* */ diff --git a/src/lang/eval.c b/src/lang/eval.c index d72841d44..defce74d0 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -1926,6 +1926,47 @@ ray_t* ray_do_fn(ray_t** args, int64_t n) { return result; } +/* (while cond body...) — iterate while cond is truthy. Receives + * unevaluated args. Always returns null: it is a statement form run for + * effect, and a never-taken loop has no last value to report. + * + * Zero body expressions is legal — a condition with side effects is then + * the whole loop, which is the shape a "repeat until done" drain wants + * (issue 588): there is no sequence to iterate, so folding over a range + * was only ever scaffolding. + * + * Unlike ray_do_fn this pushes NO scope around the body. `let` binds in + * the top frame only (env_bind_local), so a per-iteration frame would + * discard loop-carried `let` state here while the compiled path — whose + * `let` writes a function-level bytecode slot — kept it, and the two + * evaluators would disagree on the same source. A caller wanting a fresh + * frame per pass writes (while cond (do ...)), which composes. + * + * No interrupt check is needed: the condition goes through ray_eval on + * every pass, whose entry guard raises `cancel` when a Ctrl-C has landed. + * The compiled form is emitted by the bytecode compiler — see compile.c. */ +ray_t* ray_while_fn(ray_t** args, int64_t n) { + if (n < 1) return ray_error("domain", "while: expected at least 1 arg (cond), got %lld", (long long)n); + for (;;) { + ray_t* cond = ray_eval(args[0]); + if (RAY_IS_ERR(cond)) return cond; + /* Materialize lazy handles before testing truthiness — the + * truthiness belongs to the value, not to the non-NULL handle + * that happens to contain it (same rule as ray_cond_fn). */ + if (ray_is_lazy(cond)) + cond = ray_lazy_materialize(cond); + if (RAY_IS_ERR(cond)) return cond; + int truthy = is_truthy(cond); + ray_release(cond); + if (!truthy) return RAY_NULL_OBJ; + for (int64_t i = 1; i < n; i++) { + ray_t* val = ray_eval(args[i]); + if (RAY_IS_ERR(val)) return val; + ray_release(val); + } + } +} + /* ══════════════════════════════════════════ * Lambda functions * ══════════════════════════════════════════ */ @@ -3149,6 +3190,7 @@ static void ray_register_builtins(void) { register_binary("let", RAY_FN_SPECIAL_FORM, ray_let_fn); register_vary("if", RAY_FN_SPECIAL_FORM, ray_cond_fn); register_vary("do", RAY_FN_SPECIAL_FORM, ray_do_fn); + register_vary("while", RAY_FN_SPECIAL_FORM, ray_while_fn); register_vary("fn", RAY_FN_SPECIAL_FORM, ray_fn); /* Aggregation builtins */ diff --git a/src/lang/eval.h b/src/lang/eval.h index d52e67b3e..0630700cf 100644 --- a/src/lang/eval.h +++ b/src/lang/eval.h @@ -363,6 +363,7 @@ ray_t* ray_set_fn(ray_t* name_obj, ray_t* val_expr); ray_t* ray_let_fn(ray_t* name_obj, ray_t* val_expr); ray_t* ray_cond_fn(ray_t** args, int64_t n); ray_t* ray_do_fn(ray_t** args, int64_t n); +ray_t* ray_while_fn(ray_t** args, int64_t n); ray_t* ray_fn(ray_t** args, int64_t n); ray_t* ray_raise_fn(ray_t* val); ray_t* ray_try_fn(ray_t* expr, ray_t* handler_expr); diff --git a/test/rfl/lang/while.rfl b/test/rfl/lang/while.rfl new file mode 100644 index 000000000..8b1f24cef --- /dev/null +++ b/test/rfl/lang/while.rfl @@ -0,0 +1,129 @@ +;; (while cond body...) — the language's only early-terminating loop. +;; +;; Motivation (issue 588): every iteration primitive is exhaustive, so a +;; "repeat until done" loop had to be a fold over a fixed range whose full +;; length was paid on every call. `while` stops when the condition says so. +;; +;; Two implementations must agree: the tree walker (ray_while_fn in eval.c) +;; and the bytecode compiler (the sf_while case in compile.c, which emits a +;; backward OP_JMP). Every behavioural assertion below is therefore made +;; twice where it can be — once at top level (tree walk) and once inside a +;; lambda (compiled). The `let`-as-loop-variable cases are the ones that +;; would catch the two paths drifting apart: `let` binds in the top scope +;; frame (env.c env_bind_local), so a per-iteration scope push here would +;; make loop-carried `let` state work compiled and hang interpreted. + +;; ── basic iteration ────────────────────────────────────────────────── +(set i 0) +(set n 0) +(while (< i 5) (set n (+ n 1)) (set i (+ i 1))) +i -- 5 +n -- 5 + +;; a statement form: always null, whatever the body evaluated to +(set i 0) +(nil? (while (< i 2) (set i (+ i 1)) 'discarded)) -- true + +;; zero-trip loop: body never runs, result is still null +(set x 99) +(nil? (while false (set x 1))) -- true +x -- 99 + +;; a false-from-the-start condition that is an expression, not a literal +(set g 0) +(while (> g 0) (set g (+ g 1))) +g -- 0 + +;; ── body-less form ─────────────────────────────────────────────────── +;; The condition alone drives the loop — there is no sequence to fold over, +;; which is the shape the issue's drain loop actually wanted. +(set k 0) +(while (do (set k (+ k 1)) (< k 4))) +k -- 4 + +;; ── arity ──────────────────────────────────────────────────────────── +(while) !- domain + +;; ── termination is condition-driven, not bounded by a range ────────── +;; The step runs exactly as many times as there is work. This is precisely +;; what the fold-left workaround could not do: it called the lambda for all +;; DRAIN_STEPS elements however early the drain finished. +(set work 3) +(set calls 0) +(set step (fn [] (set calls (+ calls 1)) (set work (- work 1)) (> work 0))) +(set more true) +(while more (set more (step))) +calls -- 3 +work -- 0 + +;; ── locals: `let` as loop-carried state ────────────────────────────── +;; Compiled path: `let` writes a function-level slot, so it survives the +;; iteration. If the interpreter ever pushes a per-iteration scope, the +;; same source hangs instead — which is why this is asserted both ways. +((fn [n] (let i 0) (let acc 0) (while (< i n) (let acc (+ acc i)) (let i (+ i 1))) acc) 4) -- 6 + +;; the loop condition reads a lambda PARAM (the special_form_locals hazard) +((fn [n] (let c 0) (while (< c n) (let c (+ c 1))) c) 3) -- 3 + +;; tree-walk path, same arithmetic, via globals +(set i 0) +(set acc 0) +(while (< i 4) (set acc (+ acc i)) (set i (+ i 1))) +acc -- 6 + +;; a lambda-local loop must not leak its names to the global env +((fn [] (let scratch 7) (while false (let scratch 8)) scratch)) -- 7 +scratch !- name + +;; ── `return` from inside a body exits the enclosing lambda ─────────── +;; The compiled `while` must route its body through the normal sf_return +;; path. If `while` fell back to a dynamic tree-walk eval, `return` would +;; degrade to identity and the loop would run all ten iterations. +(set hits 0) +((fn [] (let i 0) (while (< i 10) (set hits (+ hits 1)) (if (> i 2) (return 42)) (let i (+ i 1))) 7)) -- 42 +hits -- 4 + +;; without the early return the same loop runs to completion +(set hits 0) +((fn [] (let i 0) (while (< i 10) (set hits (+ hits 1)) (let i (+ i 1))) 7)) -- 7 +hits -- 10 + +;; ── errors ─────────────────────────────────────────────────────────── +;; An error raised in the body propagates out and stops the loop — note the +;; loop would otherwise never terminate, so `c` pins that it stopped on the +;; FIRST pass. `raise` reports as a bare `domain` error and carries its +;; payload on __VM->raise_val (eval.c ray_raise_fn), so the payload is +;; asserted through `try`, which is the only way to observe it. +(set c 0) +(== (try (while true (set c (+ c 1)) (raise 'boom)) (fn [e] e)) 'boom) -- true +c -- 1 + +;; an error raised in the condition propagates before the body ever runs +(set c 0) +(== (try (while (raise 'bad-cond) (set c (+ c 1))) (fn [e] e)) 'bad-cond) -- true +c -- 0 + +;; same, unwinding out of a compiled lambda +(== (try ((fn [] (while true (raise 'inner)))) (fn [e] e)) 'inner) -- true + +;; a plain (non-raise) error in the body also terminates the loop +(set c 0) +(while true (set c (+ c 1)) (fold-right +)) !- domain +c -- 1 + +;; ── nesting ────────────────────────────────────────────────────────── +(set total 0) +(set i 0) +(while (< i 3) (set j 0) (while (< j 2) (set total (+ total 1)) (set j (+ j 1))) (set i (+ i 1))) +total -- 6 + +;; nested, compiled, with let-locals on both levels +((fn [] (let i 0) (let t 0) (while (< i 3) (let j 0) (while (< j 2) (let t (+ t 1)) (let j (+ j 1))) (let i (+ i 1))) t)) -- 6 + +;; ── explicit per-iteration isolation still composes ────────────────── +;; `while` does not push a scope; `do` does. Wrapping the body in `do` +;; gives a fresh frame per pass when that is what you want. +(set out (list)) +(set i 0) +(while (< i 3) (do (let sq (* i i)) (set out (concat out sq))) (set i (+ i 1))) +out -- (list 0 1 4) From 8168f1ea8cb24e74c4b42e685da233636c30ddfb Mon Sep 17 00:00:00 2001 From: Anton Date: Sat, 19 Sep 2026 21:14:42 +0200 Subject: [PATCH 03/29] feat(lang): add `times` and `fold-while` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two remaining early-termination forms requested in #588, alongside the `while` that landed in #590. Neither is an unblock — `while` already covers the reporter's case — but both complete the vocabulary he asked for. `times` ------- (times n body...) runs the body exactly n times and returns null. `do` is already progn in this language, so the bounded loop could not reuse that name; overloading `do` on an integer head was rejected as genuinely ambiguous — (do 5) would have to mean either "loop five times over nothing" or "return 5", and a computed first expression that happened to be an integer would silently change meaning. The count is evaluated ONCE on entry, so a body mutating whatever produced it cannot change how many passes remain. A count of zero or less runs zero times rather than trapping; a non-integer is a type error. Compiled as a counted loop over a hidden local slot, reusing the backward branch added for `while`. ray_times_norm_fn type-checks the count and clamps a negative bound to zero on entry, which lets the per-pass test be a bare truthiness check on the counter — 0 is falsy, so no comparison call is needed per pass and a negative bound cannot run away. That helper and the decrement are pushed as constant-pool objects rather than resolved by name, so the loop's own arithmetic is unnamable from source and cannot be swapped out by a `(set - ...)` override. The counter's slot is addressed by index and its sym carries a space, so no source token can collide with it and nested `times` counters stay apart. As with `while`, the body compiles inline, so `return` unwinds the enclosing lambda from inside the loop. fold-while ---------- (fold-while pred f init xs) offers the accumulator to `pred` before each step and stops on a falsy answer, yielding the accumulator as it stands. The test precedes the first element, so a predicate false at the start returns `init` untouched. The predicate takes the accumulator rather than the element: that is the form that expresses "iterate until the running result says stop", which is the early termination actually being asked for. One deliberate divergence from ray_fold_fn: that routes its collection through unbox_vec_arg -> to_boxed_list, boxing every element up front. For a primitive whose purpose is to stop early, paying for the tail it never reaches is the cost being removed, so elements are pulled one at a time via collection_elem. A plain variadic builtin — no compiler work, since it dispatches through the normal call path. Measured, release builds: `times` 100 ns/pass against 180 ns for `while` plus a manual counter over 1e6 passes. `fold-while` stopping after three elements of a 1e6-element vector costs 3.9 us against 369 ms for the `fold-left` equivalent, which had to box and walk all million to discover it was done. Tests: test/rfl/lang/times.rfl and test/rfl/collection/fold_while.rfl, each behaviour asserted on both evaluator paths where applicable — including the count validation and negative clamp on the compiled path, which runs through entirely different code from the tree walker's check. --- docs/docs/language/control-flow.md | 42 +++++++++ docs/docs/language/functions.md | 1 + docs/docs/reference/all-functions.md | 6 +- src/lang/compile.c | 68 ++++++++++++++- src/lang/env.c | 2 +- src/lang/eval.c | 75 ++++++++++++++++ src/lang/eval.h | 3 + src/lang/internal.h | 1 + src/ops/collection.c | 48 +++++++++++ test/rfl/collection/fold_while.rfl | 75 ++++++++++++++++ test/rfl/lang/times.rfl | 124 +++++++++++++++++++++++++++ 11 files changed, 441 insertions(+), 4 deletions(-) create mode 100644 test/rfl/collection/fold_while.rfl create mode 100644 test/rfl/lang/times.rfl diff --git a/docs/docs/language/control-flow.md b/docs/docs/language/control-flow.md index 8cf4d7c69..dbe7a7497 100644 --- a/docs/docs/language/control-flow.md +++ b/docs/docs/language/control-flow.md @@ -81,6 +81,35 @@ does push a scope: A loop whose condition never goes false runs until interrupted; Ctrl-C breaks out of one at the REPL. +## Bounded Iteration: times + +`times` runs the body a fixed number of times and returns null. + +```text +‣ (set n 0) +‣ (times 5 (set n (+ n 1))) +‣ n +5 +``` + +The count is evaluated **once**, on entry, so the bound is fixed however the +body mutates whatever produced it: + +```lisp +(set k 3) +(times k (set k (+ k 10))) ; runs 3 times, not forever +``` + +A count of zero or less runs the body zero times rather than raising — a bound +that computes to empty is a no-op, not an error. A non-integer count is a type +error. Like `while`, `times` pushes no scope of its own, so a `let` in the body +binds in the enclosing frame; wrap the body in `do` when a fresh binding per +pass is wanted. + +Reach for `times` when the number of passes is known up front and for `while` +when it is not. Neither allocates a sequence, so neither pays for a range that +exists only to be counted. + ## Variable Binding: set and let `set` creates a global binding. `let` creates a local binding scoped to the enclosing `do`: @@ -238,7 +267,20 @@ Lambdas are auto-mapped over vectors when called directly. Use `map` for explici ‣ (scan + [1 2 3 4 5]) ; => [1 3 6 10 15] +;; fold-while stops as soon as the running result fails the predicate, +;; leaving the rest of the collection untouched +‣ (fold-while (fn [acc] (< acc 100)) + 0 (til 1000)) +; => 105 + ;; where returns indices matching a condition ‣ (where (> (til 10) 3)) ; => [4 5 6 7 8 9] ``` + +`map`, `fold`, `scan` and `prior` all consume their whole input. `fold-while` +is the one member of the family that can stop: the accumulator is offered to +the predicate before each step, and a falsy answer ends the fold and yields the +accumulator as it stands. The test happens before the first element too, so a +predicate that is false at the start returns the initial value untouched. +Elements are pulled one at a time, so a fold that stops after three steps costs +three elements however long the collection is. diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index 58f578b7e..943e1b78a 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -133,6 +133,7 @@ Functions that take other functions as arguments. | `filter` | binary | Keep elements where boolean mask is true | `(filter [1 2 3 4] (> [1 2 3 4] 2))` → `[3 4]` | | `fold` | variadic | Reduce with function and initial value | `(fold + 0 [1 2 3])` → `6` | | `fold-left` | variadic | Left-associative fold | `(fold-left - 10 [1 2 3])` → `4` | +| `fold-while` | variadic | Fold that stops when the accumulator fails pred | `(fold-while (fn [a] (< a 100)) + 0 (til 1000))` → `105` | | `fold-right` | variadic | Right-associative fold | `(fold-right - 10 [1 2 3])` → `-8` | | `scan` | variadic | Running fold (returns all intermediate results) | `(scan + (enlist 1 2 3))` → `[1 3 6]` | | `scan-left` | variadic | Left-to-right running fold | `(scan-left + (enlist 1 2 3))` → `[1 3 6]` | diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index fff747dea..eba0d980b 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -12,7 +12,7 @@ |---|---|---| | [Arithmetic](#arithmetic) (24) | [Comparison](#comparison) (7) | [Logic](#logic) (3) | | [Aggregation](#aggregation) (25) | [Higher-Order](#higher-order) (13) | [Collection](#collection) (41) | -| [Sorting & Ordering](#sorting) (10) | [Control Flow & Special Forms](#control) (12) | [Table Operations](#table-ops) (20) | +| [Sorting & Ordering](#sorting) (10) | [Control Flow & Special Forms](#control) (13) | [Table Operations](#table-ops) (20) | | [Query](#query) (4) | [Joins](#joins) (7) | [Pivot](#pivot) (1) | | [String](#string-ops) (11) | [Temporal](#temporal) (3) | [Type & Introspection](#type-ops) (5) | | [I/O & Output](#io) (12) | [System & Utility](#system) (15) | [Serialization](#serialization) (2) | @@ -71,7 +71,7 @@ Generated from `src/lang/eval.c` in this checkout. The categorized reference bel `.db.parted.get`, `.db.parted.tables`, `.db.parted.fill`, `alter`, `print`, `.sys.gc`, `.mem.objsize`, `.mem.ts`, `.sys.timeit`, `.sys.env`, `.sys.args`, `.ipc.open`, `.ipc.handle`, `.repl.disconnect`, `.log.open`, `.log.roll`, `.log.snapshot`, `.log.sync`, `.log.close`, `.log.purge`, `quote`, `return`, `.time.now`, `.time.timer.set`, -`fold-left`, `fold-right`, `scan-left`, `scan-right`, `del`, `.sys.build`, `.sys.mem`, `.sys.prof`, +`fold-left`, `fold-while`, `fold-right`, `scan-left`, `scan-right`, `del`, `.sys.build`, `.sys.mem`, `.sys.prof`, `.sys.querylog`, `.sys.querylog.enable`, `modify`, `pivot`, `.sys.info`, `datoms`, `assert-fact`, `retract-fact`, `scan-eav`, `pull`, `rule`, `query`, `dl-program`, `dl-add-edb`, `knn`, `hnsw-build`, `ann`, `.graph.build`, `.graph.pagerank`, `.graph.connected`, `.graph.dijkstra`, `.graph.louvain`, `.graph.degree`, @@ -221,6 +221,7 @@ Functions that take other functions as arguments for mapping, folding, and filte | `pmap` | variadic | — | Parallel map (multi-threaded, returns a list) | `(pmap (fn [x] (* x x)) [1 2 3])` → `(1 4 9)` | | `fold` | variadic | — | Reduce with function and initial value | `(fold + 0 [1 2 3])` → `6` | | `fold-left` | variadic | — | Left-associative fold | `(fold-left - 10 [1 2 3])` → `4` | +| `fold-while` | variadic | — | Fold that stops when the accumulator fails pred | `(fold-while (fn [a] (< a 100)) + 0 (til 1000))` → `105` | | `fold-right` | variadic | — | Right-associative fold | `(fold-right - 10 [1 2 3])` → `-8` | | `scan` | variadic | — | Running fold (all intermediate results) | `(scan + (enlist 1 2 3))` → `[1 3 6]` | | `scan-left` | variadic | — | Left-to-right running fold | `(scan-left + (enlist 1 2 3))` → `[1 3 6]` | @@ -360,6 +361,7 @@ Special forms receive their arguments unevaluated. These are the core language p | `if` | variadic | special | Conditional: (if cond then else) | `(if (> x 0) "pos" "neg")` | | `do` | variadic | special | Sequential execution, returns last value | `(do (set x 1) (set y 2) (+ x y))` | | `while` | variadic | special | Iterate while cond is truthy; returns null | `(while (> n 0) (set n (- n 1)))` | +| `times` | variadic | special | Run body exactly n times (count evaluated once); returns null | `(times 5 (set n (+ n 1)))` | | `fn` | variadic | special | Create lambda function | `(fn [x y] (+ x y))` | | `try` | binary | special | Error handling: (try expr handler-fn-or-fallback-value) | `(try (/ 1 0) (fn [e] 0))` | | `raise` | unary | — | Throw an error with message | `(raise "bad input")` | diff --git a/src/lang/compile.c b/src/lang/compile.c index a20ad8390..f37ccfb6f 100644 --- a/src/lang/compile.c +++ b/src/lang/compile.c @@ -215,7 +215,7 @@ static void emit_jump_back(compiler_t *c, int32_t target) { } /* Cached sym IDs for special forms */ -static _Thread_local int64_t sf_set = -1, sf_let = -1, sf_if = -1, sf_do = -1, sf_while = -1, sf_fn = -1, sf_self = -1, sf_try = -1, sf_return = -1, sf_null = -1; +static _Thread_local int64_t sf_set = -1, sf_let = -1, sf_if = -1, sf_do = -1, sf_while = -1, sf_times = -1, sf_fn = -1, sf_self = -1, sf_try = -1, sf_return = -1, sf_null = -1; static _Thread_local int64_t sf_eval = -1, sf_resolve = -1; static void init_sf_syms(void) { @@ -225,6 +225,7 @@ static void init_sf_syms(void) { sf_if = ray_sym_intern("if", 2); sf_do = ray_sym_intern("do", 2); sf_while= ray_sym_intern("while", 5); + sf_times= ray_sym_intern("times", 5); sf_fn = ray_sym_intern("fn", 2); sf_self = ray_sym_intern("self", 4); sf_try = ray_sym_intern("try", 3); @@ -423,6 +424,71 @@ static void compile_list(compiler_t *c, ray_t *ast) { return; } + /* (times n body...) — a counted loop, desugared onto the same + * backward branch `while` uses. + * + * The count is evaluated ONCE into a hidden local slot, so the + * bound is fixed on entry however the body mutates its source. + * ray_times_norm_fn type-checks it and clamps a negative bound to + * zero, which is what lets the per-pass test be a bare truthiness + * check on the counter: 0 is falsy (is_truthy), everything else is + * truthy, so the loop needs no comparison call and a negative bound + * cannot run away. + * + * Both helpers are pushed as constant-pool objects rather than + * resolved by name, so the loop's own arithmetic is invisible to + * user code and immune to an override of `-` or `>`. The counter's + * slot is likewise addressed by index, never by name, and its + * sym contains a space so no source token can collide with it — + * which is what keeps nested `times` counters apart. + * + * As with `while`, compiling the body inline is what keeps + * `return` unwinding the enclosing lambda from inside the loop. */ + if (sym_id == sf_times && n >= 2) { + ray_t *norm_fn = ray_fn_unary("times norm", RAY_FN_NONE, ray_times_norm_fn); + ray_t *dec_fn = ray_fn_unary("times dec", RAY_FN_NONE, ray_times_dec_fn); + if (!norm_fn || RAY_IS_ERR(norm_fn) || !dec_fn || RAY_IS_ERR(dec_fn)) { + if (norm_fn && !RAY_IS_ERR(norm_fn)) ray_release(norm_fn); + if (dec_fn && !RAY_IS_ERR(dec_fn)) ray_release(dec_fn); + c->error = true; + return; + } + int32_t norm_idx = add_constant(c, norm_fn); + int32_t dec_idx = add_constant(c, dec_fn); + ray_release(norm_fn); + ray_release(dec_fn); + int32_t cslot = add_local(c, ray_sym_intern("times ctr", 9)); + if (cslot < 0 || c->error) { c->error = true; return; } + + /* counter = normalize() */ + emit_const(c, norm_idx); + compile_expr(c, elems[1]); + emit(c, OP_CALL1); + emit(c, OP_STOREENV); + emit(c, (uint8_t)cslot); + + int32_t top = c->code_len; + emit(c, OP_LOADENV); + emit(c, (uint8_t)cslot); + int32_t jmpf_pos = emit_jump(c, OP_JMPF); + for (int64_t i = 2; i < n; i++) { + compile_expr(c, elems[i]); + emit(c, OP_POP); + } + /* counter = counter - 1 */ + emit_const(c, dec_idx); + emit(c, OP_LOADENV); + emit(c, (uint8_t)cslot); + emit(c, OP_CALL1); + emit(c, OP_STOREENV); + emit(c, (uint8_t)cslot); + emit_jump_back(c, top); + patch_jump(c, jmpf_pos); + int32_t null_idx = add_constant(c, RAY_NULL_OBJ); + emit_const(c, null_idx); + return; + } + /* (fn [params] body...) — nested lambda via dynamic eval */ if (sym_id == sf_fn && n >= 3) { if (ast_refs_locals(c, ast)) { diff --git a/src/lang/env.c b/src/lang/env.c index 886bbd47a..65ba600a6 100644 --- a/src/lang/env.c +++ b/src/lang/env.c @@ -839,7 +839,7 @@ int32_t ray_env_list_user(int64_t* sym_ids, ray_t** vals, int32_t max_entries) { /* ---- Prefix lookup ---- */ static const char* s_keywords[] = { - "def", "do", "false", "fn", "if", "let", "set", "true", "while", NULL + "def", "do", "false", "fn", "if", "let", "set", "times", "true", "while", NULL }; /* Compare helper for qsort on const char* */ diff --git a/src/lang/eval.c b/src/lang/eval.c index defce74d0..ced4f8ad1 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -1967,6 +1967,79 @@ ray_t* ray_while_fn(ray_t** args, int64_t n) { } } +/* Read a loop count from an evaluated atom. Integers only: floats are + * rejected rather than truncated, because as_i64 on an F64 reads the bit + * pattern, and a silent (times 1.5 ...) meaning "once" hides a mistake + * either way. Returns 0 on success, or fills *err. */ +static int loop_count(ray_t* x, int64_t* out, const char* who, ray_t** err) { + if (ray_is_atom(x)) { + switch (x->type) { + case -RAY_I64: case -RAY_I32: case -RAY_I16: case -RAY_U8: + *out = as_i64(x); + return 0; + default: break; + } + } + *err = ray_error("type", "%s: count must be an integer, got %s", who, ray_type_name(x->type)); + return -1; +} + +/* The compiled `times` loop drives its counter through these two, held + * as constant-pool objects rather than bound in the env — so they carry + * no name a user could write, and the loop's arithmetic cannot be + * changed out from under it by a `(set - ...)` style override. + * + * Normalizing once on entry (type-check, and clamp a negative bound to + * zero) is what lets the loop test the raw counter for truthiness: 0 is + * falsy, every other count is truthy, so no comparison call is needed + * per pass and a negative bound cannot run away. */ +ray_t* ray_times_norm_fn(ray_t* x) { + int64_t reps = 0; + ray_t* err = NULL; + if (loop_count(x, &reps, "times", &err)) return err; + return make_i64(reps < 0 ? 0 : reps); +} + +ray_t* ray_times_dec_fn(ray_t* x) { + return make_i64(as_i64(x) - 1); +} + +/* (times n body...) — evaluate the body exactly n times. Receives + * unevaluated args. Always returns null, like `while`. + * + * `n` is evaluated ONCE, up front: the count is a bound fixed on entry, + * so a body that mutates whatever produced it cannot change how many + * passes remain. A count of zero or less runs the body zero times + * rather than trapping — a bound computed as empty is a no-op, not an + * error. + * + * Pushes no scope, for the reason given on ray_while_fn: `let` binds in + * the top frame only, so a per-pass frame would discard loop-carried + * state here while the compiled path kept it. + * + * The compiled form is emitted by the bytecode compiler — see compile.c. */ +ray_t* ray_times_fn(ray_t** args, int64_t n) { + if (n < 1) return ray_error("domain", "times: expected at least 1 arg (count), got %lld", (long long)n); + ray_t* cnt = ray_eval(args[0]); + if (RAY_IS_ERR(cnt)) return cnt; + if (ray_is_lazy(cnt)) + cnt = ray_lazy_materialize(cnt); + if (RAY_IS_ERR(cnt)) return cnt; + int64_t reps = 0; + ray_t* err = NULL; + int bad = loop_count(cnt, &reps, "times", &err); + ray_release(cnt); + if (bad) return err; + for (int64_t r = 0; r < reps; r++) { + for (int64_t i = 1; i < n; i++) { + ray_t* val = ray_eval(args[i]); + if (RAY_IS_ERR(val)) return val; + ray_release(val); + } + } + return RAY_NULL_OBJ; +} + /* ══════════════════════════════════════════ * Lambda functions * ══════════════════════════════════════════ */ @@ -3191,6 +3264,7 @@ static void ray_register_builtins(void) { register_vary("if", RAY_FN_SPECIAL_FORM, ray_cond_fn); register_vary("do", RAY_FN_SPECIAL_FORM, ray_do_fn); register_vary("while", RAY_FN_SPECIAL_FORM, ray_while_fn); + register_vary("times", RAY_FN_SPECIAL_FORM, ray_times_fn); register_vary("fn", RAY_FN_SPECIAL_FORM, ray_fn); /* Aggregation builtins */ @@ -3512,6 +3586,7 @@ static void ray_register_builtins(void) { /* Directional fold/scan variants */ register_vary("fold-left", RAY_FN_NONE, ray_fold_left_fn); + register_vary("fold-while", RAY_FN_NONE, ray_fold_while_fn); register_vary("fold-right", RAY_FN_NONE, ray_fold_right_fn); register_vary("scan-left", RAY_FN_NONE, ray_scan_left_fn); register_vary("scan-right", RAY_FN_NONE, ray_scan_right_fn); diff --git a/src/lang/eval.h b/src/lang/eval.h index 0630700cf..0cfab1d0d 100644 --- a/src/lang/eval.h +++ b/src/lang/eval.h @@ -364,6 +364,9 @@ ray_t* ray_let_fn(ray_t* name_obj, ray_t* val_expr); ray_t* ray_cond_fn(ray_t** args, int64_t n); ray_t* ray_do_fn(ray_t** args, int64_t n); ray_t* ray_while_fn(ray_t** args, int64_t n); +ray_t* ray_times_fn(ray_t** args, int64_t n); +ray_t* ray_times_norm_fn(ray_t* x); +ray_t* ray_times_dec_fn(ray_t* x); ray_t* ray_fn(ray_t** args, int64_t n); ray_t* ray_raise_fn(ray_t* val); ray_t* ray_try_fn(ray_t* expr, ray_t* handler_expr); diff --git a/src/lang/internal.h b/src/lang/internal.h index 103bdd8d5..4a5136860 100644 --- a/src/lang/internal.h +++ b/src/lang/internal.h @@ -526,6 +526,7 @@ ray_t* ray_binr_fn(ray_t* sorted, ray_t* val); ray_t* ray_map_left_fn(ray_t** args, int64_t n); ray_t* ray_map_right_fn(ray_t** args, int64_t n); ray_t* ray_fold_left_fn(ray_t** args, int64_t n); +ray_t* ray_fold_while_fn(ray_t** args, int64_t n); ray_t* ray_fold_right_fn(ray_t** args, int64_t n); ray_t* ray_scan_left_fn(ray_t** args, int64_t n); ray_t* ray_scan_right_fn(ray_t** args, int64_t n); diff --git a/src/ops/collection.c b/src/ops/collection.c index b3e29db13..b9ac009d8 100644 --- a/src/ops/collection.c +++ b/src/ops/collection.c @@ -4366,6 +4366,54 @@ ray_t* ray_fold_left_fn(ray_t** args, int64_t n) { return ray_fold_fn(args, n); } +/* (fold-while pred f init coll) — a fold that stops when the running + * result says stop. + * + * Before each step the accumulator is offered to `pred`; a falsy answer + * ends the fold and yields the accumulator as it stands. The test comes + * BEFORE the first element, so a predicate that is false at the start + * returns `init` untouched and touches nothing. + * + * Deliberately unlike ray_fold_fn in one respect: that routes its + * collection through unbox_vec_arg -> to_boxed_list, boxing every element + * up front. For a primitive whose whole purpose is to stop early, paying + * for the tail it never reaches is exactly the cost being removed here + * (issue 588), so elements are pulled one at a time via collection_elem — + * the same way map_iterate walks its input. Stopping at element three of + * a million costs three boxed atoms, not a million. */ +ray_t* ray_fold_while_fn(ray_t** args, int64_t n) { + if (n != 4) return ray_error("domain", "fold-while: requires exactly 4 args (pred, fn, init, coll), got %lld", (long long)n); + for (int64_t i = 0; i < n; i++) + if (ray_is_lazy(args[i])) args[i] = ray_lazy_materialize(args[i]); + + ray_t* pred = args[0]; + ray_t* fn = args[1]; + ray_t* coll = args[3]; + if (!is_collection(coll)) + return ray_error("type", "fold-while: coll arg must be a collection, got %s", ray_type_name(coll->type)); + + ray_retain(args[2]); + ray_t* acc = args[2]; + int64_t len = ray_len(coll); + for (int64_t i = 0; i < len; i++) { + ray_t* keep = call_fn1(pred, acc); + if (ray_is_lazy(keep)) keep = ray_lazy_materialize(keep); + if (RAY_IS_ERR(keep)) { ray_release(acc); return keep; } + int go = is_truthy(keep); + ray_release(keep); + if (!go) return acc; + + int alloc = 0; + ray_t* elem = collection_elem(coll, i, &alloc); + ray_t* next = call_fn2(fn, acc, elem); + if (alloc) ray_release(elem); + ray_release(acc); + if (RAY_IS_ERR(next)) return next; + acc = next; + } + return acc; +} + /* (fold-right fn init coll) — right fold */ ray_t* ray_fold_right_fn(ray_t** args, int64_t n) { if (n < 2) return ray_error("domain", "fold-right: requires at least 2 args (fn and vec), got %lld", (long long)n); diff --git a/test/rfl/collection/fold_while.rfl b/test/rfl/collection/fold_while.rfl new file mode 100644 index 000000000..8885c3b3a --- /dev/null +++ b/test/rfl/collection/fold_while.rfl @@ -0,0 +1,75 @@ +;; (fold-while pred f init xs) — a fold that stops when the running result +;; says stop. +;; +;; Before each step the accumulator is offered to `pred`; a falsy answer ends +;; the fold and yields the accumulator as it stands. The predicate is tested +;; BEFORE the first element too, so a predicate that is false at the start +;; returns `init` untouched. +;; +;; Unlike `fold`, this does not box the whole collection up front (`fold` +;; routes through to_boxed_list): a primitive whose purpose is to stop early +;; must not pay for the tail it never reaches. The counting assertions below +;; pin that — they fail if the implementation touches more elements than the +;; predicate allows. + +;; ── basic early termination ────────────────────────────────────────── +;; sum until the running total reaches 100 +(fold-while (fn [acc] (< acc 100)) + 0 (til 1000)) -- 105 + +;; double until past 100 — the sequence is only a step counter here +(fold-while (fn [acc] (< acc 100)) (fn [acc _x] (* acc 2)) 1 (til 1000)) -- 128 + +;; ── the predicate is tested before the first step ──────────────────── +(fold-while (fn [acc] false) + 7 (til 10)) -- 7 + +;; a predicate false at the start touches no element at all +(set seen 0) +(fold-while (fn [acc] false) (fn [acc x] (set seen (+ seen 1)) (+ acc x)) 0 (til 1000)) -- 0 +seen -- 0 + +;; ── it touches exactly as many elements as the predicate allows ────── +;; The step runs while acc < 3, so it runs for acc = 0,1,2 — three times — +;; and never looks at the remaining 997 elements. +(set seen 0) +(set r (fold-while (fn [acc] (< acc 3)) (fn [acc x] (set seen (+ seen 1)) (+ acc 1)) 0 (til 1000))) +r -- 3 +seen -- 3 + +;; ── running to completion ──────────────────────────────────────────── +;; a predicate that never fails folds the whole collection, like fold-left +(fold-while (fn [acc] true) + 0 (til 10)) -- 45 +(fold-left + 0 (til 10)) -- 45 + +;; ── empty and single-element collections ───────────────────────────── +(fold-while (fn [acc] true) + 42 (til 0)) -- 42 +(fold-while (fn [acc] false) + 42 (til 0)) -- 42 +(fold-while (fn [acc] true) + 0 (til 1)) -- 0 + +;; ── collection kinds ───────────────────────────────────────────────── +;; a boxed list, not just a typed vector +(fold-while (fn [acc] (< acc 6)) + 0 (list 1 2 3 4 5)) -- 6 + +;; a typed vector of a narrower width +(fold-while (fn [acc] (< acc 6)) + 0 [1 2 3 4 5]) -- 6 + +;; ── arity and type ─────────────────────────────────────────────────── +(fold-while) !- domain +(fold-while (fn [acc] true) + 0) !- domain +(fold-while (fn [acc] true) + 0 (til 5) 9) !- domain +(fold-while (fn [acc] true) + 0 42) !- type + +;; ── errors propagate from both callbacks ───────────────────────────── +;; from the predicate, before any step runs +(set seen 0) +(== (try (fold-while (fn [acc] (raise 'bad-pred)) (fn [acc x] (set seen (+ seen 1)) acc) 0 (til 5)) (fn [e] e)) 'bad-pred) -- true +seen -- 0 + +;; from the step function, on the first element +(== (try (fold-while (fn [acc] true) (fn [acc x] (raise 'bad-step)) 0 (til 5)) (fn [e] e)) 'bad-step) -- true + +;; ── compiled path ──────────────────────────────────────────────────── +;; the whole form inside a lambda, with the bound as a param +((fn [cap] (fold-while (fn [acc] (< acc cap)) + 0 (til 1000))) 100) -- 105 + +;; a builtin as the predicate rather than a lambda +(fold-while nil? (fn [acc _x] 1) null (til 10)) -- 1 diff --git a/test/rfl/lang/times.rfl b/test/rfl/lang/times.rfl new file mode 100644 index 000000000..05fd9c00b --- /dev/null +++ b/test/rfl/lang/times.rfl @@ -0,0 +1,124 @@ +;; (times n body...) — bounded loop: run the body exactly n times. +;; +;; The count is evaluated ONCE, up front, so a body that mutates whatever +;; produced it cannot change how many passes remain. Returns null, pushes +;; no scope, and is asserted on both evaluators — the tree walker +;; (ray_times_fn) and the bytecode compiler, whose sf_times case desugars +;; to a counted loop over a hidden local slot. + +;; ── basic counting ─────────────────────────────────────────────────── +(set n 0) +(times 5 (set n (+ n 1))) +n -- 5 + +;; a statement form: always null, whatever the body evaluated to +(nil? (times 3 'discarded)) -- true + +;; several body expressions, run in order, every pass +(set a 0) +(set b 0) +(times 4 (set a (+ a 1)) (set b (+ b a))) +a -- 4 +b -- 10 + +;; ── zero and negative counts ───────────────────────────────────────── +(set z 99) +(nil? (times 0 (set z 1))) -- true +z -- 99 + +;; a negative count runs zero times rather than trapping +(set z 99) +(nil? (times -3 (set z 1))) -- true +z -- 99 + +;; body-less form is legal and does nothing observable +(nil? (times 5)) -- true + +;; ── the count is evaluated once, up front ──────────────────────────── +;; If the count were re-read each pass this would not terminate at 3. +(set k 3) +(set passes 0) +(times k (set k (+ k 10)) (set passes (+ passes 1))) +passes -- 3 +k -- 33 + +;; the count is an arbitrary expression, evaluated once +(set calls 0) +(set howmany (fn [] (set calls (+ calls 1)) 4)) +(set p 0) +(times (howmany) (set p (+ p 1))) +p -- 4 +calls -- 1 + +;; ── arity and type ─────────────────────────────────────────────────── +(times) !- domain +(times "3" (set n 1)) !- type +(times 1.5 (set n 1)) !- type + +;; ── compiled path ──────────────────────────────────────────────────── +;; count from a lambda param, accumulator in a let-local +((fn [m] (let acc 0) (times m (let acc (+ acc 2))) acc) 5) -- 10 + +;; the count is validated and clamped on the COMPILED path too, where it +;; runs through ray_times_norm_fn rather than the tree walker's check +((fn [] (times "3" 1))) !- type +((fn [] (times 1.5 1))) !- type +((fn [n] (let z 99) (times n (let z 1)) z) -3) -- 99 +((fn [n] (let z 99) (times n (let z 1)) z) 0) -- 99 + +;; the hidden loop counter must not collide with a user local of any name +((fn [] (let n 0) (let c 100) (times 3 (let n (+ n c))) n)) -- 300 + +;; tree-walk path, same arithmetic +(set acc 0) +(times 5 (set acc (+ acc 2))) +acc -- 10 + +;; ── `return` from inside a body exits the enclosing lambda ─────────── +;; Body compiles inline, so return unwinds the lambda rather than +;; degrading to the tree walker's identity return. +(set hits 0) +((fn [] (let i 0) (times 10 (set hits (+ hits 1)) (if (> i 2) (return 42)) (let i (+ i 1))) 7)) -- 42 +hits -- 4 + +;; without the early return the same loop runs all ten passes +(set hits 0) +((fn [] (times 10 (set hits (+ hits 1))) 7)) -- 7 +hits -- 10 + +;; ── errors ─────────────────────────────────────────────────────────── +;; an error in the body propagates and stops the loop on the first pass +(set c 0) +(== (try (times 10 (set c (+ c 1)) (raise 'boom)) (fn [e] e)) 'boom) -- true +c -- 1 + +;; an error in the count propagates before the body ever runs +(set c 0) +(== (try (times (raise 'bad-count) (set c (+ c 1))) (fn [e] e)) 'bad-count) -- true +c -- 0 + +;; ── nesting ────────────────────────────────────────────────────────── +;; nested counters must not clobber one another +(set total 0) +(times 3 (times 2 (set total (+ total 1)))) +total -- 6 + +;; nested, compiled, with let-locals on both levels +((fn [] (let t 0) (times 3 (times 2 (let t (+ t 1)))) t)) -- 6 + +;; nested three deep +(set total 0) +(times 2 (times 3 (times 4 (set total (+ total 1))))) +total -- 24 + +;; ── composes with while ────────────────────────────────────────────── +(set out 0) +(set i 0) +(while (< i 3) (times 2 (set out (+ out 1))) (set i (+ i 1))) +out -- 6 + +;; ── per-pass isolation via do, as with while ───────────────────────── +(set out (list)) +(set i 0) +(times 3 (do (let sq (* i i)) (set out (concat out sq))) (set i (+ i 1))) +out -- (list 0 1 4) From 62e44476b0f585352b7d71c96a04a9485c90b5c3 Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 20 Sep 2026 11:37:36 +0200 Subject: [PATCH 04/29] perf(join): skip per-cell key null tests on provably null-free columns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ray_vec_is_null is out-of-line (no LTO) and the join called it once per key column per row in hash_row_keys — on the build side, the probe side, and the prefetch lookahead — plus twice per key column per hash-chain step in join_keys_eq, across both the count and the fill pass. A reported profile put 13.28% of a service's samples there, on a join keyed by two SYM columns that structurally never hold a null. Prove once per join that no key column can hold a null and drop the call. SYM/STR nulls are canonical empty payloads (id 0 / length 0) that HAS_NULLS does not track, so text columns are proven by the chunked zero-scan from #533 rather than by the flag; everything else reads the flag through slices and takes a set bit at face value, so the proof stays O(n) and never degrades into ray_vec_has_nulls' per-element walk. Flag-readable columns are settled first, so a nullable numeric key short-circuits before any text column is scanned. OP_CONST (atom) key slots are refused as unprovable. Also skip the #458 null-run pre-scan under the proof. It gates on ray_vec_may_have_nulls, which is unconditionally true for SYM/STR, so a SYM-keyed join ran a full per-key-per-build-row ray_vec_is_null scan before the join proper on every execution; a null-free key set cannot contain an all-null row, so the scan is dead. Measured with bench/join_nullfree (release, 1:1 book join, 4M probe x 500K build): two SYM keys 275 -> 249 ms (-9.5% median, -7.8% min); single I64 key 106 -> 99 ms (-6.3% median, -7.9% min). A proof that fails on a text key costs a partial scan (~8ms on a 4M-row SYM column) and gains nothing — only nullable SYM/STR key columns pay it. ray_join_force_null_checks forces the null-aware loops so the differential tests and the perf gate can compare both paths in one binary; ray_join_nullfree_keys counts the joins that took the fast path. Closes #597 --- bench/join_nullfree/main.c | 307 +++++++++++++++++++++++++++++++++++++ src/ops/internal.h | 2 + src/ops/join.c | 129 +++++++++++++--- test/test_join_buildside.c | 184 ++++++++++++++++++++++ 4 files changed, 599 insertions(+), 23 deletions(-) create mode 100644 bench/join_nullfree/main.c diff --git a/bench/join_nullfree/main.c b/bench/join_nullfree/main.c new file mode 100644 index 000000000..bdb3252f6 --- /dev/null +++ b/bench/join_nullfree/main.c @@ -0,0 +1,307 @@ +/* Null-free join key perf gate (#597). + * + * The join tests every key cell for null on every row: once per key column + * in hash_row_keys (build and probe, plus the prefetch lookahead) and twice + * per key column per hash-chain step in join_keys_eq, across both the count + * and the fill pass. ray_vec_is_null is out-of-line (no LTO), so each test + * is a call. A reporter profiled 13.28% of a service's samples there, on a + * join keyed by two SYM columns that structurally never hold a null. + * + * join_keys_nullfree proves once per join that no key column can hold a + * null and the loops drop the call. This measures what that is worth. + * + * Cases (all two-key SYM joins, mirroring the reported venue+instrument + * book shape): + * SYM2 right=500K (unique venue+instrument pairs), left=4M + * drawn from those pairs, both key columns null-free, so + * each left row matches exactly one right row — the shape + * of a book join, not a fan-out. The fast path must fire. + * SYM2-NULL identical, except one left venue cell is the SYM null. + * The fast path must NOT fire; both sides must time alike, + * bounding what the proof scan itself costs. + * I64 right=500K, left=4M, single I64 key, HAS_NULLS clear. + * Fast path fires via the attrs bit rather than a scan. + * + * Mechanism: ray_join_nullfree_keys must advance on SYM2 and I64 and must + * not advance on SYM2-NULL. ray_join_force_null_checks supplies the + * null-aware baseline in the same binary. + * + * Timing: CLOCK_MONOTONIC around ray_execute only. Tables built once + * outside the timed loop; graph rebuilt per rep; sides interleaved per rep + * so drift hits both equally. + */ +#if defined(__APPLE__) +# define _DARWIN_C_SOURCE +#else +# define _POSIX_C_SOURCE 200809L +#endif + +#include +#include "mem/heap.h" +#include "ops/ops.h" +#include "ops/internal.h" +#include "table/sym.h" +#include +#include +#include +#include +#include +#include + +/* ---------- timing ---------- */ +static double now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec * 1e3 + (double)ts.tv_nsec * 1e-6; +} + +static int cmp_double(const void* a, const void* b) { + double x = *(const double*)a, y = *(const double*)b; + return (x > y) - (x < y); +} +static double medianN(double arr[], int n) { + double tmp[64]; + memcpy(tmp, arr, (size_t)n * sizeof(double)); + qsort(tmp, (size_t)n, sizeof(double), cmp_double); + return tmp[n / 2]; +} +static double minN(double arr[], int n) { + double m = arr[0]; + for (int i = 1; i < n; i++) if (arr[i] < m) m = arr[i]; + return m; +} + +/* ---------- SYM column over a vocabulary of `vocab` interned symbols ------ + * Cell i takes vocabulary entry (i * stride) % vocab. null_at, when >= 0, + * is written as SYM id 0 — the canonical SYM null, which HAS_NULLS does not + * track, so only a payload scan can see it. */ +static ray_t* make_sym_col(const char* prefix, int64_t n, int64_t vocab, + int64_t stride, int64_t null_at) { + ray_t* col = ray_sym_vec_new(RAY_SYM_W64, n); + if (!col || RAY_IS_ERR(col)) { fprintf(stderr, "make_sym_col: alloc\n"); abort(); } + col->len = n; + + int64_t* ids = (int64_t*)malloc((size_t)vocab * sizeof(int64_t)); + if (!ids) { fprintf(stderr, "make_sym_col: OOM vocab\n"); abort(); } + for (int64_t v = 0; v < vocab; v++) { + char b[32]; + int m = snprintf(b, sizeof(b), "%s%lld", prefix, (long long)v); + ids[v] = ray_sym_intern(b, (size_t)m); + } + for (int64_t i = 0; i < n; i++) + ray_write_sym(ray_data(col), i, (uint64_t)ids[(i * stride) % vocab], + RAY_SYM, col->attrs); + if (null_at >= 0 && null_at < n) + ray_write_sym(ray_data(col), null_at, 0, RAY_SYM, col->attrs); + free(ids); + return col; +} + +static ray_t* make_i64_col(int64_t n, int64_t mod) { + int64_t* v = (int64_t*)malloc((size_t)n * sizeof(int64_t)); + if (!v) { fprintf(stderr, "make_i64_col: OOM\n"); abort(); } + for (int64_t i = 0; i < n; i++) v[i] = i % mod; + ray_t* col = ray_vec_from_raw(RAY_I64, v, n); + free(v); + if (!col || RAY_IS_ERR(col)) { fprintf(stderr, "make_i64_col: from_raw\n"); abort(); } + return col; +} + +static ray_t* table_of(const char* const* names, ray_t* const* cols, int64_t ncols) { + ray_t* tbl = ray_table_new(ncols); + for (int64_t c = 0; c < ncols; c++) + tbl = ray_table_add_col(tbl, ray_sym_intern(names[c], strlen(names[c])), cols[c]); + if (!tbl || RAY_IS_ERR(tbl)) { fprintf(stderr, "table_of: add_col\n"); abort(); } + return tbl; +} + +/* ---------- one inner-join rep ---------- */ +static double run_join_rep(ray_t* lt, const char* const* lkeys, + ray_t* rt, const char* const* rkeys, + uint32_t n_keys, int64_t* rows_out) { + ray_graph_t* g = ray_graph_new(lt); + if (!g) { fprintf(stderr, "run_join_rep: graph alloc\n"); abort(); } + + ray_op_t* lt_node = ray_const_table(g, lt); + ray_op_t* rt_node = ray_const_table(g, rt); + ray_op_t* lk_arr[4]; + ray_op_t* rk_arr[4]; + for (uint32_t k = 0; k < n_keys; k++) { + lk_arr[k] = ray_scan(g, lkeys[k]); + rk_arr[k] = ray_scan(g, rkeys[k]); + if (!lk_arr[k] || !rk_arr[k]) { fprintf(stderr, "run_join_rep: key node\n"); abort(); } + } + if (!lt_node || !rt_node) { fprintf(stderr, "run_join_rep: node alloc\n"); abort(); } + + ray_op_t* jn = ray_join(g, lt_node, lk_arr, rt_node, rk_arr, n_keys, 0); + if (!jn) { fprintf(stderr, "run_join_rep: join node\n"); abort(); } + jn = ray_optimize(g, jn); + + double t0 = now_ms(); + ray_t* result = ray_execute(g, jn); + double t1 = now_ms(); + + if (!result || RAY_IS_ERR(result)) { + fprintf(stderr, "run_join_rep: execute returned error\n"); abort(); + } + if (rows_out) *rows_out = ray_table_nrows(result); + ray_release(result); + ray_graph_free(g); + return t1 - t0; +} + +#define NREPS 11 + +typedef struct { + const char* name; + double fast_ms[NREPS]; /* knob off — null-free proof allowed */ + double base_ms[NREPS]; /* knob on — null-aware loops (pre-#597) */ + int64_t rows_out; +} case_result_t; + +static void run_case(const char* name, + ray_t* lt, const char* const* lkeys, + ray_t* rt, const char* const* rkeys, + uint32_t n_keys, bool expect_fast, + case_result_t* cr) { + cr->name = name; + cr->rows_out = -1; + + printf("Running case %-12s (%d reps)...\n", name, NREPS); + fflush(stdout); + + uint64_t nf_before = ray_join_nullfree_keys; + + for (int rep = 0; rep < NREPS; rep++) { + ray_join_force_null_checks = false; + int64_t rows_f = -1; + cr->fast_ms[rep] = run_join_rep(lt, lkeys, rt, rkeys, n_keys, &rows_f); + + ray_join_force_null_checks = true; + int64_t rows_b = -1; + cr->base_ms[rep] = run_join_rep(lt, lkeys, rt, rkeys, n_keys, &rows_b); + ray_join_force_null_checks = false; + + if (rows_f != rows_b) { + fprintf(stderr, + "CORRECTNESS FAILURE case %s rep %d: fast=%lld rows, baseline=%lld rows\n", + name, rep, (long long)rows_f, (long long)rows_b); + abort(); + } + cr->rows_out = rows_f; + } + + bool fired = ray_join_nullfree_keys > nf_before; + if (expect_fast != fired) { + fprintf(stderr, + "MECHANISM FAILURE case %s: expected null-free path %s " + "(before=%llu after=%llu)\n", + name, expect_fast ? "to fire" : "NOT to fire", + (unsigned long long)nf_before, + (unsigned long long)ray_join_nullfree_keys); + abort(); + } + + printf(" nullfree counter: before=%llu after=%llu fired=%s rows=%lld\n", + (unsigned long long)nf_before, + (unsigned long long)ray_join_nullfree_keys, + fired ? "YES" : "NO", + (long long)cr->rows_out); + fflush(stdout); +} + +static void report(const case_result_t* cr) { + double fmed = medianN((double*)cr->fast_ms, NREPS); + double bmed = medianN((double*)cr->base_ms, NREPS); + double fmin = minN((double*)cr->fast_ms, NREPS); + double bmin = minN((double*)cr->base_ms, NREPS); + printf("%-12s median %8.2f -> %8.2f ms (%+6.1f%%) min %8.2f -> %8.2f ms (%+6.1f%%)\n", + cr->name, bmed, fmed, 100.0 * (fmed - bmed) / bmed, + bmin, fmin, 100.0 * (fmin - bmin) / bmin); +} + +int main(void) { + ray_heap_init(); + (void)ray_sym_init(); + ray_join_force_null_checks = false; + + printf("=== bench-join-nullfree (#597) ===\n"); + printf("NREPS=%d RAY_PARALLEL_THRESHOLD=%d\n\n", + NREPS, (int)RAY_PARALLEL_THRESHOLD); + fflush(stdout); + + const int64_t nl = 4000000L; /* probe side */ + const int64_t nr = 500000L; /* build side */ + + /* ---- SYM2: two null-free SYM key columns ---- */ + printf("Building SYM2 tables (left=%lld, right=%lld)...\n", + (long long)nl, (long long)nr); + fflush(stdout); + { + /* Right: instrument unique per row, venue spread over 64 — 500K + * distinct (venue, instrument) pairs. Left: the same pairs cycled, + * so every left row has exactly one match. */ + ray_t* rv = make_sym_col("venue", nr, nr, 1, -1); + ray_t* ri = make_sym_col("inst", nr, nr, 1, -1); + ray_t* lv = make_sym_col("venue", nl, nr, 1, -1); + ray_t* li = make_sym_col("inst", nl, nr, 1, -1); + + /* SYM2-NULL shares the build side and differs only in one left cell. */ + ray_t* lv_null = make_sym_col("venue", nl, nr, 1, nl / 2); + ray_t* li_null = make_sym_col("inst", nl, nr, 1, -1); + + static const char* const lnames[] = { "lvenue", "linst" }; + static const char* const rnames[] = { "rvenue", "rinst" }; + static const char* const lkeys[] = { "lvenue", "linst" }; + static const char* const rkeys[] = { "rvenue", "rinst" }; + + ray_t* lcols[2] = { lv, li }; + ray_t* rcols[2] = { rv, ri }; + ray_t* lcols_n[2] = { lv_null, li_null }; + ray_t* lt = table_of(lnames, lcols, 2); + ray_t* rt = table_of(rnames, rcols, 2); + ray_t* lt_null = table_of(lnames, lcols_n, 2); + ray_release(lv); ray_release(li); ray_release(rv); ray_release(ri); + ray_release(lv_null); ray_release(li_null); + + case_result_t cr_sym2, cr_sym2n; + run_case("SYM2", lt, lkeys, rt, rkeys, 2, true, &cr_sym2); + run_case("SYM2-NULL", lt_null, lkeys, rt, rkeys, 2, false, &cr_sym2n); + + printf("\n--- results (baseline = forced null-aware loops) ---\n"); + report(&cr_sym2); + report(&cr_sym2n); + + ray_release(lt); ray_release(rt); ray_release(lt_null); + } + + /* ---- I64: single key, proof is the HAS_NULLS bit ---- */ + printf("\nBuilding I64 tables (left=%lld, right=%lld)...\n", + (long long)nl, (long long)nr); + fflush(stdout); + { + ray_t* lc = make_i64_col(nl, nr); + ray_t* rc = make_i64_col(nr, nr); + static const char* const lnames[] = { "lk" }; + static const char* const rnames[] = { "rk" }; + static const char* const lkeys[] = { "lk" }; + static const char* const rkeys[] = { "rk" }; + ray_t* lcols[1] = { lc }; + ray_t* rcols[1] = { rc }; + ray_t* lt = table_of(lnames, lcols, 1); + ray_t* rt = table_of(rnames, rcols, 1); + ray_release(lc); ray_release(rc); + + case_result_t cr_i64; + run_case("I64", lt, lkeys, rt, rkeys, 1, true, &cr_i64); + printf("\n--- results (baseline = forced null-aware loops) ---\n"); + report(&cr_i64); + + ray_release(lt); ray_release(rt); + } + + printf("\n(negative %% = faster with the null-free path)\n"); + ray_sym_destroy(); + ray_heap_destroy(); + return 0; +} diff --git a/src/ops/internal.h b/src/ops/internal.h index 4ff400598..2bb8dd9e9 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -804,6 +804,8 @@ extern bool ray_join_force_dup_fallback; extern bool ray_join_no_dup_fallback; extern uint64_t ray_join_dup_fallbacks; extern uint64_t ray_join_null_fallbacks; +extern bool ray_join_force_null_checks; +extern uint64_t ray_join_nullfree_keys; extern bool ray_agg_engine_v2; /* route OP_GROUP through v2 agg engine; default ON (agg_engine.c) */ void ray_expr_stats_init(void); diff --git a/src/ops/join.c b/src/ops/join.c index bc8e744c0..7a53f57f3 100644 --- a/src/ops/join.c +++ b/src/ops/join.c @@ -44,6 +44,67 @@ uint64_t ray_join_dup_fallbacks = 0; /* Diagnostic: radix joins routed to the chained path upfront because the * build side carries more all-null key rows than RADIX_DUP_RUN_MAX (#458). */ uint64_t ray_join_null_fallbacks = 0; +/* Test knob: suppress the null-free key fast path (#597) so the differential + * harness can compare it against the null-aware loops in one binary. */ +bool ray_join_force_null_checks = false; +/* Diagnostic: joins whose key columns were all proven null-free. */ +uint64_t ray_join_nullfree_keys = 0; + +/* ── #597: null-free key proof ─────────────────────────────────────────── + * ray_vec_is_null is an out-of-line call (no LTO), and the join makes one + * per key column per row in hash_row_keys plus two per key column per + * hash-chain step in join_keys_eq — on both the count and the fill pass. + * A profiled service spent 13% of its samples there. Prove ONCE per join + * that no key column can hold a null and the loops drop the call entirely. + * + * SYM/STR nulls are canonical empty payloads (id 0 / length 0) that + * HAS_NULLS does not track, so text columns are proven by the chunked, + * vectorized zero-scan from #533 rather than by the flag — which is why + * the flag alone would not have helped a SYM-keyed join. Everything else + * is the flag, read through slices by ray_vec_may_have_nulls; a set flag + * is taken at face value (a column that merely may hold a null keeps the + * null-aware path) so the proof stays O(n) and never degrades into the + * per-element walk ray_vec_has_nulls would do. + * + * An absent key column is not a null cell: hash_row_keys skips it and + * join_keys_eq rejects the pair before either reaches the null test, so + * it cannot affect the proof. */ +static bool join_key_col_nullfree(const ray_t* v) { + if (!v) return true; + /* A key slot may hold an OP_CONST literal, i.e. an atom, whose null + * state is RAY_ATOM_IS_NULL and not the vector attrs the proof reads. + * Nothing in the current tree builds such a key, so this is a guard + * rather than a fix: refuse to prove what this function cannot see. */ + if (ray_is_atom(v)) return false; + if (v->type == RAY_SYM || v->type == RAY_STR) return !ray_vec_text_has_nulls(v); + return !ray_vec_may_have_nulls(v); +} + +/* Both sides must be clean: join_keys_eq tests the left and the right cell. + * + * Flag-readable columns are settled first, in one O(1) pass, so a nullable + * numeric key short-circuits the whole proof before any text column is + * scanned. A failed proof on a text column still costs a partial scan + * (~8ms on a 4M-row SYM column, measured) with nothing to show for it — + * that is the price of a payload-encoded null, and only nullable SYM/STR + * keys pay it. */ +static bool join_key_col_scanned(const ray_t* v) { + return v && !ray_is_atom(v) && (v->type == RAY_SYM || v->type == RAY_STR); +} + +static bool join_keys_nullfree(ray_t* const* l_vecs, ray_t* const* r_vecs, + uint32_t n_keys) { + if (ray_join_force_null_checks) return false; + for (uint32_t k = 0; k < n_keys; k++) { + if (!join_key_col_scanned(l_vecs[k]) && !join_key_col_nullfree(l_vecs[k])) return false; + if (!join_key_col_scanned(r_vecs[k]) && !join_key_col_nullfree(r_vecs[k])) return false; + } + for (uint32_t k = 0; k < n_keys; k++) { + if (join_key_col_scanned(l_vecs[k]) && !join_key_col_nullfree(l_vecs[k])) return false; + if (join_key_col_scanned(r_vecs[k]) && !join_key_col_nullfree(r_vecs[k])) return false; + } + return true; +} static int join_store_key_cell(ray_t* dst, int64_t dst_row, ray_t* src, int64_t src_row) { @@ -112,13 +173,14 @@ static inline bool join_str_eq_hashed(const ray_str_t* a, const char* pool_a, * real key's hash is resolved by join_keys_eq, as for any other hash. */ #define JOIN_NULL_KEY_HASH INT64_C(0x5B7A6D3F2E1C0A94) -static uint64_t hash_row_keys(ray_t** key_vecs, uint32_t n_keys, int64_t row) { +static uint64_t hash_row_keys(ray_t** key_vecs, uint32_t n_keys, int64_t row, + bool nullfree) { uint64_t h = 0; for (uint32_t k = 0; k < n_keys; k++) { ray_t* col = key_vecs[k]; if (!col) continue; uint64_t kh; - if (ray_vec_is_null(col, row)) { + if (!nullfree && ray_vec_is_null(col, row)) { /* null == null: hash every null cell alike instead of giving the * row a private hash. A per-row hash made a null key unmatchable * even against itself, so `anti-join [c] X X` came back non-empty @@ -224,6 +286,7 @@ typedef struct { uint32_t* hashes; /* output: hash[row] */ const ray_str_t* str_desc; /* one-key STR specialization, else NULL */ const char* str_pool; + bool nullfree; /* #597: no key column can hold a null */ } join_radix_hash_ctx_t; static void join_radix_hash_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { @@ -241,14 +304,14 @@ static void join_radix_hash_fn(void* raw, uint32_t wid, int64_t start, int64_t e return; } for (int64_t r = start; r < end; r++) - c->hashes[r] = (uint32_t)hash_row_keys(c->key_vecs, c->n_keys, r); + c->hashes[r] = (uint32_t)hash_row_keys(c->key_vecs, c->n_keys, r, c->nullfree); } static join_radix_hash_ctx_t join_radix_hash_ctx(ray_t** keys, uint32_t n_keys, - uint32_t* hashes) { + uint32_t* hashes, bool nullfree) { join_radix_hash_ctx_t c = { .key_vecs = keys, .n_keys = n_keys, .hashes = hashes, - .str_desc = NULL, .str_pool = NULL, + .str_desc = NULL, .str_pool = NULL, .nullfree = nullfree, }; if (n_keys == 1 && keys[0] && keys[0]->type == RAY_STR) { ray_t* col = keys[0]; @@ -584,7 +647,7 @@ static ray_t* join_gather_col_serial(ray_t* src, const int64_t* idx, /* Key equality helper — shared by count + fill phases */ static inline bool join_keys_eq(ray_t* const* l_vecs, ray_t* const* r_vecs, uint32_t n_keys, - int64_t l, int64_t r) { + int64_t l, int64_t r, bool nullfree) { for (uint32_t k = 0; k < n_keys; k++) { ray_t* lc = l_vecs[k]; ray_t* rc = r_vecs[k]; @@ -598,8 +661,8 @@ static inline bool join_keys_eq(ray_t* const* l_vecs, ray_t* const* r_vecs, uint * whenever c held a null and made left-join miss a null-keyed match. * As-of join keeps its own documented NULLs-never-match rule; it * does not route through here. */ - bool l_null = ray_vec_is_null(lc, l); - bool r_null = ray_vec_is_null(rc, r); + bool l_null = !nullfree && ray_vec_is_null(lc, l); + bool r_null = !nullfree && ray_vec_is_null(rc, r); if (l_null || r_null) { if (l_null != r_null) return false; /* No looser than the value arms below: they pair STR only with @@ -667,6 +730,7 @@ typedef struct { const char* l_str_pool; const char* r_str_pool; uint8_t join_type; + bool nullfree; /* #597: no key column can hold a null */ /* Per-partition output: pp_l[p], pp_r[p] are local buffers */ int32_t** pp_l; /* per-partition left indices (int32_t) */ int32_t** pp_r; /* per-partition right indices (int32_t) */ @@ -858,7 +922,7 @@ static void join_radix_build_probe_fn(void* raw, uint32_t wid, int64_t task_star ? join_str_eq_hashed(&c->l_str_desc[lr], c->l_str_pool, &c->r_str_desc[rr], c->r_str_pool) : join_keys_eq(c->l_key_vecs, c->r_key_vecs, c->n_keys, - (int64_t)lr, (int64_t)rr); + (int64_t)lr, (int64_t)rr, c->nullfree); if (keys_equal) { if (!bp_grow_bufs(c, p, &pl, &pr, &cap, cnt)) goto done; @@ -908,6 +972,7 @@ typedef struct { /* ASP-Join: semijoin filter from factorized left side (NULL if N/A) */ uint64_t* asp_bits; int64_t asp_key_max; + bool nullfree; /* #597: no key column can hold a null */ } join_build_ctx_t; static void join_build_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { @@ -930,10 +995,10 @@ static void join_build_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { continue; } if (r + 8 < end) { - uint64_t pf_h = hash_row_keys(c->r_key_vecs, c->n_keys, r + 8); + uint64_t pf_h = hash_row_keys(c->r_key_vecs, c->n_keys, r + 8, c->nullfree); __builtin_prefetch(&heads[(uint32_t)(pf_h & mask)], 1, 1); } - uint64_t h = hash_row_keys(c->r_key_vecs, c->n_keys, r); + uint64_t h = hash_row_keys(c->r_key_vecs, c->n_keys, r, c->nullfree); uint32_t slot = (uint32_t)(h & mask); uint32_t row32 = (uint32_t)r; uint32_t old = atomic_load_explicit(&heads[slot], memory_order_relaxed); @@ -966,6 +1031,7 @@ typedef struct { /* S-Join: semijoin filter bitmap (NULL if not applicable) */ uint64_t* sjoin_bits; int64_t sjoin_key_max; + bool nullfree; /* #597: no key column can hold a null */ } join_probe_ctx_t; /* Pass 2a: count matches per morsel */ @@ -993,14 +1059,14 @@ static void join_count_fn(void* raw, uint32_t wid, int64_t task_start, int64_t t } if (l + 8 < row_end) { - uint64_t pf_h = hash_row_keys(c->l_key_vecs, c->n_keys, l + 8); + uint64_t pf_h = hash_row_keys(c->l_key_vecs, c->n_keys, l + 8, c->nullfree); __builtin_prefetch(&c->ht_heads[(uint32_t)(pf_h & ht_mask)], 0, 1); } - uint64_t h = hash_row_keys(c->l_key_vecs, c->n_keys, l); + uint64_t h = hash_row_keys(c->l_key_vecs, c->n_keys, l, c->nullfree); uint32_t slot = (uint32_t)(h & ht_mask); bool matched = false; for (uint32_t r = c->ht_heads[slot]; r != JHT_EMPTY; r = c->ht_next[r]) { - if (join_keys_eq(c->l_key_vecs, c->r_key_vecs, c->n_keys, l, (int64_t)r)) { + if (join_keys_eq(c->l_key_vecs, c->r_key_vecs, c->n_keys, l, (int64_t)r, c->nullfree)) { count++; matched = true; } @@ -1042,14 +1108,14 @@ static void join_fill_fn(void* raw, uint32_t wid, int64_t task_start, int64_t ta } if (l + 8 < row_end) { - uint64_t pf_h = hash_row_keys(c->l_key_vecs, c->n_keys, l + 8); + uint64_t pf_h = hash_row_keys(c->l_key_vecs, c->n_keys, l + 8, c->nullfree); __builtin_prefetch(&c->ht_heads[(uint32_t)(pf_h & ht_mask)], 0, 1); } - uint64_t h = hash_row_keys(c->l_key_vecs, c->n_keys, l); + uint64_t h = hash_row_keys(c->l_key_vecs, c->n_keys, l, c->nullfree); uint32_t slot = (uint32_t)(h & ht_mask); bool matched = false; for (uint32_t r = c->ht_heads[slot]; r != JHT_EMPTY; r = c->ht_next[r]) { - if (join_keys_eq(c->l_key_vecs, c->r_key_vecs, c->n_keys, l, (int64_t)r)) { + if (join_keys_eq(c->l_key_vecs, c->r_key_vecs, c->n_keys, l, (int64_t)r, c->nullfree)) { li[off] = l; ri[off] = (int64_t)r; off++; @@ -1156,6 +1222,10 @@ static ray_t* exec_join_flat(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ra return ray_error("oom", "join: sym domain runtime-id LUT build failed"); } + /* #597: one proof for the whole join — see join_keys_nullfree. */ + bool keys_nullfree = join_keys_nullfree(l_key_vecs, r_key_vecs, n_keys); + if (keys_nullfree) ray_join_nullfree_keys++; + ray_pool_t* pool = ray_pool_get(); /* Shared output state — used by both radix and chained HT paths */ @@ -1203,8 +1273,14 @@ static ray_t* exec_join_flat(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ra * hash_row_keys (so it counts exactly what would form the run), and * stops at the threshold. */ { + /* #597: ray_vec_may_have_nulls is unconditionally true for + * SYM/STR (their nulls are in the payload, not in attrs), so a + * SYM-keyed join always reached the row scan below — a second + * out-of-line ray_vec_is_null per key per build row, before the + * join proper, every execution. A proven null-free key set + * cannot contain an all-null row, so the whole scan is dead. */ bool any_nullable = false; - for (uint32_t k = 0; k < n_keys && !any_nullable; k++) + for (uint32_t k = 0; k < n_keys && !any_nullable && !keys_nullfree; k++) if (build_keys[k] && ray_vec_may_have_nulls(build_keys[k])) any_nullable = true; if (any_nullable) { @@ -1236,8 +1312,8 @@ static ray_t* exec_join_flat(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ra if (l_hash_hdr) scratch_free(l_hash_hdr); goto chained_ht_fallback; } - join_radix_hash_ctx_t rhctx = join_radix_hash_ctx(build_keys, n_keys, r_hashes); - join_radix_hash_ctx_t lhctx = join_radix_hash_ctx(probe_keys, n_keys, l_hashes); + join_radix_hash_ctx_t rhctx = join_radix_hash_ctx(build_keys, n_keys, r_hashes, keys_nullfree); + join_radix_hash_ctx_t lhctx = join_radix_hash_ctx(probe_keys, n_keys, l_hashes, keys_nullfree); if (pool) { ray_pool_dispatch(pool, join_radix_hash_fn, &rhctx, build_rows); ray_pool_dispatch(pool, join_radix_hash_fn, &lhctx, probe_rows); @@ -1331,7 +1407,7 @@ static ray_t* exec_join_flat(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ra join_radix_bp_ctx_t bp_ctx = { .l_parts = l_parts, .r_parts = r_parts, .l_key_vecs = probe_keys, .r_key_vecs = build_keys, - .n_keys = n_keys, .join_type = join_type, + .n_keys = n_keys, .join_type = join_type, .nullfree = keys_nullfree, .l_str_desc = lhctx.str_desc, .r_str_desc = rhctx.str_desc, .l_str_pool = lhctx.str_pool, .r_str_pool = rhctx.str_pool, .pp_l = pp_l, .pp_r = pp_r, @@ -1508,6 +1584,7 @@ chained_ht_fallback:; .n_keys = n_keys, .asp_bits = asp_bits, .asp_key_max = asp_key_max, + .nullfree = keys_nullfree, }; if (pool && right_rows > RAY_PARALLEL_THRESHOLD) ray_pool_dispatch(pool, join_build_fn, &bctx, right_rows); @@ -1585,6 +1662,7 @@ chained_ht_fallback:; .matched_right = matched_right, .sjoin_bits = sjoin_bits, .sjoin_key_max = sjoin_key_max, + .nullfree = keys_nullfree, }; /* 2a: Count matches per morsel */ @@ -2100,6 +2178,10 @@ static ray_t* exec_antijoin_flat(ray_graph_t* g, ray_op_t* op, return ray_error("oom", "join: sym domain runtime-id LUT build failed"); } + /* #597: one proof for the whole anti-join — see join_keys_nullfree. */ + bool keys_nullfree = join_keys_nullfree(l_key_vecs, r_key_vecs, n_keys); + if (keys_nullfree) ray_join_nullfree_keys++; + /* Build chained hash table from right side */ ray_t* ht_next_hdr = NULL; ray_t* ht_heads_hdr = NULL; @@ -2133,6 +2215,7 @@ static ray_t* exec_antijoin_flat(ray_graph_t* g, ray_op_t* op, .n_keys = n_keys, .asp_bits = NULL, .asp_key_max = 0, + .nullfree = keys_nullfree, }; if (pool && right_rows > RAY_PARALLEL_THRESHOLD) ray_pool_dispatch(pool, join_build_fn, &bctx, right_rows); @@ -2171,11 +2254,11 @@ static ray_t* exec_antijoin_flat(ray_graph_t* g, ray_op_t* op, scratch_free(key_vecs_hdr); return ray_error("cancel", NULL); } - uint64_t h = hash_row_keys(l_key_vecs, n_keys, l); + uint64_t h = hash_row_keys(l_key_vecs, n_keys, l, keys_nullfree); uint32_t slot = (uint32_t)(h & ht_mask); bool matched = false; for (uint32_t r = ht_heads[slot]; r != JHT_EMPTY; r = ht_next[r]) { - if (join_keys_eq(l_key_vecs, r_key_vecs, n_keys, l, (int64_t)r)) { + if (join_keys_eq(l_key_vecs, r_key_vecs, n_keys, l, (int64_t)r, keys_nullfree)) { matched = true; break; /* anti-join: one match is enough to exclude */ } diff --git a/test/test_join_buildside.c b/test/test_join_buildside.c index 30ebccaf6..a39b94155 100644 --- a/test/test_join_buildside.c +++ b/test/test_join_buildside.c @@ -1071,6 +1071,186 @@ static test_result_t test_jb_mixed_type_radix(void) { PASS(); } + +/* ── #597: null-free key-column fast path ───────────────────────────────── + * A join proves once, per key column, whether the column can hold a null + * (payload scan for SYM/STR, the HAS_NULLS bit otherwise) and skips the + * per-cell null test in hash_row_keys / join_keys_eq when no key column can. + * + * ray_join_nullfree_keys counts the joins that took that path; + * ray_join_force_null_checks suppresses it, giving the differential tests a + * null-aware oracle inside one binary (same shape as the build-swap knob). + * ──────────────────────────────────────────────────────────────────────── */ + +/* SYM table; a "" entry is the canonical SYM null (id 0). */ +static ray_t* jb_sym_table1(const char* name, const char* const* vals, int64_t n) { + ray_t* col = ray_sym_vec_new(RAY_SYM_W64, n); + if (!col || RAY_IS_ERR(col)) return col; + col->len = n; + for (int64_t i = 0; i < n; i++) { + int64_t id = vals[i][0] ? ray_sym_intern(vals[i], strlen(vals[i])) : 0; + ray_write_sym(ray_data(col), i, (uint64_t)id, RAY_SYM, col->attrs); + } + ray_t* tbl = ray_table_new(1); + int64_t sym = ray_sym_intern(name, strlen(name)); + tbl = ray_table_add_col(tbl, sym, col); + ray_release(col); + return tbl; +} + +/* I64 table with an optional null at `null_at` (-1 for none). */ +static ray_t* jb_table1_null(const char* name, const int64_t* vals, int64_t n, + int64_t null_at) { + ray_t* col = ray_vec_from_raw(RAY_I64, vals, n); + if (!col || RAY_IS_ERR(col)) return col; + if (null_at >= 0) ray_vec_set_null(col, null_at, true); + ray_t* tbl = ray_table_new(1); + int64_t sym = ray_sym_intern(name, strlen(name)); + tbl = ray_table_add_col(tbl, sym, col); + ray_release(col); + return tbl; +} + +/* SYM key columns with no null cell take the null-free path. */ +static test_result_t test_jb_nf_sym_keys_prove(void) { + ray_heap_init(); + (void)ray_sym_init(); + + static const char* const lv[] = { "NYSE", "LSE", "NYSE", "TSE" }; + static const char* const rv[] = { "LSE", "NYSE", "XETR" }; + ray_t* lt = jb_sym_table1("venue", lv, 4); + ray_t* rt = jb_sym_table1("rvenue", rv, 3); + TEST_ASSERT(lt && !RAY_IS_ERR(lt), "left SYM table"); + TEST_ASSERT(rt && !RAY_IS_ERR(rt), "right SYM table"); + + uint64_t before = ray_join_nullfree_keys; + ray_t* got = jb_inner_join(lt, "venue", rt, "rvenue"); + TEST_ASSERT(got && !RAY_IS_ERR(got), "join execution"); + TEST_ASSERT(ray_join_nullfree_keys > before, + "null-free SYM key columns must take the null-free path"); + TEST_ASSERT_EQ_I(ray_table_nrows(got), 3); + + ray_release(got); + ray_release(lt); + ray_release(rt); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* One null SYM cell on the left blocks the fast path. SYM nulls are id 0 + * in the payload and are NOT reflected in HAS_NULLS, so this case is the + * reason the proof scans the payload instead of reading the flag. */ +static test_result_t test_jb_nf_sym_null_blocks(void) { + ray_heap_init(); + (void)ray_sym_init(); + + static const char* const lv[] = { "NYSE", "", "NYSE", "TSE" }; + static const char* const rv[] = { "LSE", "NYSE", "XETR" }; + ray_t* lt = jb_sym_table1("venue", lv, 4); + ray_t* rt = jb_sym_table1("rvenue", rv, 3); + TEST_ASSERT(lt && !RAY_IS_ERR(lt), "left SYM table"); + TEST_ASSERT(rt && !RAY_IS_ERR(rt), "right SYM table"); + TEST_ASSERT_FALSE(ray_table_get_col_idx(lt, 0)->attrs & RAY_ATTR_HAS_NULLS); + + uint64_t before = ray_join_nullfree_keys; + ray_t* got = jb_inner_join(lt, "venue", rt, "rvenue"); + TEST_ASSERT(got && !RAY_IS_ERR(got), "join execution"); + TEST_ASSERT(ray_join_nullfree_keys == before, + "a null SYM key cell must block the null-free path"); + + ray_release(got); + ray_release(lt); + ray_release(rt); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* I64 keys: the HAS_NULLS bit decides. */ +static test_result_t test_jb_nf_i64_flag_decides(void) { + ray_heap_init(); + (void)ray_sym_init(); + + static const int64_t lv[] = { 1, 2, 3, 4 }; + static const int64_t rv[] = { 2, 3, 9 }; + + ray_t* lt_clean = jb_table1_null("lk", lv, 4, -1); + ray_t* rt = jb_table1_null("rk", rv, 3, -1); + uint64_t before = ray_join_nullfree_keys; + ray_t* got = jb_inner_join(lt_clean, "lk", rt, "rk"); + TEST_ASSERT(got && !RAY_IS_ERR(got), "clean join execution"); + TEST_ASSERT(ray_join_nullfree_keys > before, + "HAS_NULLS-clear I64 keys must take the null-free path"); + ray_release(got); + ray_release(lt_clean); + + ray_t* lt_null = jb_table1_null("lk", lv, 4, 1); + TEST_ASSERT_TRUE(ray_table_get_col_idx(lt_null, 0)->attrs & RAY_ATTR_HAS_NULLS); + before = ray_join_nullfree_keys; + got = jb_inner_join(lt_null, "lk", rt, "rk"); + TEST_ASSERT(got && !RAY_IS_ERR(got), "nullable join execution"); + TEST_ASSERT(ray_join_nullfree_keys == before, + "a HAS_NULLS I64 key column must block the null-free path"); + + ray_release(got); + ray_release(lt_null); + ray_release(rt); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* The null-free path must not change any answer: run every join type, at + * both the chained and the radix size, with and without null keys, against + * the forced null-aware oracle. */ +static test_result_t test_jb_nf_differential(void) { + ray_heap_init(); + (void)ray_sym_init(); + + const int64_t sizes[] = { 64, RAY_PARALLEL_THRESHOLD + 5000 }; + const uint8_t types[] = { 0, 1, 2 }; + test_result_t result = (test_result_t){ TEST_PASS, NULL }; + + for (size_t s = 0; s < sizeof sizes / sizeof *sizes && result.status == TEST_PASS; s++) { + int64_t n = sizes[s]; + int64_t* lv = malloc((size_t)n * sizeof(*lv)); + int64_t* rv = malloc((size_t)n * sizeof(*rv)); + if (!lv || !rv) { free(lv); free(rv); ray_sym_destroy(); ray_heap_destroy(); + return (test_result_t){ TEST_FAIL, "malloc" }; } + for (int64_t i = 0; i < n; i++) { lv[i] = i % (n / 4 + 1); rv[i] = i % (n / 3 + 1); } + + for (int nulls = 0; nulls < 2 && result.status == TEST_PASS; nulls++) { + ray_t* lt = jb_table1_null("lk", lv, n, nulls ? n / 2 : -1); + ray_t* rt = jb_table1_null("rk", rv, n, nulls ? n / 3 : -1); + + for (size_t t = 0; t < sizeof types / sizeof *types && result.status == TEST_PASS; t++) { + ray_join_force_null_checks = true; + ray_t* oracle = jb_join(lt, "lk", rt, "rk", types[t]); + ray_join_force_null_checks = false; + ray_t* fast = jb_join(lt, "lk", rt, "rk", types[t]); + + if (!oracle || RAY_IS_ERR(oracle) || !fast || RAY_IS_ERR(fast)) { + result = (test_result_t){ TEST_FAIL, "differential join execution" }; + } else { + result = jb_results_equal(fast, oracle); + } + ray_release(oracle); + ray_release(fast); + } + ray_release(lt); + ray_release(rt); + } + free(lv); + free(rv); + } + + ray_join_force_null_checks = false; + ray_sym_destroy(); + ray_heap_destroy(); + return result; +} + /* ── Entry table ─────────────────────────────────────────────────────────── */ const test_entry_t join_buildside_entries[] = { @@ -1093,5 +1273,9 @@ const test_entry_t join_buildside_entries[] = { { "join_buildside/not_sticky", test_jb_not_sticky, NULL, NULL }, { "join_buildside/mixed_type_radix", test_jb_mixed_type_radix, NULL, NULL }, { "join_buildside/null_run_upfront_fallback", test_jb_null_run_upfront_fallback, NULL, NULL }, + { "join_buildside/nf_sym_keys_prove", test_jb_nf_sym_keys_prove, NULL, NULL }, + { "join_buildside/nf_sym_null_blocks", test_jb_nf_sym_null_blocks, NULL, NULL }, + { "join_buildside/nf_i64_flag_decides", test_jb_nf_i64_flag_decides, NULL, NULL }, + { "join_buildside/nf_differential", test_jb_nf_differential, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; From 06449e6f6e0b5afc0c3523d6d1fdd2230cbd6f82 Mon Sep 17 00:00:00 2001 From: belowzeroff Date: Fri, 18 Sep 2026 12:10:50 -0400 Subject: [PATCH 05/29] fix(system): validate launcher and timeit integer arguments --- src/app/main.c | 9 ++++- src/lang/syscmd.c | 19 +++++++++-- src/ops/system.c | 53 +++++++++++++++++++++++++---- test/rfl/system/syscmd_coverage.rfl | 10 +++--- test/test_runtime.c | 17 ++++++++- 5 files changed, 92 insertions(+), 16 deletions(-) diff --git a/src/app/main.c b/src/app/main.c index f6ff95f3a..332773143 100644 --- a/src/app/main.c +++ b/src/app/main.c @@ -214,7 +214,14 @@ int main(int argc, char** argv) { } /* Expose the full command line to Rayfall via (.sys.args). */ - ray_runtime_set_sys_args(ray_build_sys_args(argc, argv)); + ray_t* sys_args = ray_build_sys_args(argc, argv); + if (!sys_args || RAY_IS_ERR(sys_args)) { + fprintf(stderr, "error: invalid command-line arguments\n"); + if (sys_args && RAY_IS_ERR(sys_args)) ray_error_free(sys_args); + ray_runtime_destroy(rt); + return 2; + } + ray_runtime_set_sys_args(sys_args); /* Initialise the worker pool before anything else that might use it * (file load, REPL eval, builtins). If -c wasn't given, leave the diff --git a/src/lang/syscmd.c b/src/lang/syscmd.c index a02c07c29..9fd7b44c6 100644 --- a/src/lang/syscmd.c +++ b/src/lang/syscmd.c @@ -38,6 +38,8 @@ void* ray_runtime_get_poll(void); #include +#include +#include #include #include #include @@ -79,9 +81,20 @@ static int64_t arg_as_i64(ray_t* arg, int* err) { int sign = 1; if (i < len && (p[i] == '+' || p[i] == '-')) { if (p[i] == '-') sign = -1; i++; } if (i >= len || p[i] < '0' || p[i] > '9') { *err = 1; return 0; } - int64_t v = 0; - while (i < len && p[i] >= '0' && p[i] <= '9') { v = v * 10 + (p[i] - '0'); i++; } - return sign * v; + uint64_t v = 0; + uint64_t limit = sign < 0 ? (uint64_t)INT64_MAX + 1u : (uint64_t)INT64_MAX; + while (i < len && p[i] >= '0' && p[i] <= '9') { + uint64_t digit = (uint64_t)(p[i] - '0'); + if (v > (limit - digit) / 10u) { *err = 1; return 0; } + v = v * 10u + digit; + i++; + } + if (i != len) { *err = 1; return 0; } + if (sign < 0) { + if (v == (uint64_t)INT64_MAX + 1u) return INT64_MIN; + return -(int64_t)v; + } + return (int64_t)v; } *err = 1; return 0; diff --git a/src/ops/system.c b/src/ops/system.c index dec663f7a..176415645 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -53,10 +53,12 @@ void* ray_runtime_get_poll(void); void ray_runtime_set_sys_args(void* dict); void* ray_runtime_get_sys_args(void); #include +#include #include #include #include #include + #if !defined(RAY_OS_WINDOWS) #include #include /* WIFEXITED/WEXITSTATUS — .sys.exec exit codes */ @@ -67,6 +69,25 @@ void* ray_runtime_get_sys_args(void); #define RAY_PCLOSE(f) _pclose(f) #endif +static int parse_sys_int_arg(const char* s, bool nonnegative, bool core_count, + int64_t* out) { + if (!s || !*s) return 0; + const unsigned char* p = (const unsigned char*)s; + if (!nonnegative && (*p == '+' || *p == '-')) p++; + if (!isdigit(*p)) return 0; + for (const unsigned char* q = p; *q; q++) + if (!isdigit(*q)) return 0; + + char* end = NULL; + errno = 0; + long long v = strtoll(s, &end, 10); + if (errno == ERANGE || end == s || *end != '\0' || + (nonnegative && v < 0) || (core_count && v > INT_MAX)) + return 0; + *out = (int64_t)v; + return 1; +} + /* ══════════════════════════════════════════ * Serialization / storage * ══════════════════════════════════════════ */ @@ -1553,13 +1574,33 @@ ray_t* ray_build_sys_args(int argc, char** argv) { interactive = true; else if ((strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--port") == 0) && i + 1 < argc) port = (int64_t)atoll(argv[++i]); - else if ((strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--cores") == 0) && i + 1 < argc) { - long long v = atoll(argv[++i]); if (v < 0) v = 0; cores = (int64_t)v; + else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--cores") == 0) { + if (i + 1 >= argc) + return ray_error("rank", ".sys.args: %s requires an argument", argv[i]); + int64_t v; + if (!parse_sys_int_arg(argv[++i], true, true, &v)) + return ray_error("domain", ".sys.args: invalid %s value \"%s\"", + argv[i - 1], argv[i]); + cores = v; + } + else if (strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--timeit") == 0) { + if (i + 1 >= argc) + return ray_error("rank", ".sys.args: %s requires an argument", argv[i]); + int64_t v; + if (!parse_sys_int_arg(argv[++i], false, false, &v)) + return ray_error("domain", ".sys.args: invalid %s value \"%s\"", + argv[i - 1], argv[i]); + timeit = (v != 0); + } + else if (strcmp(argv[i], "-Q") == 0 || strcmp(argv[i], "--querylog") == 0) { + if (i + 1 >= argc) + return ray_error("rank", ".sys.args: %s requires an argument", argv[i]); + int64_t v; + if (!parse_sys_int_arg(argv[++i], false, false, &v)) + return ray_error("domain", ".sys.args: invalid %s value \"%s\"", + argv[i - 1], argv[i]); + querylog = (v != 0); } - else if ((strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--timeit") == 0) && i + 1 < argc) - timeit = (atoll(argv[++i]) != 0); - else if ((strcmp(argv[i], "-Q") == 0 || strcmp(argv[i], "--querylog") == 0) && i + 1 < argc) - querylog = (atoll(argv[++i]) != 0); else if ((strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--file") == 0) && i + 1 < argc) file = argv[++i]; else if (strcmp(argv[i], "-u") == 0 && i + 1 < argc) i++; /* skip secret */ diff --git a/test/rfl/system/syscmd_coverage.rfl b/test/rfl/system/syscmd_coverage.rfl index 8a0a18fe8..a69bf0af6 100644 --- a/test/rfl/system/syscmd_coverage.rfl +++ b/test/rfl/system/syscmd_coverage.rfl @@ -55,14 +55,14 @@ (.sys.cmd "timeit 100") -- 1 (.sys.cmd "timeit 0") -- 0 -;; Empty-after-sign / non-digit start → type error (line 80). +;; Empty-after-sign / non-digit start / trailing garbage → type error. (.sys.cmd "timeit +") !- type (.sys.cmd "timeit -") !- type (.sys.cmd "timeit abc") !- type -(.sys.cmd "timeit 1.5") -- 1 -;; ^ "1.5" parses up to the dot → 1, profile turns on; the trailing -;; ".5" is not an error (the parser stops at first non-digit and -;; returns what it has). Reset state for any later toggle tests. +(.sys.cmd "timeit 1.5") !- type +(.sys.timeit "1abc") !- type +(.sys.timeit "9223372036854775808") !- type +;; Reset state for any later toggle tests. (.sys.timeit 0) -- 0 ;; ────────────── arg_as_i64: type-fallthrough (lines 85-86) ────────────── diff --git a/test/test_runtime.c b/test/test_runtime.c index 8e6094fad..35160723b 100644 --- a/test/test_runtime.c +++ b/test/test_runtime.c @@ -635,6 +635,21 @@ static test_result_t test_build_sys_args_edges(void) { PASS(); } +static test_result_t test_build_sys_args_rejects_malformed_numbers(void) { + char* cases[][3] = { + { "rayforce", "-c", "2abc" }, + { "rayforce", "-c", "999999999999999999999999" }, + { "rayforce", "-t", "1abc" }, + { "rayforce", "-Q", "0abc" }, + }; + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + ray_t* d = ray_build_sys_args(3, cases[i]); + TEST_ASSERT_TRUE(RAY_IS_ERR(d)); + ray_error_free(d); + } + PASS(); +} + /* .sys.args builtin: only `source` when unset; reflects stored dict when set */ static test_result_t test_sys_args_builtin(void) { /* unset → a dict holding just `source` (empty here: ray_eval_str is @@ -1288,6 +1303,7 @@ const test_entry_t runtime_entries[] = { { "runtime/build_sys_args_defaults", test_build_sys_args_defaults, sys_setup, sys_teardown }, { "runtime/build_sys_args_flags_user", test_build_sys_args_flags_and_user, sys_setup, sys_teardown }, { "runtime/build_sys_args_edges", test_build_sys_args_edges, sys_setup, sys_teardown }, + { "runtime/build_sys_args_rejects_malformed_numbers", test_build_sys_args_rejects_malformed_numbers, sys_setup, sys_teardown }, { "runtime/sys_args_builtin", test_sys_args_builtin, sys_setup, sys_teardown }, { "runtime/syscov_rc", test_syscov_rc, sys_setup, sys_teardown }, { "runtime/syscov_time_now", test_syscov_time_now, sys_setup, sys_teardown }, @@ -1315,4 +1331,3 @@ const test_entry_t runtime_entries[] = { { NULL, NULL, NULL, NULL }, }; - From 525a51dc41cc6ce927e99931cdd668ef8111cb79 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 21 Sep 2026 01:11:48 +0200 Subject: [PATCH 06/29] fix(cli): reject a flag as another flag's value, and unknown options MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every value-taking startup flag was gated on `i + 1 < argc` and then consumed argv[++i] blindly, so one flag silently ate the next. The shape that was reported is the worst one for a service: rayforce -Q -p 5099 svc.rfl `-Q` took `-p` as its value, the port was never bound, and nothing on stdout or stderr said so. Under a supervisor the process starts, the script runs, the unit looks healthy, and every client gets connection refused. `-c` and `-t` had the identical hole. Two neighbouring cases came out of the same code. A trailing flag with no value fell through to the positional-file arm and reported the misleading `cannot open '-Q'`. And that arm took ANY unrecognized token as the script name, which the real positional then overwrote, so a typo'd option was not merely ignored — it was silently swallowed: `rayforce -x svc.rfl` ran the script as if `-x` had never been typed. Every value-taking flag now goes through flag_value(), which refuses a missing value and a value that is EXACTLY one of this program's flag tokens (including the `--` app-args terminator), with a diagnostic and exit 2 before the script is loaded. A value that merely STARTS with '-' stays legal: a password or a negative number is a legitimate value, and refusing those would break working command lines for no gain. An unrecognized `-`-prefixed token is now an error too; a lone `-` is still a positional, and tokens after `--` belong to the app and are never validated. `-Q, --querylog N` was a real flag, referenced twice in the docs, that --help never listed beside its sibling `-t, --timeit N` — added, along with `[-Q 0|1]` in the synopsis. The suggestion to fail when `-p` was requested but nothing bound is already in (#473, listen_fatal.rfl), and cannot catch this: the parser never saw the eaten `-p`, so there was no request to check against. The guard on the value is what closes the class. Also: the two pre-existing `-p` validation bail-outs now release the runtime like every other error path, since these paths are exercised under ASan by the new test. Closes #600 --- src/app/main.c | 126 +++++++++++++++++++++------- test/rfl/system/cli_flag_values.rfl | 47 +++++++++++ 2 files changed, 142 insertions(+), 31 deletions(-) create mode 100644 test/rfl/system/cli_flag_values.rfl diff --git a/src/app/main.c b/src/app/main.c index f6ff95f3a..ad2d16bcb 100644 --- a/src/app/main.c +++ b/src/app/main.c @@ -67,6 +67,56 @@ static int64_t parse_size_arg(const char* s) { return (int64_t)(v * (double)mult); } +/* -------------------------------------------------------------------------- + * Flag-value guard (#600) + * + * Every value-taking flag used to be gated on `i + 1 < argc` and then + * consume argv[++i] blindly, so one flag silently ate the next: `-Q -p + * 5099` started a server with NO listener, no error and no warning — + * the worst shape for a service, because the unit looks healthy while + * every client gets connection refused. A trailing flag fell through to + * the positional-file arm and reported `cannot open '-Q'`. + * + * A value is refused when it is missing, or when it is EXACTLY one of + * this program's flag tokens. A value that merely STARTS with '-' (a + * password, a negative number) stays legal — refusing those would break + * working command lines for no gain. + * + * Keep this list in step with the flags handled in main's parse loop and + * with --help. (ray_build_sys_args in src/ops/system.c walks argv a + * second time for .sys.args; it only ever sees a command line that + * already passed this guard, so it cannot mis-pair.) + * -------------------------------------------------------------------------- */ +static const char* const k_known_flags[] = { + "-i", "--interactive", "-p", "--port", "-c", "--cores", + "-t", "--timeit", "-Q", "--querylog", "-f", "--file", + "-u", "-U", "-l", "-L", "-m", "--mem", "-h", "--help", + "--", /* the app-args terminator is not a value either */ + NULL +}; + +static bool arg_is_known_flag(const char* tok) { + for (int k = 0; k_known_flags[k]; k++) + if (strcmp(tok, k_known_flags[k]) == 0) return true; + return false; +} + +/* The value for a value-taking flag, or NULL with the diagnostic already + * printed. Advances *i past the value it returns. */ +static const char* flag_value(int argc, char** argv, int* i, const char* name) { + if (*i + 1 >= argc) { + fprintf(stderr, "error: %s expects a value\n", name); + return NULL; + } + const char* v = argv[*i + 1]; + if (arg_is_known_flag(v)) { + fprintf(stderr, "error: %s expects a value, got flag '%s'\n", name, v); + return NULL; + } + ++*i; + return v; +} + int main(int argc, char** argv) { /* Install the fatal-signal handler first: a crash during startup * should still produce a symbolized backtrace. Handles the fault @@ -104,17 +154,19 @@ int main(int argc, char** argv) { for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--interactive") == 0) interactive = 1; - else if ((strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--port") == 0) && i + 1 < argc) { + else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--port") == 0) { /* PORT binds all interfaces; HOST:PORT confines the listener * to one IPv4 address (#427). Strict digits-only port — a * silently truncated "65536x" listener is worse than exiting. */ - const char* parg = argv[++i]; + const char* parg = flag_value(argc, argv, &i, argv[i]); + if (!parg) { ray_runtime_destroy(rt); return 2; } const char* colon = strchr(parg, ':'); const char* pstr = parg; if (colon) { size_t hlen = (size_t)(colon - parg); if (hlen == 0 || hlen >= sizeof(bind_host)) { fprintf(stderr, "bad -p bind address: %s\n", parg); + ray_runtime_destroy(rt); return 2; } memcpy(bind_host, parg, hlen); @@ -126,44 +178,45 @@ int main(int argc, char** argv) { long pv = strtol(pstr, &endp, 10); if (endp == pstr || *endp != '\0' || errno == ERANGE || pv <= 0 || pv > 65535) { fprintf(stderr, "bad -p port (must be 1..65535): %s\n", parg); + ray_runtime_destroy(rt); return 2; } port = (uint16_t)pv; } - else if ((strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--cores") == 0) && i + 1 < argc) { - int v = atoi(argv[++i]); - if (v < 0) v = 0; - n_cores = v; - } - else if ((strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--timeit") == 0) && i + 1 < argc) { - int v = atoi(argv[++i]); - timeit_init = (v != 0); - } - else if ((strcmp(argv[i], "-Q") == 0 || strcmp(argv[i], "--querylog") == 0) && i + 1 < argc) { - int v = atoi(argv[++i]); - qlog_init = (v != 0); + else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--cores") == 0) { + const char* v = flag_value(argc, argv, &i, argv[i]); + if (!v) { ray_runtime_destroy(rt); return 2; } + n_cores = atoi(v); + if (n_cores < 0) n_cores = 0; } - else if ((strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--file") == 0) && i + 1 < argc) { - file = argv[++i]; + else if (strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--timeit") == 0) { + const char* v = flag_value(argc, argv, &i, argv[i]); + if (!v) { ray_runtime_destroy(rt); return 2; } + timeit_init = (atoi(v) != 0); } - else if (strcmp(argv[i], "-u") == 0 && i + 1 < argc) { - auth_pw = argv[++i]; - auth_restricted = false; + else if (strcmp(argv[i], "-Q") == 0 || strcmp(argv[i], "--querylog") == 0) { + const char* v = flag_value(argc, argv, &i, argv[i]); + if (!v) { ray_runtime_destroy(rt); return 2; } + qlog_init = (atoi(v) != 0); } - else if (strcmp(argv[i], "-U") == 0 && i + 1 < argc) { - auth_pw = argv[++i]; - auth_restricted = true; + else if (strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--file") == 0) { + file = flag_value(argc, argv, &i, argv[i]); + if (!file) { ray_runtime_destroy(rt); return 2; } } - else if (strcmp(argv[i], "-l") == 0 && i + 1 < argc) { - log_base = argv[++i]; - log_mode = RAY_JOURNAL_ASYNC; + else if (strcmp(argv[i], "-u") == 0 || strcmp(argv[i], "-U") == 0) { + auth_restricted = (argv[i][1] == 'U'); + auth_pw = flag_value(argc, argv, &i, argv[i]); + if (!auth_pw) { ray_runtime_destroy(rt); return 2; } } - else if (strcmp(argv[i], "-L") == 0 && i + 1 < argc) { - log_base = argv[++i]; - log_mode = RAY_JOURNAL_SYNC; + else if (strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "-L") == 0) { + log_mode = (argv[i][1] == 'L') ? RAY_JOURNAL_SYNC : RAY_JOURNAL_ASYNC; + log_base = flag_value(argc, argv, &i, argv[i]); + if (!log_base) { ray_runtime_destroy(rt); return 2; } } - else if ((strcmp(argv[i], "-m") == 0 || strcmp(argv[i], "--mem") == 0) && i + 1 < argc) { - int64_t wm = parse_size_arg(argv[++i]); + else if (strcmp(argv[i], "-m") == 0 || strcmp(argv[i], "--mem") == 0) { + const char* mv = flag_value(argc, argv, &i, argv[i]); + if (!mv) { ray_runtime_destroy(rt); return 2; } + int64_t wm = parse_size_arg(mv); if (wm <= 0) { fprintf(stderr, "error: -m/--mem expects a size like 4G, 512M, or a byte count\n"); ray_runtime_destroy(rt); @@ -173,13 +226,15 @@ int main(int argc, char** argv) { } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { fprintf(stdout, - "usage: %s [-f file] [-p port] [-c cores] [-t 0|1] [-i]" + "usage: %s [-f file] [-p port] [-c cores] [-t 0|1] [-Q 0|1] [-i]" " [-u PW | -U PW] [-l BASE | -L BASE] [-m SIZE] [file.rfl] [-- app args]\n" " -f, --file FILE run script file (or pass as a positional arg)\n" " -p, --port PORT listen for IPC clients on PORT (all interfaces)\n" " --port HOST:PORT bind the listener to HOST only (e.g. 127.0.0.1:7701)\n" " -c, --cores N total execution cores, main included (0 = auto)\n" " -t, --timeit N enable profiler at startup (N != 0)\n" + " -Q, --querylog N enable query logging at startup (N != 0);\n" + " read the ring with (.sys.querylog)\n" " -i, --interactive start the REPL even after running a file\n" " -u PW set plain auth password\n" " -U PW set restricted auth password\n" @@ -209,6 +264,15 @@ int main(int argc, char** argv) { } else if (strcmp(argv[i], "--") == 0) break; /* stop flag parsing; remaining tokens are app args */ + else if (argv[i][0] == '-' && argv[i][1] != '\0') { + /* Not a known flag. This used to fall into the positional arm + * below, so a typo'd option was silently swallowed as the script + * name and then overwritten by the real one — the flag simply + * did nothing (#600). A lone "-" stays a positional. */ + fprintf(stderr, "error: unknown option '%s'\n", argv[i]); + ray_runtime_destroy(rt); + return 2; + } else file = argv[i]; } diff --git a/test/rfl/system/cli_flag_values.rfl b/test/rfl/system/cli_flag_values.rfl new file mode 100644 index 000000000..c014eadac --- /dev/null +++ b/test/rfl/system/cli_flag_values.rfl @@ -0,0 +1,47 @@ +;; cli_flag_values.rfl — a value-taking flag must not swallow the next flag, +;; and an unknown option must not be mistaken for the script (#600). +;; +;; Regression: every value-taking flag consumed argv[++i] blindly, so +;; `-Q -p 5099` ate `-p` and started a server with NO listener, no error +;; and no warning — the worst shape for a service, since the unit looks +;; healthy and every client gets connection refused. `-c` and `-t` had +;; the same hole. A trailing `-Q` fell through to the positional-file +;; arm and failed with the misleading `cannot open '-Q'`, and an unknown +;; option was silently swallowed by that same arm. +(.sys.exec "printf '(println \"script ran\")\n' > /tmp/rfl_cfv.rfl") + +;; ---- a flag as another flag's value is rejected, script never runs ---- +;; (.sys.exec returns the raw wait status, so each case folds to 0/1) +(.sys.exec "./rayforce -Q -p 19961 /tmp/rfl_cfv.rfl /tmp/rfl_cfv.out 2>&1; rc=$?; grep -q 'script ran' /tmp/rfl_cfv.out && exit 99; grep -q \"\\-Q expects a value, got flag '-p'\" /tmp/rfl_cfv.out || exit 98; [ $rc -eq 2 ]") -- 0 + +;; the same hole in -c and -t +(.sys.exec "./rayforce -c -p 19962 /tmp/rfl_cfv.rfl /tmp/rfl_cfv.out 2>&1; rc=$?; grep -q 'script ran' /tmp/rfl_cfv.out && exit 99; grep -q \"\\-c expects a value, got flag '-p'\" /tmp/rfl_cfv.out || exit 98; [ $rc -eq 2 ]") -- 0 +(.sys.exec "./rayforce -t -p 19963 /tmp/rfl_cfv.rfl /tmp/rfl_cfv.out 2>&1; rc=$?; grep -q 'script ran' /tmp/rfl_cfv.out && exit 99; grep -q \"\\-t expects a value, got flag '-p'\" /tmp/rfl_cfv.out || exit 98; [ $rc -eq 2 ]") -- 0 + +;; long form too +(.sys.exec "./rayforce --querylog --port 19964 /tmp/rfl_cfv.rfl /tmp/rfl_cfv.out 2>&1; rc=$?; grep -q 'script ran' /tmp/rfl_cfv.out && exit 99; grep -q \"expects a value, got flag '--port'\" /tmp/rfl_cfv.out || exit 98; [ $rc -eq 2 ]") -- 0 + +;; ---- a missing value says so, instead of 'cannot open' ---- +(.sys.exec "./rayforce /tmp/rfl_cfv.rfl -Q /tmp/rfl_cfv.out 2>&1; rc=$?; grep -q \"cannot open\" /tmp/rfl_cfv.out && exit 99; grep -q \"\\-Q expects a value\" /tmp/rfl_cfv.out || exit 98; [ $rc -eq 2 ]") -- 0 + +;; ---- an unknown option is rejected, not taken as the script ---- +(.sys.exec "./rayforce -x /tmp/rfl_cfv.rfl /tmp/rfl_cfv.out 2>&1; rc=$?; grep -q 'script ran' /tmp/rfl_cfv.out && exit 99; grep -q \"unknown option '-x'\" /tmp/rfl_cfv.out || exit 98; [ $rc -eq 2 ]") -- 0 + +;; ---- values that merely START with '-' are still accepted ---- +;; A password or a negative number is a legitimate value; only an exact +;; match against a known flag token is refused. +(.sys.exec "./rayforce -u -s3cret -t -1 /tmp/rfl_cfv.rfl /tmp/rfl_cfv.out 2>&1; grep -q 'script ran' /tmp/rfl_cfv.out") -- 0 + +;; ---- the -Q that #600 was reached through still works, and still binds ---- +(.sys.exec "./rayforce -Q 1 -p 19965 /tmp/rfl_cfv.rfl /tmp/rfl_cfv2.out 2>&1 & p=$!; for i in $(seq 50); do grep -q 'script ran' /tmp/rfl_cfv2.out && break; sleep 0.1; done; bash -c '(echo > /dev/tcp/127.0.0.1/19965) 2>/dev/null'; rc=$?; kill $p 2>/dev/null; [ $rc -eq 0 ]") -- 0 + +;; the app-args terminator is not a value either +(.sys.exec "./rayforce -Q -- /tmp/rfl_cfv.rfl /tmp/rfl_cfv.out 2>&1; rc=$?; grep -q \"\\-Q expects a value, got flag '--'\" /tmp/rfl_cfv.out || exit 98; [ $rc -eq 2 ]") -- 0 + +;; ---- tokens after `--` belong to the app and are never validated ---- +(.sys.exec "./rayforce /tmp/rfl_cfv.rfl -- -Q -p /tmp/rfl_cfv.out 2>&1; grep -q 'script ran' /tmp/rfl_cfv.out") -- 0 + +;; ---- --help still lists -Q, beside its sibling -t ---- +(.sys.exec "./rayforce --help 2>&1 | grep -q -- '-Q, --querylog'") -- 0 + +(.sys.exec "rm -f /tmp/rfl_cfv.rfl /tmp/rfl_cfv.out /tmp/rfl_cfv2.out; true") From 63d91b1ef5cee7b488184c7dfe9c4ba8fba69329 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Mon, 21 Sep 2026 10:56:19 +0300 Subject: [PATCH 07/29] fix(exec): release the input table of window, sort and limit unconditionally MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every node the executor evaluates returns an owned reference — the constant table node included, it retains its literal. The OP_WINDOW, OP_SORT and OP_HEAD cases released their input only when it differed from the graph's table, taking an equal pointer for a borrowed one. A query's root is a constant node over that very table, so the reference was never released: one input table per windowed, sorted or limited query. Invisible while a global kept the table alive; a whole table per call when the input was built for that call, as a service that windowed a freshly concatenated buffer on a timer found (#602). The four cases now release the input on every path, as the join and the plain head/tail cases already did. Test: window, sorted and limited selects over a table built per call, measured with the two-window bytes-allocated method of the other memory probes, plus a shared input reused across fifty calls. Co-Authored-By: Claude Fable 5.1 --- src/ops/exec.c | 27 ++++++++++-------- test/rfl/mem/query_input_release.rfl | 42 ++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 11 deletions(-) create mode 100644 test/rfl/mem/query_input_release.rfl diff --git a/src/ops/exec.c b/src/ops/exec.c index 93b549448..d762388dc 100644 --- a/src/ops/exec.c +++ b/src/ops/exec.c @@ -2610,20 +2610,26 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } case OP_SORT: { + /* exec_node hands back an OWNED reference for every node, + * the constant table node included (it retains its literal). + * A `!= g->table` guard here treated a child that evaluates + * to the query table as borrowed and leaked one table per + * call — the ordinary shape, since a select's root is a + * constant node over that very table. */ ray_t* input = exec_node(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; ray_t* tbl = (input->type == RAY_TABLE) ? input : g->table; /* Compact lazy selection before sort (needs dense data) */ if (g->selection && tbl && !RAY_IS_ERR(tbl) && tbl->type == RAY_TABLE) { ray_t* compacted = sel_compact(g, tbl, g->selection, NULL, 0); - if (input != g->table) ray_release(input); + ray_release(input); ray_release(g->selection); g->selection = NULL; input = compacted; tbl = compacted; } ray_t* result = exec_sort(g, op, tbl, 0); - if (input != g->table) ray_release(input); + ray_release(input); return result; } @@ -2835,20 +2841,21 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } case OP_WINDOW: { + /* Owned input, released unconditionally: see OP_SORT. */ ray_t* input = exec_node(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; ray_t* wdf = (input->type == RAY_TABLE) ? input : g->table; /* Compact lazy selection before window (needs dense data) */ if (g->selection && wdf && !RAY_IS_ERR(wdf) && wdf->type == RAY_TABLE) { ray_t* compacted = sel_compact(g, wdf, g->selection, NULL, 0); - if (input != g->table) ray_release(input); + ray_release(input); ray_release(g->selection); g->selection = NULL; input = compacted; wdf = compacted; } ray_t* result = exec_window(g, op, wdf); - if (input != g->table) ray_release(input); + ray_release(input); return result; } @@ -2865,14 +2872,14 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { /* Compact lazy selection before sort */ if (g->selection && tbl && !RAY_IS_ERR(tbl) && tbl->type == RAY_TABLE) { ray_t* compacted = sel_compact(g, tbl, g->selection, NULL, 0); - if (sort_input != g->table) ray_release(sort_input); + ray_release(sort_input); /* owned: see OP_SORT */ ray_release(g->selection); g->selection = NULL; sort_input = compacted; tbl = compacted; } ray_t* result = exec_sort(g, child_op, tbl, n); - if (sort_input != g->table) ray_release(sort_input); + ray_release(sort_input); /* Top-level statement GC catches intermediates. */ return result; } @@ -2935,7 +2942,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ? filter_input : g->table; if (g->selection && ftbl && ftbl->type == RAY_TABLE) { ray_t* compacted = sel_compact(g, ftbl, g->selection, NULL, 0); - if (filter_input != g->table) ray_release(filter_input); + ray_release(filter_input); /* owned: see OP_SORT */ ray_release(g->selection); g->selection = NULL; filter_input = compacted; @@ -2949,15 +2956,13 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { g->table = saved_table; if (!pred || RAY_IS_ERR(pred)) { - if (filter_input != saved_table) - ray_release(filter_input); + ray_release(filter_input); return pred; } ray_t* result = exec_filter_head(ftbl, pred, n); ray_release(pred); - if (filter_input != saved_table) - ray_release(filter_input); + ray_release(filter_input); /* Top-level statement GC catches intermediates. */ return result; } else { diff --git a/test/rfl/mem/query_input_release.rfl b/test/rfl/mem/query_input_release.rfl new file mode 100644 index 000000000..80d4c0c0c --- /dev/null +++ b/test/rfl/mem/query_input_release.rfl @@ -0,0 +1,42 @@ +;; query_input_release.rfl — a query over a table built for that one call +;; must give the table back. +;; +;; Every node the executor evaluates hands back an OWNED reference, the +;; constant table node included. The window, sort and limit cases once +;; skipped the release when the input equalled the graph's table, taking it +;; for a borrowed reference — and a query's root is a constant node over that +;; very table, so one input table leaked per call. Invisible while a global +;; kept the table alive; a whole table per call on a fresh one. +;; +;; Same method as the other probes in this directory: warm up, then two equal +;; windows of calls; the first may settle a slab or an arena, the second must +;; not move. `bytes-allocated` is exact, so the bound is a few KB; the table +;; below is ~19 KB, so a single leaked call already fails it. +(set syms (as 'SYMBOL (map (fn [i] (format "inst%" i)) (til 700)))) +(set mk (fn [p] (table [instrument rid v] (list (take syms 786) (as 'I64 (+ p (til 786))) (as 'I64 (til 786)))))) +(set heapb (fn [] (at (.sys.mem) 'bytes-allocated))) +(set probe (fn [f warm reps] (do (map f (til warm)) (map f (til reps)) (set h0 (heapb)) (map f (til reps)) (< (- (heapb) h0) 4096)))) + +;; partitioned + ordered, trailing frame (the shape of the report) +(probe (fn [p] (count (window {from: (mk p) part: [instrument] order: [rid] frame: 2 funcs: {prev: (first v) n: (count v)}}))) 5 60) -- true +;; no part/order: the whole table is one partition +(probe (fn [p] (count (window {from: (mk p) funcs: {n: (count v)}}))) 5 60) -- true +;; running frame +(probe (fn [p] (count (window {from: (mk p) part: [instrument] order: [rid] frame: 'running funcs: {s: (sum v)}}))) 5 60) -- true +;; a where: on the window input (from: is materialised before the window) +(probe (fn [p] (count (window {from: (select {from: (mk p) where: (> rid 3)}) part: [instrument] order: [rid] funcs: {n: (count v)}}))) 5 60) -- true +;; the same guard sat under sort and limit: a sorted or limited select over +;; a table built for the call leaked it the same way +(probe (fn [p] (count (select {from: (mk p) asc: rid}))) 5 60) -- true +(probe (fn [p] (count (select {from: (mk p) desc: v take: 5}))) 5 60) -- true +(probe (fn [p] (count (select {from: (mk p) where: (> rid 3) take: 5}))) 5 60) -- true +(probe (fn [p] (count (select {from: (mk p) where: (> rid 3) asc: v}))) 5 60) -- true +(probe (fn [p] (count (select {from: (mk p) by: instrument s: (sum v) asc: s}))) 5 60) -- true +(probe (fn [p] (count (select {from: (mk p) by: instrument s: (sum v) desc: s take: 3}))) 5 60) -- true +;; the same table reused across calls must not be released twice: the +;; result is still right after many calls +(set T (mk 1)) +(map (fn [p] (window {from: T part: [instrument] order: [rid] funcs: {n: (count v)}})) (til 50)) +(count T) -- 786 +(count (window {from: T part: [instrument] order: [rid] funcs: {n: (count v)}})) -- 786 +(== (sum (at (window {from: T part: [instrument] order: [rid] frame: 'running funcs: {s: (sum v)}}) 's)) (sum (at (window {from: T part: [instrument] order: [rid] frame: 'running funcs: {s: (sum v)}}) 's))) -- true From a2fe4960d46a529d1717df161a2a9d6217eeae1b Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Mon, 21 Sep 2026 11:16:20 +0300 Subject: [PATCH 08/29] test(lang): pin the refcount of a table across window, sort and limit queries Twenty calls of each shape over one global table; the table's refcount must be exactly what it was before, and the table still whole after. Fails on the unfixed executor at the first window shape. Co-Authored-By: Claude Fable 5.1 --- test/test_lang.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/test/test_lang.c b/test/test_lang.c index 1aaa33c64..afbdf69d0 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -8703,6 +8703,58 @@ static test_result_t test_builtin_group_guid_rfl(void) { * the expression over the vocabulary bytes a chunk at a time. With the * chunk shrunk to 100 values, a 200-value vocabulary crosses chunk * boundaries; the groups and aggregates must equal the in-memory answer. */ +/* ---- Test: a query releases the table it was given ------------------- + * Every node the executor evaluates returns an owned reference, the + * constant table node a query is rooted on included. The window, sort + * and limit cases used to skip that release when the input equalled the + * graph's table, so each such query left one reference behind: the + * table's refcount climbed by one per call and, for a table built for + * the call, the whole table stayed allocated. Pin the refcount: after + * twenty calls of each shape it must be exactly what it was before. */ +static test_result_t test_select_releases_input_table(void) { + ray_t* setup = ray_eval_str( + "(do (set __rl_i (til 786)) " + " (set __rl_syms (as 'SYMBOL (map (fn [i] (format \"inst%\" i)) (til 700)))) " + " (set __rl_T (table [instrument rid v] (list (take __rl_syms 786) __rl_i (% (* 7 __rl_i) 101)))) 0)"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); ray_release(setup); + ray_t* T = ray_eval_str("__rl_T"); /* one more ref: ours */ + TEST_ASSERT_NOT_NULL(T); TEST_ASSERT_FALSE(RAY_IS_ERR(T)); + TEST_ASSERT_EQ_I(T->type, RAY_TABLE); + uint32_t rc0 = ray_atomic_load(&T->rc); + static const char* const shapes[] = { + "(window {from: __rl_T part: [instrument] order: [rid] frame: 2 funcs: {n: (count v)}})", + "(window {from: __rl_T funcs: {n: (count v)}})", + "(window {from: __rl_T part: [instrument] order: [rid] frame: 'running funcs: {s: (sum v)}})", + "(select {from: __rl_T asc: rid})", + "(select {from: __rl_T desc: v take: 5})", + "(select {from: __rl_T where: (> rid 3) take: 5})", + "(select {from: __rl_T where: (> rid 3) asc: v})", + "(select {from: __rl_T by: instrument s: (sum v) asc: s})", + "(select {from: __rl_T by: instrument s: (sum v) desc: s take: 3})", + "(select {from: __rl_T take: 5})", + "(select {from: __rl_T where: (> rid 3)})", + }; + for (size_t k = 0; k < sizeof(shapes) / sizeof(shapes[0]); k++) { + for (int i = 0; i < 20; i++) { + ray_t* r = ray_eval_str(shapes[k]); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->type, RAY_TABLE); + ray_release(r); + } + if (ray_atomic_load(&T->rc) != rc0) + FAIL(shapes[k]); + } + /* the table is still whole after all of that */ + ray_t* n = ray_eval_str("(count __rl_T)"); + TEST_ASSERT_NOT_NULL(n); TEST_ASSERT_FALSE(RAY_IS_ERR(n)); + TEST_ASSERT_EQ_I(n->i64, 786); + ray_release(n); + ray_release(T); + ray_release(ray_eval_str("(set __rl_T 0) (set __rl_i 0) (set __rl_syms 0)")); + PASS(); +} + static test_result_t test_select_derived_key_file_chunks(void) { ray_t* r = ray_eval_str( "(do (set __dk_i (til 20000)) " @@ -9600,6 +9652,7 @@ const test_entry_t lang_entries[] = { { "lang/builtin/group_guid_rfl", test_builtin_group_guid_rfl, lang_setup, lang_teardown }, { "lang/builtin/group_empty_list", test_builtin_group_empty_and_list, lang_setup, lang_teardown }, { "lang/select/derived_key_file_chunks", test_select_derived_key_file_chunks, lang_setup, lang_teardown }, + { "lang/select/releases_input_table", test_select_releases_input_table, lang_setup, lang_teardown }, { "lang/temporal/extract_builtins_fn", test_temporal_extract_builtins_fn, lang_setup, lang_teardown }, { "lang/temporal/extract_time_atom", test_temporal_extract_time_atom, lang_setup, lang_teardown }, { "lang/temporal/extract_time_vector", test_temporal_extract_time_vector, lang_setup, lang_teardown }, From 2ccebde24b0c9d3614b7b649b2b631b34689d5d0 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Mon, 21 Sep 2026 11:26:16 +0300 Subject: [PATCH 09/29] fix(exec): the reduction case owns its input too The same borrowed-query-table guard sat under the reductions; no child evaluates to the query table there today, so nothing leaked, but the premise is the one the sort, window and limit cases just dropped. Co-Authored-By: Claude Fable 5.1 --- src/ops/exec.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ops/exec.c b/src/ops/exec.c index d762388dc..de07dbbe4 100644 --- a/src/ops/exec.c +++ b/src/ops/exec.c @@ -2025,7 +2025,9 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { if (!input || RAY_IS_ERR(input)) return input; /* Compact lazy selection before reducing — filters may have * set g->selection without materializing a compacted table. */ - bool own_input = (input != g->table); + /* Owned, like every exec_node result (see OP_SORT); no child + * evaluates to a borrowed query table. */ + bool own_input = true; if (g->selection && input->type == RAY_TABLE) { ray_t* compacted = sel_compact(g, input, g->selection, NULL, 0); if (own_input) ray_release(input); From a7b9b3991bcee6f4a24c2cf46e52b6dc5ef83176 Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 21 Sep 2026 15:45:51 +0200 Subject: [PATCH 10/29] perf(pool): wake only the workers a dispatch can keep busy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ray_pool_dispatch and ray_pool_dispatch_n signalled the whole pool on every dispatch, however narrow the window. The main thread participates as worker 0, so at most n_tasks-1 helpers can ever claim anything; the surplus threads woke, raced to an already-drained window, and went straight back to the semaphore. On a dispatch narrower than the machine that is pure overhead — a partition-parallel step over three partitions woke every core on the box to run two tasks. Signal min(n_tasks-1, n_workers) instead. Signalling FEWER is safe: completion is governed by the `pending` spin-wait, never by the signal count, so an unsignalled worker simply stays asleep, and under-signalling cannot produce the surplus-signal problem between consecutive dispatches that the spin-wait exists to avoid. Measured (10M-row ClickBench, 43 queries x 3, splayed): sum of per-query hot times 5690.7 ms -> 5667.3 ms (-0.4%, within noise), user CPU 55.1 s -> 54.8 s. So this is waste removal rather than a speedup on workloads whose dispatches are already wider than the pool. Not a fix for #599. That report's shape — a 130k-row join probe, which splits into 16 tasks against 8 workers — is unaffected, because the clamp lands on the same worker count it already used (measured: 5.19 s -> 5.18 s of CPU, unchanged). The investigation there points at the pool defaulting to logical rather than physical cores; that is a separate change with its own benchmark trade and is filed on its own. test_pool.c gains pool/dispatch_narrow, which is the case the existing coverage missed: dispatch_n_small uses 4 tasks on a 2-worker pool, so the clamp never binds. The new test drives windows of 1..4 tasks on a 4-worker pool, then alternates narrow and wide windows 25 times over the same pool, asserting exact task and element counts throughout — the two risks the change introduces are a task nobody claims and signal accounting that drifts across dispatches and starves a later wide window. --- src/core/pool.c | 24 ++++++++++++++++++---- test/test_pool.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 4 deletions(-) diff --git a/src/core/pool.c b/src/core/pool.c index 0b81070ab..c3cac8002 100644 --- a/src/core/pool.c +++ b/src/core/pool.c @@ -340,8 +340,16 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, const bool prog = ray_qstats_mode() & RAY_QS_PROGRESS; if (prog) ray_progress_dispatch_begin((uint64_t)total_elems); - /* Wake worker threads */ - for (uint32_t i = 0; i < pool->n_workers; i++) { + /* Wake worker threads — only as many as have something to claim. Main + * participates as worker 0, so at most n_tasks-1 helpers can be useful; + * signalling the whole pool woke threads that raced to an already-drained + * window and went straight back to sleep, which is pure overhead on any + * dispatch narrower than the machine (#599). Signalling FEWER is safe: + * completion is governed by the `pending` spin-wait below, never by the + * signal count, so an unsignalled worker simply stays asleep. */ + uint32_t wake = n_tasks > 0 ? n_tasks - 1 : 0; + if (wake > pool->n_workers) wake = pool->n_workers; + for (uint32_t i = 0; i < wake; i++) { ray_sem_signal(&pool->work_ready); } @@ -413,8 +421,16 @@ static void dispatch_n_round(ray_pool_t* pool, ray_pool_fn fn, void* ctx, const bool prog = ray_qstats_mode() & RAY_QS_PROGRESS; if (prog) ray_progress_dispatch_begin((uint64_t)n_tasks); - /* Wake worker threads */ - for (uint32_t i = 0; i < pool->n_workers; i++) { + /* Wake worker threads — only as many as have something to claim. Main + * participates as worker 0, so at most n_tasks-1 helpers can be useful; + * signalling the whole pool woke threads that raced to an already-drained + * window and went straight back to sleep, which is pure overhead on any + * dispatch narrower than the machine (#599). Signalling FEWER is safe: + * completion is governed by the `pending` spin-wait below, never by the + * signal count, so an unsignalled worker simply stays asleep. */ + uint32_t wake = n_tasks > 0 ? n_tasks - 1 : 0; + if (wake > pool->n_workers) wake = pool->n_workers; + for (uint32_t i = 0; i < wake; i++) { ray_sem_signal(&pool->work_ready); } diff --git a/test/test_pool.c b/test/test_pool.c index 7e2f177de..8eb499a1e 100644 --- a/test/test_pool.c +++ b/test/test_pool.c @@ -462,6 +462,57 @@ static test_result_t test_dispatch_small(void) { * spin-wait for completion). * -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- + * Test: a dispatch NARROWER than the pool still runs every task, and leaves + * the pool fully usable for a later wide one (#599). + * + * ray_pool_dispatch/_n now signal only min(n_tasks-1, n_workers) workers + * instead of the whole pool, so the under-signalled workers stay asleep. The + * risks that buys are (a) a task nobody claims and (b) signal accounting that + * drifts across dispatches, starving a later wide window. Alternating narrow + * and wide dispatches over one pool catches both: every window is verified for + * exact task and element counts. + * -------------------------------------------------------------------------- */ +static test_result_t test_dispatch_narrower_than_pool(void) { + ray_heap_init(); + + ray_pool_t pool; + TEST_ASSERT_EQ_I(ray_pool_create(&pool, 4), RAY_OK); + + /* n_tasks below the worker count: 1 wakes nobody, 2 wakes one, etc. */ + for (uint32_t n = 1; n <= 4; n++) { + pool_count_ctx_t ctx = {0}; + ray_pool_dispatch_n(&pool, pool_count_fn, &ctx, n); + TEST_ASSERT_EQ_I(atomic_load(&ctx.calls), n); + TEST_ASSERT_EQ_I(atomic_load(&ctx.elem_sum), n); + } + + /* The element form, sized to a single task. */ + { + pool_count_ctx_t ctx = {0}; + ray_pool_dispatch(&pool, pool_count_fn, &ctx, 1); + TEST_ASSERT_EQ_I(atomic_load(&ctx.calls), 1); + TEST_ASSERT_EQ_I(atomic_load(&ctx.elem_sum), 1); + } + + /* Alternating narrow/wide over the same pool: a wide window must still be + * fully served after windows that signalled fewer workers than exist. */ + for (int rep = 0; rep < 25; rep++) { + pool_count_ctx_t narrow = {0}; + ray_pool_dispatch_n(&pool, pool_count_fn, &narrow, 1); + TEST_ASSERT_EQ_I(atomic_load(&narrow.calls), 1); + + pool_count_ctx_t wide = {0}; + ray_pool_dispatch_n(&pool, pool_count_fn, &wide, 32); + TEST_ASSERT_EQ_I(atomic_load(&wide.calls), 32); + TEST_ASSERT_EQ_I(atomic_load(&wide.elem_sum), 32); + } + + ray_pool_free(&pool); + ray_heap_destroy(); + PASS(); +} + static test_result_t test_dispatch_n_small(void) { ray_heap_init(); @@ -1357,6 +1408,7 @@ const test_entry_t pool_entries[] = { { "pool/dispatch_zero_elems", test_dispatch_zero_elems, NULL, NULL }, { "pool/dispatch_small", test_dispatch_small, NULL, NULL }, { "pool/dispatch_n_small", test_dispatch_n_small, NULL, NULL }, + { "pool/dispatch_narrow", test_dispatch_narrower_than_pool, NULL, NULL }, { "pool/dispatch_n_ring_grow", test_dispatch_n_ring_growth, NULL, NULL }, { "pool/dispatch_ring_grow", test_dispatch_ring_growth, NULL, NULL }, { "pool/dispatch_n_cancelled", test_dispatch_n_cancelled, NULL, NULL }, From 08c5918cd7f81c1ef3c8890e18d484d2d99aaef7 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Tue, 22 Sep 2026 14:58:56 +0300 Subject: [PATCH 11/29] build: Windows (MSYS2 CLANG64/MINGW64) toolchain in the Makefile Detect Windows via $(OS) or uname (MSYS2's make hides $(OS)), link Winsock and a statically linked winpthreads, build with 64-bit off_t (_FILE_OFFSET_BITS=64) and an 8 MiB stack like a Linux main thread. Co-Authored-By: Claude Opus 5 (1M context) --- Makefile | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index aa6b666e9..f6c170f30 100644 --- a/Makefile +++ b/Makefile @@ -81,7 +81,25 @@ COVERAGE_CFLAGS = -fPIC $(WARNS) -std=$(STD) -g -O0 -march=$(RAY_MARCH) -DDEBUG -fno-omit-frame-pointer -fprofile-instr-generate -fcoverage-mapping COVERAGE_LDFLAGS = -fprofile-instr-generate -fcoverage-mapping -ifeq ($(UNAME_S),Linux) +# Windows: MSYS2 CLANG64/MINGW64 toolchain (x86_64-w64-windows-gnu). MSYS2's +# own make hides $(OS), so also match `uname -s` (MINGW64_NT-*, CLANG64_NT-*, +# MSYS_NT-*); a native make started from PowerShell/cmd sees OS=Windows_NT. +RAY_WINDOWS := $(if $(filter Windows_NT,$(OS))$(findstring _NT-,$(UNAME_S)),1,) + +ifeq ($(RAY_WINDOWS),1) + # 64-bit off_t / struct stat.st_size: MinGW defaults both to 32 bits, which + # silently truncates sizes of files over 2 GiB (stat, lseek, ftruncate). + DEFS += -D_FILE_OFFSET_BITS=64 + # --stack: 8 MiB like a Linux main thread (the Windows default is 1 MiB, + # too little for deep DAG/eval recursion). CreateThread(size 0) inherits + # it too, so pool workers get the same. winpthreads (sched_yield, + # clock_gettime) is linked statically so the binary needs no MSYS2 DLL; the + # UCRT it also uses ships with Windows 10+. + LIBS = -lws2_32 -lmswsock -lkernel32 -ladvapi32 \ + -Wl,-Bstatic -lpthread -Wl,-Bdynamic \ + -Wl,--stack,8388608 + RELEASE_LDFLAGS = -Wl,--gc-sections +else ifeq ($(UNAME_S),Linux) LIBS = -lm -lpthread RELEASE_LDFLAGS = -Wl,--gc-sections -Wl,--as-needed else From 5ee60ea89b0702c3d708256f5d4eaf4b6b7bcd5e Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Tue, 22 Sep 2026 14:58:56 +0300 Subject: [PATCH 12/29] feat(core): WSAPoll event loop for Windows Replace the IOCP stub with a readiness-based loop that mirrors the epoll backend's dispatch order, so the selector state machine is identical on every platform. stdin (console or pipe) is not a socket, so RAY_SEL_STDIN selectors are probed directly and the socket wait is sliced while one is registered. Co-Authored-By: Claude Opus 5 (1M context) --- src/core/iocp.c | 431 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 416 insertions(+), 15 deletions(-) diff --git a/src/core/iocp.c b/src/core/iocp.c index 636c3fed1..dd75fd8f3 100644 --- a/src/core/iocp.c +++ b/src/core/iocp.c @@ -21,36 +21,181 @@ * SOFTWARE. */ +#include "core/platform.h" + #if defined(RAY_OS_WINDOWS) +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#include + #include "core/poll.h" -#include +#include "core/mcast.h" +#include "core/timer.h" +#include "mem/sys.h" +#include "mem/heap.h" /* idle decay: bound the wait, sweep after wakeup */ + +/* Windows event loop. + * + * Readiness-based, like the epoll and kqueue backends, so the selector + * state machine (rx fill -> read_fn -> data_fn, tx flush) is the same on + * every platform. Sockets are waited on with WSAPoll. Standard input is + * not a socket and WSAPoll cannot watch it, so RAY_SEL_STDIN selectors are + * probed directly (console input queue, bytes in a pipe) and the socket + * wait is cut into short slices while one is registered. + * + * WSAPoll keeps no kernel-side registration, so the wait set is rebuilt + * from poll->sels on every pass: register/deregister and tx request/cancel + * need no OS call, and a selector's write interest simply follows whether + * it has a pending tx buffer. */ + +#define RAY_POLL_INITIAL_CAP 16 +#define RAY_POLL_STDIN_SLICE_MS 10 + +enum { EV_IN = 1, EV_OUT = 2, EV_HUP = 4 }; + +/* ===== stdin readiness ===== */ + +/* Would a read of `fd` return now (data or EOF) instead of blocking? */ +static int stdin_events(int64_t fd) +{ + HANDLE h = (HANDLE)_get_osfhandle((int)fd); + if (h == INVALID_HANDLE_VALUE) return EV_HUP; + + switch (GetFileType(h)) { + case FILE_TYPE_CHAR: { + DWORD mode; + if (!GetConsoleMode(h, &mode)) return EV_IN; /* NUL device: never blocks */ + for (;;) { + INPUT_RECORD rec; + DWORD n = 0; + if (!PeekConsoleInputW(h, &rec, 1, &n)) return EV_HUP; + if (n == 0) return 0; + if (rec.EventType == KEY_EVENT && rec.Event.KeyEvent.bKeyDown && + rec.Event.KeyEvent.uChar.UnicodeChar != 0) + return EV_IN; + /* Focus, mouse, resize and key-up records never yield a byte to + * ReadFile: drop them, or a "ready" console would make the + * reader block in ReadFile until the next real keystroke. */ + if (!ReadConsoleInputW(h, &rec, 1, &n)) return EV_HUP; + } + } + case FILE_TYPE_PIPE: { + DWORD avail = 0; + if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) + return EV_IN | EV_HUP; /* writer gone: the read returns EOF */ + return avail ? EV_IN : 0; + } + default: + return EV_IN; /* disk file: reads never block */ + } +} -/* Windows IOCP implementation — stub for now. - * Full IOCP support is deferred to a future release. */ +/* ===== Lifecycle ===== */ ray_poll_t* ray_poll_create(void) { - fprintf(stderr, "ray_poll_create: IOCP not yet implemented\n"); - return NULL; + WSADATA wsa; + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return NULL; + + ray_poll_t* poll = (ray_poll_t*)ray_sys_alloc(sizeof(ray_poll_t)); + if (!poll) return NULL; + + memset(poll, 0, sizeof(*poll)); + poll->fd = -1; /* no kernel object behind a WSAPoll loop */ + poll->code = -1; + poll->sel_cap = RAY_POLL_INITIAL_CAP; + poll->sels = (ray_selector_t**)ray_sys_alloc( + poll->sel_cap * sizeof(ray_selector_t*)); + if (!poll->sels) { + ray_sys_free(poll); + return NULL; + } + memset(poll->sels, 0, poll->sel_cap * sizeof(ray_selector_t*)); + return poll; } void ray_poll_destroy(ray_poll_t* poll) { - (void)poll; + if (!poll) return; + + for (uint32_t i = 0; i < poll->n_sels; i++) { + ray_selector_t* sel = poll->sels[i]; + if (!sel) continue; + if (sel->close_fn) sel->close_fn(poll, sel); + if (sel->rx.buf) ray_poll_buf_free(sel->rx.buf); + ray_poll_buf_free(sel->tx.buf); + ray_sys_free(sel); + poll->sels[i] = NULL; + } + + if (poll->sels) ray_sys_free(poll->sels); + if (poll->timers) { + ray_timers_destroy((ray_timers_t*)poll->timers); + poll->timers = NULL; + } + if (poll->mcast) { + ray_mcast_destroy((ray_mcast_t*)poll->mcast); + poll->mcast = NULL; + } + ray_sys_free(poll); } +/* ===== Registration ===== */ + int64_t ray_poll_register(ray_poll_t* poll, ray_poll_reg_t* reg) { - (void)poll; (void)reg; - return -1; -} + if (!poll || !reg) return -1; -void ray_poll_deregister(ray_poll_t* poll, int64_t id) -{ - (void)poll; (void)id; + /* Find free slot or grow */ + int64_t id = -1; + for (uint32_t i = 0; i < poll->n_sels; i++) { + if (!poll->sels[i]) { id = (int64_t)i; break; } + } + if (id < 0) { + if (poll->n_sels >= poll->sel_cap) { + uint32_t new_cap = poll->sel_cap * 2; + ray_selector_t** ns = (ray_selector_t**)ray_sys_alloc( + new_cap * sizeof(ray_selector_t*)); + if (!ns) return -1; + memcpy(ns, poll->sels, poll->n_sels * sizeof(ray_selector_t*)); + memset(ns + poll->n_sels, 0, + (new_cap - poll->n_sels) * sizeof(ray_selector_t*)); + ray_sys_free(poll->sels); + poll->sels = ns; + poll->sel_cap = new_cap; + } + id = (int64_t)poll->n_sels; + poll->n_sels++; + } + + ray_selector_t* sel = (ray_selector_t*)ray_sys_alloc(sizeof(ray_selector_t)); + if (!sel) return -1; + memset(sel, 0, sizeof(*sel)); + + sel->fd = reg->fd; + sel->id = id; + sel->type = reg->type; + sel->data = reg->data; + sel->open_fn = reg->open_fn; + sel->close_fn = reg->close_fn; + sel->error_fn = reg->error_fn; + sel->data_fn = reg->data_fn; + sel->rx.recv_fn = reg->recv_fn; + sel->rx.read_fn = reg->read_fn; + sel->tx.send_fn = reg->send_fn; + + poll->sels[id] = sel; + poll->n_live++; + if (sel->open_fn) sel->open_fn(poll, sel); + return id; } +/* Write interest is derived from sel->tx.buf when the wait set is built. */ void ray_poll_tx_request(ray_poll_t* poll, ray_selector_t* sel) { (void)poll; (void)sel; @@ -61,10 +206,266 @@ void ray_poll_tx_cancel(ray_poll_t* poll, ray_selector_t* sel) (void)poll; (void)sel; } +void ray_poll_deregister(ray_poll_t* poll, int64_t id) +{ + if (!poll || id < 0 || (uint32_t)id >= poll->n_sels) return; + ray_selector_t* sel = poll->sels[id]; + if (!sel) return; + + if (sel->close_fn) sel->close_fn(poll, sel); + if (sel->rx.buf) ray_poll_buf_free(sel->rx.buf); + ray_poll_buf_free(sel->tx.buf); + ray_sys_free(sel); + poll->sels[id] = NULL; + if (poll->n_live > 0) poll->n_live--; +} + +/* ===== Event dispatch (same order and rules as the epoll backend) ===== */ + +static void poll_dispatch(ray_poll_t* poll, uint64_t eid, int events) +{ + ray_selector_t* sel = NULL; + if (eid < poll->n_sels) + sel = poll->sels[eid]; + if (!sel) return; + + /* Process readable data first — even if hangup is also set. A client + * may send a message and close; both arrive in the same wakeup. */ + if (events & EV_IN) { + /* Loop: read data -> call read_fn -> if state advanced, read more. + * Handles multi-phase protocols (handshake -> header -> payload) + * arriving in a single wakeup. */ + for (;;) { + if (sel->rx.recv_fn && sel->rx.buf) { + while (sel->rx.buf->offset < sel->rx.buf->size) { + int64_t nr = sel->rx.recv_fn( + sel->fd, + sel->rx.buf->data + sel->rx.buf->offset, + sel->rx.buf->size - sel->rx.buf->offset); + if (nr <= 0) { + if (nr < 0 && errno == EINTR) continue; + if (nr < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) + break; + /* Error or peer closed mid-read */ + if (sel->error_fn) + sel->error_fn(poll, sel); + else + ray_poll_deregister(poll, sel->id); + return; + } + sel->rx.buf->offset += nr; + } + } + + /* Not enough data for current phase */ + if (sel->rx.buf && sel->rx.buf->offset < sel->rx.buf->size) + break; + + /* Call read_fn — may advance state and request new buffer */ + if (!sel->rx.read_fn) break; + ray_t* obj = sel->rx.read_fn(poll, sel); + + /* Re-validate: read_fn may have deregistered this selector */ + if (eid >= poll->n_sels || !poll->sels[eid]) return; + sel = poll->sels[eid]; + + if (obj && sel->data_fn) + sel->data_fn(poll, sel, obj); + + if (eid >= poll->n_sels || !poll->sels[eid]) return; + sel = poll->sels[eid]; + + /* If no rx buffer (state machine done or not set), stop */ + if (!sel->rx.buf) break; + /* If buffer already has enough data for next phase, loop */ + if (sel->rx.buf->offset >= sel->rx.buf->size) continue; + /* Otherwise try reading more (may EAGAIN -> break) */ + } + } + + if (events & EV_OUT) { + if (eid >= poll->n_sels || !poll->sels[eid]) return; + sel = poll->sels[eid]; + if (sel->tx.buf && ray_poll_tx_flush(poll, sel) < 0) { + if (eid < poll->n_sels && poll->sels[eid]) { + sel = poll->sels[eid]; + if (sel->error_fn) + sel->error_fn(poll, sel); + else + ray_poll_deregister(poll, sel->id); + } + return; + } + } + + /* Error / hangup — after data is drained */ + if (events & EV_HUP) { + if (eid < poll->n_sels && poll->sels[eid]) { + sel = poll->sels[eid]; + if (sel->error_fn) + sel->error_fn(poll, sel); + else + ray_poll_deregister(poll, sel->id); + } + } +} + +/* ===== Run loop ===== */ + int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) { - (void)poll; (void)timeout_ms; - return -1; + if (!poll) return -1; + + bool bounded = timeout_ms >= 0; + int64_t end_ms = bounded ? ray_time_now_ms() + timeout_ms : INT64_MAX; + + while (poll->code < 0) { + int wait_ms = -1; + if (bounded) { + int64_t remaining = end_ms - ray_time_now_ms(); + if (remaining < 0) remaining = 0; + if (remaining > INT_MAX) remaining = INT_MAX; + wait_ms = (int)remaining; + } + + /* Nothing registered and nothing scheduled: an unbounded loop + * would block here forever. Return instead, so a process that + * stayed only for its timers can end once they are spent. */ + if (!bounded && ray_poll_idle(poll)) return 0; + + if (poll->timers) { + int64_t deadline = ray_timers_next_deadline_ms( + (ray_timers_t*)poll->timers); + if (deadline != INT64_MAX) { + int64_t delta = deadline - ray_time_now_ms(); + if (delta < 0) delta = 0; + if (delta > INT_MAX) delta = INT_MAX; + if (wait_ms < 0 || delta < wait_ms) + wait_ms = (int)delta; + } + } + + /* Idle allocator decay bounds an unbounded wait, exactly as in the + * epoll backend (see the comment there). */ + { + int64_t decay = bounded ? -1 : ray_heap_decay_due_ms(); + if (decay >= 0) { + if (decay > INT_MAX) decay = INT_MAX; + if (wait_ms < 0 || decay < wait_ms) wait_ms = (int)decay; + } + } + + /* Build this pass's wait set: sockets for WSAPoll, stdin probed. */ + uint32_t cap = poll->n_sels ? poll->n_sels : 1; + WSAPOLLFD* pfds = (WSAPOLLFD*)ray_sys_alloc(cap * sizeof(WSAPOLLFD)); + uint32_t* pids = (uint32_t*)ray_sys_alloc(cap * sizeof(uint32_t)); + uint32_t* sids = (uint32_t*)ray_sys_alloc(cap * sizeof(uint32_t)); + int* sevs = (int*)ray_sys_alloc(cap * sizeof(int)); + if (!pfds || !pids || !sids || !sevs) { + if (pfds) ray_sys_free(pfds); + if (pids) ray_sys_free(pids); + if (sids) ray_sys_free(sids); + if (sevs) ray_sys_free(sevs); + return -1; + } + + uint32_t nfds = 0, nstd = 0; + for (uint32_t i = 0; i < poll->n_sels; i++) { + ray_selector_t* sel = poll->sels[i]; + if (!sel) continue; + if (sel->type == RAY_SEL_STDIN) { + sids[nstd] = i; + sevs[nstd] = 0; + nstd++; + continue; + } + pfds[nfds].fd = (SOCKET)sel->fd; + pfds[nfds].events = POLLRDNORM | (sel->tx.buf ? POLLWRNORM : 0); + pfds[nfds].revents = 0; + pids[nfds] = i; + nfds++; + } + + /* Wait. With stdin registered the socket wait is sliced so the + * console/pipe is re-probed every RAY_POLL_STDIN_SLICE_MS. */ + int64_t wait_end = wait_ms < 0 ? INT64_MAX : ray_time_now_ms() + wait_ms; + int n = 0; + bool failed = false; + for (;;) { + bool std_ready = false; + for (uint32_t k = 0; k < nstd; k++) { + sevs[k] = stdin_events(poll->sels[sids[k]]->fd); + if (sevs[k]) std_ready = true; + } + + int remain = -1; + if (wait_end != INT64_MAX) { + int64_t r = wait_end - ray_time_now_ms(); + remain = r < 0 ? 0 : (r > INT_MAX ? INT_MAX : (int)r); + } + int slice = std_ready ? 0 : remain; + if (nstd && !std_ready && + (slice < 0 || slice > RAY_POLL_STDIN_SLICE_MS)) + slice = RAY_POLL_STDIN_SLICE_MS; + + if (nfds) { + n = WSAPoll(pfds, nfds, slice); + if (n == SOCKET_ERROR) { + if (WSAGetLastError() == WSAEINTR) continue; + failed = true; + break; + } + } else if (slice > 0) { + Sleep((DWORD)slice); + } else if (slice < 0) { + /* Only reachable with a live selector that is neither a + * socket nor stdin; nothing can wake us, so just yield. */ + Sleep(RAY_POLL_STDIN_SLICE_MS); + } + + if (n > 0 || std_ready) break; + if (remain == 0) break; /* deadline reached */ + if (!nstd && slice == remain) break; /* whole wait elapsed */ + } + + if (!failed) { + for (uint32_t j = 0; j < nfds && n > 0; j++) { + short re = pfds[j].revents; + if (!re) continue; + int ev = 0; + if (re & (POLLRDNORM | POLLRDBAND)) ev |= EV_IN; + if (re & POLLWRNORM) ev |= EV_OUT; + if (re & (POLLERR | POLLHUP | POLLNVAL)) ev |= EV_HUP; + /* The slot may have been reused by an earlier dispatch in + * this pass (deregister + accept): only act on the socket + * the event was reported for. */ + ray_selector_t* sel = pids[j] < poll->n_sels ? poll->sels[pids[j]] : NULL; + if (!sel || (SOCKET)sel->fd != pfds[j].fd) continue; + poll_dispatch(poll, pids[j], ev); + } + for (uint32_t k = 0; k < nstd; k++) { + if (!sevs[k]) continue; + ray_selector_t* sel = sids[k] < poll->n_sels ? poll->sels[sids[k]] : NULL; + if (!sel || sel->type != RAY_SEL_STDIN) continue; + poll_dispatch(poll, sids[k], sevs[k]); + } + } + + ray_sys_free(pfds); + ray_sys_free(pids); + ray_sys_free(sids); + ray_sys_free(sevs); + if (failed) return -1; + + if (poll->timers) { + if (ray_timers_fire_expired((ray_timers_t*)poll->timers) > 0) + ray_heap_note_activity(); + } + ray_heap_decay(); + if (bounded) break; + } + + return poll->code >= 0 ? poll->code : 0; } int64_t ray_poll_run(ray_poll_t* poll) @@ -72,4 +473,4 @@ int64_t ray_poll_run(ray_poll_t* poll) return ray_poll_run_for(poll, -1); } -#endif /* _WIN32 */ +#endif /* RAY_OS_WINDOWS */ From 7cb12aff93839c848f89eb30fc72a281f017304b Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Tue, 22 Sep 2026 14:58:56 +0300 Subject: [PATCH 13/29] fix(net): Winsock errno mapping, exclusive bind and IPC on Windows - mirror WSAGetLastError()/SO_ERROR into errno for send/recv/connect/ accept/bind/listen: callers branch on EAGAIN/ECONNREFUSED; - ipc_send_fn always overwrites errno, so a stale EAGAIN can no longer park a frame on a dead socket; - SO_EXCLUSIVEADDRUSE instead of SO_REUSEADDR (which lets a bind steal a port that is in use); - WSAStartup at load time; sock.h pulls in platform.h; - verbose IPC capture uses a temp file that works without admin rights; - the SIGURG out-of-band cancel stays POSIX-only. Co-Authored-By: Claude Opus 5 (1M context) --- src/core/ipc.c | 27 +++++++++++++++- src/core/sock.c | 84 ++++++++++++++++++++++++++++++++++++++++++++++--- src/core/sock.h | 2 +- 3 files changed, 107 insertions(+), 6 deletions(-) diff --git a/src/core/ipc.c b/src/core/ipc.c index 5143b5ce6..c25935101 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -39,6 +39,7 @@ #ifdef RAY_OS_WINDOWS #define WIN32_LEAN_AND_MEAN + #include /* dup, dup2, close */ #include #include #else @@ -719,13 +720,31 @@ static ray_t* eval_payload_core(uint8_t* payload, size_t payload_len, * to fail the whole request because /tmp is full. The captured * string is then empty, and the response shape is still the 2-elem * list — clients can rely on that invariant. */ +#ifdef RAY_OS_WINDOWS +/* MSVCRT's tmpfile() creates its file in the drive root (admin-only on a + * stock system); use the user's temp directory, deleted on close ("D"). + * With no TMP/TEMP/USERPROFILE in the environment GetTempPath falls back + * to the (unwritable) Windows directory, so retry in the working dir. */ +static FILE* ipc_tmpfile(void) +{ + char dir[MAX_PATH + 1], path[MAX_PATH + 1]; + DWORD n = GetTempPathA(sizeof(dir), dir); + if (n == 0 || n > sizeof(dir) || !GetTempFileNameA(dir, "ray", 0, path)) { + if (!GetTempFileNameA(".", "ray", 0, path)) return NULL; + } + return fopen(path, "w+bD"); +} +#else +#define ipc_tmpfile() tmpfile() +#endif + static ray_t* eval_payload(uint8_t* payload, size_t payload_len, ray_ipc_header_t* hdr) { if (!(hdr->flags & RAY_IPC_FLAG_VERBOSE)) return eval_payload_core(payload, payload_len, hdr); - FILE* cap = tmpfile(); + FILE* cap = ipc_tmpfile(); int saved_out = -1, saved_err = -1; bool capturing = false; @@ -831,9 +850,13 @@ static int64_t ipc_send_fn(int64_t fd, uint8_t* buf, int64_t len) #ifdef RAY_OS_WINDOWS int n = send((ray_sock_t)fd, (const char*)buf, (int)len, 0); if (n < 0) { + /* Always overwrite errno: callers treat EAGAIN as "queue and retry", + * so a stale EAGAIN left over from an earlier call would turn a dead + * socket into a silently parked frame. */ int e = WSAGetLastError(); if (e == WSAEWOULDBLOCK) errno = EAGAIN; else if (e == WSAEINTR) errno = EINTR; + else errno = EIO; } return n; #else @@ -855,6 +878,7 @@ static int64_t ipc_send_fn(int64_t fd, uint8_t* buf, int64_t len) * ray_request_interrupt(). */ static volatile sig_atomic_t g_ipc_active_fd = -1; +#ifndef RAY_OS_WINDOWS /* no SIGURG on Windows: OOB cancel is POSIX-only */ static void ipc_sigurg_handler(int sig) { (void)sig; @@ -867,6 +891,7 @@ static void ipc_sigurg_handler(int sig) if (ray_sock_take_oob((ray_sock_t)fd)) ray_request_interrupt(); } +#endif static void ipc_install_oob_cancel(void) { diff --git a/src/core/sock.c b/src/core/sock.c index 750af93a2..18f0c502c 100644 --- a/src/core/sock.c +++ b/src/core/sock.c @@ -21,7 +21,7 @@ * SOFTWARE. */ -#ifndef RAY_OS_WINDOWS +#ifndef _WIN32 #define _GNU_SOURCE #endif @@ -48,6 +48,44 @@ /* ===== Socket Implementation ===== */ +#ifdef RAY_OS_WINDOWS +/* Winsock must be initialised before the process's first socket call; do it + * at load time so no entry point (listen, connect, a bare client) can miss + * it. Never paired with WSACleanup: process exit releases it. */ +__attribute__((constructor)) static void sock_win_startup(void) +{ + WSADATA wsa; + (void)WSAStartup(MAKEWORD(2, 2), &wsa); +} + +/* Winsock reports failures through WSAGetLastError(), never errno. The + * callers (poll loop, IPC) branch on errno == EINTR / EAGAIN, so mirror the + * Winsock code into errno after every failed socket call (or a code taken + * from SO_ERROR). */ +static void sock_win_errno_code(int code) +{ + switch (code) { + case WSAEWOULDBLOCK: errno = EAGAIN; break; + case WSAEINTR: errno = EINTR; break; + case WSAEINPROGRESS: errno = EINPROGRESS; break; + case WSAETIMEDOUT: errno = ETIMEDOUT; break; + case WSAECONNRESET: errno = ECONNRESET; break; + case WSAECONNABORTED: errno = ECONNABORTED; break; + case WSAECONNREFUSED: errno = ECONNREFUSED; break; + case WSAENOTCONN: errno = ENOTCONN; break; + case WSAENOTSOCK: errno = ENOTSOCK; break; + case WSAEADDRINUSE: errno = EADDRINUSE; break; + case WSAEINVAL: errno = EINVAL; break; + default: errno = EIO; break; + } +} + +static void sock_win_errno(void) +{ + sock_win_errno_code(WSAGetLastError()); +} +#endif + ray_sock_t ray_sock_listen_at(const char* host, uint16_t port) { /* NULL/empty host keeps the historical INADDR_ANY bind. A host that @@ -68,7 +106,15 @@ ray_sock_t ray_sock_listen_at(const char* host, uint16_t port) if (fd == RAY_INVALID_SOCK) return RAY_INVALID_SOCK; int yes = 1; +#ifdef RAY_OS_WINDOWS + /* Windows SO_REUSEADDR lets a second socket bind a port another one is + * actively listening on (the bind "steals" it). The POSIX meaning — + * rebind right after a restart, but fail while the port is in use — is + * SO_EXCLUSIVEADDRUSE here (TIME_WAIT never blocks a Windows bind). */ + setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&yes, sizeof(yes)); +#else setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof(yes)); +#endif struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); @@ -77,10 +123,16 @@ ray_sock_t ray_sock_listen_at(const char* host, uint16_t port) addr.sin_port = htons(port); if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { +#ifdef RAY_OS_WINDOWS + sock_win_errno(); /* e.g. EADDRINUSE for a taken port */ +#endif ray_sock_close(fd); return RAY_INVALID_SOCK; } if (listen(fd, 128) < 0) { +#ifdef RAY_OS_WINDOWS + sock_win_errno(); +#endif ray_sock_close(fd); return RAY_INVALID_SOCK; } @@ -97,6 +149,9 @@ ray_sock_t ray_sock_accept(ray_sock_t srv) ray_sock_t fd; do { fd = (ray_sock_t)accept(srv, NULL, NULL); +#ifdef RAY_OS_WINDOWS + if (fd == RAY_INVALID_SOCK) sock_win_errno(); +#endif } while (fd == RAY_INVALID_SOCK && errno == EINTR); if (fd == RAY_INVALID_SOCK) return RAY_INVALID_SOCK; @@ -115,8 +170,13 @@ ray_sock_t ray_sock_accept(ray_sock_t srv) static int sock_connect_one(ray_sock_t fd, const struct sockaddr* addr, socklen_t addrlen, int timeout_ms) { - if (timeout_ms <= 0) - return connect(fd, addr, addrlen) < 0 ? -1 : 0; + if (timeout_ms <= 0) { + if (connect(fd, addr, addrlen) == 0) return 0; +#ifdef RAY_OS_WINDOWS + sock_win_errno(); /* callers tell refusal from other failures by errno */ +#endif + return -1; + } ray_sock_set_nonblocking(fd); int rc = connect(fd, addr, addrlen); @@ -124,6 +184,7 @@ static int sock_connect_one(ray_sock_t fd, const struct sockaddr* addr, #ifdef RAY_OS_WINDOWS int werr = WSAGetLastError(); int in_progress = (werr == WSAEWOULDBLOCK || werr == WSAEINPROGRESS); + if (!in_progress) sock_win_errno_code(werr); #else int in_progress = (errno == EINPROGRESS); #endif @@ -136,13 +197,22 @@ static int sock_connect_one(ray_sock_t fd, const struct sockaddr* addr, do { pr = poll(&pfd, 1, timeout_ms); } while (pr < 0 && errno == EINTR); #endif if (pr == 0) { errno = ETIMEDOUT; return -1; } - if (pr < 0) return -1; + if (pr < 0) { +#ifdef RAY_OS_WINDOWS + sock_win_errno(); +#endif + return -1; + } /* Writable: harvest the pending connect result via SO_ERROR. */ int soerr = 0; socklen_t soerr_len = sizeof(soerr); if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&soerr, &soerr_len) < 0 || soerr != 0) { +#ifdef RAY_OS_WINDOWS + if (soerr != 0) sock_win_errno_code(soerr); /* a WSAE* code */ +#else if (soerr != 0) errno = soerr; +#endif return -1; } } @@ -213,6 +283,7 @@ int64_t ray_sock_send(ray_sock_t s, const void* buf, size_t len) while (rem > 0) { #ifdef RAY_OS_WINDOWS int n = send(s, (const char*)p, (int)rem, 0); + if (n < 0) sock_win_errno(); #else ssize_t n = send(s, p, rem, MSG_NOSIGNAL); #endif @@ -221,7 +292,11 @@ int64_t ray_sock_send(ray_sock_t s, const void* buf, size_t len) if (errno == EAGAIN || errno == EWOULDBLOCK) { /* Wait for write-readiness before retry */ struct pollfd pfd = { .fd = s, .events = POLLOUT }; +#ifdef RAY_OS_WINDOWS + WSAPoll(&pfd, 1, -1); +#else poll(&pfd, 1, -1); +#endif continue; } return -1; @@ -237,6 +312,7 @@ int64_t ray_sock_recv(ray_sock_t s, void* buf, size_t len) for (;;) { #ifdef RAY_OS_WINDOWS int n = recv(s, (char*)buf, (int)len, 0); + if (n < 0) sock_win_errno(); #else ssize_t n = recv(s, buf, len, 0); #endif diff --git a/src/core/sock.h b/src/core/sock.h index e35e566c1..d400dbef6 100644 --- a/src/core/sock.h +++ b/src/core/sock.h @@ -24,7 +24,7 @@ #ifndef RAY_SOCK_H #define RAY_SOCK_H -#include +#include "core/platform.h" /* ===== Socket Abstraction ===== */ From 4a392b761cba159a3f4507adf46a07ece85eee47 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Tue, 22 Sep 2026 14:58:56 +0300 Subject: [PATCH 14/29] fix: Windows platform layer (file mapping, pools, crash report, paths) - ray_vm_unmap_file only unmaps at a view's own base: UnmapViewOfFile drops the whole view for an interior pointer, which freed columns that carry a passenger index (munmap is a no-op there); - ray_vm_alloc_aligned returns its own allocation base, so pools are really released by ray_vm_free; - ray_vm_map_fd_ro maps for real (CSV reads always failed with io); - crash report via SetUnhandledExceptionFilter; - heap: file-backed spill stays POSIX-only (docs/architecture/memory.md); - domain: realpath substitute; symfile paths compare case/separator- insensitively so one file never gets two domains; - aof/csr/hnsw: platform handle for fsync, portable ray_mkdir. Co-Authored-By: Claude Opus 5 (1M context) --- src/core/crash.c | 107 +++++++++++++++++++++++++++++++++----------- src/core/platform.c | 59 ++++++++++++++++++------ src/io/csv.c | 4 +- src/mem/heap.c | 36 +++++++++++++-- src/store/aof.c | 13 +++++- src/store/csr.c | 3 +- src/store/fileio.h | 5 ++- src/store/hnsw.c | 3 +- src/table/domain.c | 42 +++++++++++++++-- 9 files changed, 218 insertions(+), 54 deletions(-) diff --git a/src/core/crash.c b/src/core/crash.c index 17d644edb..76f894b2a 100644 --- a/src/core/crash.c +++ b/src/core/crash.c @@ -19,10 +19,13 @@ #include "core/crash.h" #include +#include #include #include -#if !defined(_WIN32) +#if defined(_WIN32) +#include +#else #include #endif @@ -42,7 +45,7 @@ static void cw(const char* s) { /* Write an unsigned value as 0x-prefixed hex. No libc formatting. * Routes through cw() so the write return value is handled (gcc's * warn_unused_result on write() is not silenced by a (void) cast). */ -static void cw_hex(unsigned long v) { +static void cw_hex(uint64_t v) { char buf[2 + 16 + 1]; static const char hexd[] = "0123456789abcdef"; buf[0] = '0'; buf[1] = 'x'; @@ -52,7 +55,8 @@ static void cw_hex(unsigned long v) { cw(buf); } -/* Write a small non-negative integer as decimal. */ +#if !defined(_WIN32) +/* Write a small non-negative integer as decimal (backtrace frame count). */ static void cw_int(int v) { if (v < 0) { cw("-"); v = -v; } char buf[16]; @@ -62,6 +66,75 @@ static void cw_int(int v) { while (v > 0 && i > 0) { buf[--i] = (char)('0' + v % 10); v /= 10; } cw(&buf[i]); } +#endif + +/* Banner precomputed at install time so the handler doesn't format it. */ +static char g_banner[128]; + +static void crash_banner_init(void) { + const char* v = +#ifdef RAYFORCE_VERSION + "rayforce " RAYFORCE_VERSION +#else + "rayforce" +#endif +#ifdef RAYFORCE_GIT_COMMIT + " (" RAYFORCE_GIT_COMMIT ")" +#endif + "\n"; + size_t vl = strlen(v); + if (vl >= sizeof(g_banner)) vl = sizeof(g_banner) - 1; + memcpy(g_banner, v, vl); + g_banner[vl] = '\0'; +} + +#if defined(_WIN32) + +/* ── Windows: structured exceptions ───────────────────────────────── */ + +static const char* exc_name(DWORD code) { + switch (code) { + case EXCEPTION_ACCESS_VIOLATION: return "EXCEPTION_ACCESS_VIOLATION"; + case EXCEPTION_STACK_OVERFLOW: return "EXCEPTION_STACK_OVERFLOW"; + case EXCEPTION_ILLEGAL_INSTRUCTION: return "EXCEPTION_ILLEGAL_INSTRUCTION"; + case EXCEPTION_INT_DIVIDE_BY_ZERO: return "EXCEPTION_INT_DIVIDE_BY_ZERO"; + case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED"; + case EXCEPTION_IN_PAGE_ERROR: return "EXCEPTION_IN_PAGE_ERROR"; + default: return "exception"; + } +} + +/* Top-level filter: runs only for exceptions nobody else handled. Report + * and let the default handling (WER / exit with the exception code) run, + * which keeps the process exit status meaningful to the orchestrator. */ +static LONG WINAPI crash_filter(EXCEPTION_POINTERS* ep) { + const EXCEPTION_RECORD* er = ep ? ep->ExceptionRecord : NULL; + cw("\n=== rayforce fatal "); + cw(er ? exc_name(er->ExceptionCode) : "exception"); + if (er) { + cw(" code "); cw_hex((uint64_t)er->ExceptionCode); + cw(" at "); cw_hex((uint64_t)(uintptr_t)er->ExceptionAddress); + if (er->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && + er->NumberParameters >= 2) { + cw(" fault addr "); + cw_hex((uint64_t)er->ExceptionInformation[1]); + } + } + cw(" ===\n"); + cw(g_banner); + return EXCEPTION_CONTINUE_SEARCH; +} + +void ray_crash_install(void) { + crash_banner_init(); + /* Reserve stack for the filter itself, so a stack-overflow exception + * can still be reported (the Windows analogue of sigaltstack). */ + ULONG guarantee = 64 * 1024; + (void)SetThreadStackGuarantee(&guarantee); + SetUnhandledExceptionFilter(crash_filter); +} + +#else /* POSIX */ static const char* sig_name(int sig) { switch (sig) { @@ -74,9 +147,6 @@ static const char* sig_name(int sig) { } } -/* Banner precomputed at install time so the handler doesn't format it. */ -static char g_banner[128]; - /* ── the handler ──────────────────────────────────────────────────── */ static void crash_handler(int sig, siginfo_t* info, void* ucontext) { @@ -84,11 +154,10 @@ static void crash_handler(int sig, siginfo_t* info, void* ucontext) { cw("\n=== rayforce fatal "); cw(sig_name(sig)); - if (info) { cw(" at fault addr "); cw_hex((unsigned long)info->si_addr); } + if (info) { cw(" at fault addr "); cw_hex((uint64_t)(uintptr_t)info->si_addr); } cw(" ===\n"); cw(g_banner); -#if !defined(_WIN32) void* frames[64]; int n = backtrace(frames, 64); /* backtrace_symbols_fd writes directly to the fd without allocating. */ @@ -96,7 +165,6 @@ static void crash_handler(int sig, siginfo_t* info, void* ucontext) { cw("=== end backtrace ("); cw_int(n); cw(" frames) ===\n"); -#endif /* Restore the default disposition and re-raise, so the process dies * from the original signal: this preserves the core dump and reports @@ -116,24 +184,8 @@ static void crash_handler(int sig, siginfo_t* info, void* ucontext) { static char g_altstack[RAY_CRASH_ALTSTACK_SZ]; void ray_crash_install(void) { -#if !defined(_WIN32) /* Precompute the version banner once (async-signal-safe reuse). */ - { - const char* v = -#ifdef RAYFORCE_VERSION - "rayforce " RAYFORCE_VERSION -#else - "rayforce" -#endif -#ifdef RAYFORCE_GIT_COMMIT - " (" RAYFORCE_GIT_COMMIT ")" -#endif - "\n"; - size_t vl = strlen(v); - if (vl >= sizeof(g_banner)) vl = sizeof(g_banner) - 1; - memcpy(g_banner, v, vl); - g_banner[vl] = '\0'; - } + crash_banner_init(); /* Warm up the unwinder: the first backtrace() may dlopen libgcc and * allocate, which must not happen inside the handler. */ @@ -157,5 +209,6 @@ void ray_crash_install(void) { static const int sigs[] = { SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGABRT }; for (size_t i = 0; i < sizeof(sigs) / sizeof(sigs[0]); i++) (void)sigaction(sigs[i], &sa, NULL); -#endif } + +#endif /* _WIN32 */ diff --git a/src/core/platform.c b/src/core/platform.c index 89852918a..bad99c91d 100644 --- a/src/core/platform.c +++ b/src/core/platform.c @@ -469,6 +469,7 @@ void ray_sem_signal(ray_sem_t* s) { #define WIN32_LEAN_AND_MEAN #endif #include +#include /* _get_osfhandle */ #include "mem/sys.h" /* -------------------------------------------------------------------------- @@ -518,13 +519,34 @@ void* ray_vm_map_file(const char* path, size_t* out_size) { void ray_vm_unmap_file(void* ptr, size_t size) { if (!ptr) return; - UnmapViewOfFile(ptr); + /* munmap releases exactly [ptr, ptr+size) and is a no-op (EINVAL) for an + * unaligned ptr — the heap relies on that when it frees a block living + * inside a column's mapping (a passenger index). UnmapViewOfFile instead + * drops the WHOLE view containing ptr, which would pull the column out + * from under its live references. So only unmap at the view's own base; + * an interior block goes away with the view. The byte accounting still + * follows the call, exactly as on POSIX. */ + MEMORY_BASIC_INFORMATION mbi; + if (VirtualQuery(ptr, &mbi, sizeof(mbi)) && mbi.AllocationBase == ptr) + UnmapViewOfFile(ptr); ray_sys_track_file_sub((int64_t)size); } -/* Windows never reaches the fd/mmap CSV path (#ifndef RAY_OS_WINDOWS), so this - * is an unused stub kept only for API completeness. */ -void* ray_vm_map_fd_ro(int fd, size_t size) { (void)fd; (void)size; return NULL; } +/* Read-only view of an open CRT descriptor (the CSV reader maps the file this + * way, then closes the fd). The view keeps the file alive on its own, so both + * the mapping handle and the caller's fd may be closed afterwards. */ +void* ray_vm_map_fd_ro(int fd, size_t size) { + if (size == 0) return NULL; + HANDLE hFile = (HANDLE)_get_osfhandle(fd); + if (hFile == INVALID_HANDLE_VALUE) return NULL; + HANDLE hMap = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL); + if (!hMap) return NULL; + void* p = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, size); + CloseHandle(hMap); + if (!p) return NULL; + ray_sys_track_file_add((int64_t)size); + return p; +} void ray_vm_advise_seq(void* ptr, size_t size) { /* PrefetchVirtualMemory is Win8.1+. Best-effort; ignore failure. */ @@ -546,16 +568,25 @@ void ray_vm_release_block(void* blk, size_t bsize, bool hugepage) { } void* ray_vm_alloc_aligned(size_t size, size_t alignment) { - /* Over-allocate, find aligned offset. Can't trim on Windows, so the - * pool header's vm_base field stores the original base for VirtualFree. */ - void* mem = VirtualAlloc(NULL, size + alignment, - MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - if (!mem) return NULL; - uintptr_t aligned = ((uintptr_t)mem + alignment - 1) & ~(alignment - 1); - /* Count the kept `size` to balance ray_vm_free(ptr, size); the alignment - * slack Windows cannot trim is left uncounted (parity with POSIX). */ - ray_sys_track_add((int64_t)size); - return (void*)aligned; + /* VirtualFree(MEM_RELEASE) only accepts the exact base VirtualAlloc + * returned, and a reservation cannot be trimmed. So find an aligned + * hole by reserving size+alignment, release it, and allocate exactly + * `size` at the aligned address inside it. Another thread may take the + * hole in between; retry a few times. The result is its own allocation + * base, so ray_vm_free(ptr, size) releases it like any other block. */ + for (int attempt = 0; attempt < 16; attempt++) { + void* probe = VirtualAlloc(NULL, size + alignment, MEM_RESERVE, PAGE_NOACCESS); + if (!probe) return NULL; + uintptr_t aligned = ((uintptr_t)probe + alignment - 1) & ~(alignment - 1); + VirtualFree(probe, 0, MEM_RELEASE); + void* p = VirtualAlloc((void*)aligned, size, + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (p) { + ray_sys_track_add((int64_t)size); + return p; + } + } + return NULL; } bool ray_vm_hugepage(void* ptr, size_t size) { (void)ptr; (void)size; return false; } diff --git a/src/io/csv.c b/src/io/csv.c index 269fb3daa..25302c1f9 100644 --- a/src/io/csv.c +++ b/src/io/csv.c @@ -65,8 +65,8 @@ #include #ifndef RAY_OS_WINDOWS #include -#endif #include +#endif /* -------------------------------------------------------------------------- * Constants @@ -104,7 +104,9 @@ static inline uint64_t csv_prog_at(size_t file_size, unsigned pct) { * mmap flags * -------------------------------------------------------------------------- */ +#ifndef RAY_OS_WINDOWS #define MMAP_FLAGS MAP_PRIVATE +#endif /* -------------------------------------------------------------------------- * Scratch memory helpers (same pattern as exec.c). diff --git a/src/mem/heap.c b/src/mem/heap.c index 1f82a7e69..906ef225e 100644 --- a/src/mem/heap.c +++ b/src/mem/heap.c @@ -44,11 +44,21 @@ #include /* getpid, close, ftruncate, unlink */ #include /* open, fcntl, F_PREALLOCATE on macOS */ #include -#include /* mmap, munmap */ #include /* O_* modes */ #include #include +/* File-backed spill (a pool or direct block mapped over a preallocated temp + * file when the anonymous mapping is refused) is POSIX-only. Windows pools + * take only the anonymous VirtualAlloc path (docs/architecture/memory.md): + * the spill helpers are compiled out and swap_fd stays -1 there. */ +#if defined(RAY_OS_WINDOWS) +# define RAY_HEAP_FILE_SPILL 0 +#else +# define RAY_HEAP_FILE_SPILL 1 +# include /* mmap, munmap */ +#endif + #ifdef DEBUG /* ===================================================================== * Debug-only stale-pointer detector (issue #240 investigation). @@ -64,7 +74,9 @@ * choice for chasing double releases (found while debugging #240). * RAY_DFD_NO_ABORT=1 reports without aborting. * ===================================================================== */ +#if !defined(RAY_OS_WINDOWS) #include +#endif #define DFD_CAP_BITS 20 #define DFD_CAP (1u << DFD_CAP_BITS) @@ -149,10 +161,12 @@ static void dfd_purge_range(uintptr_t lo, uintptr_t hi) { } static void dfd_report(const char* who, const void* p) { + fprintf(stderr, "\n=== DFD: %s on FREED block %p ===\n", who, p); +#if !defined(RAY_OS_WINDOWS) void* frames[64]; int n = backtrace(frames, 64); - fprintf(stderr, "\n=== DFD: %s on FREED block %p ===\n", who, p); backtrace_symbols_fd(frames, n, 2); +#endif fflush(stderr); if (!getenv("RAY_DFD_NO_ABORT")) abort(); } @@ -179,6 +193,7 @@ static void dfd_validate_freelists(void); * contiguous first, fall back to non-contiguous, then ftruncate to * extend the file size if needed (F_PREALLOCATE doesn't grow the file * beyond its current size). */ +#if RAY_HEAP_FILE_SPILL static int heap_preallocate(int fd, off_t offset, off_t len) { #if defined(__APPLE__) fstore_t fs = { @@ -202,6 +217,7 @@ static int heap_preallocate(int fd, off_t offset, off_t len) { return posix_fallocate(fd, offset, len); #endif } +#endif /* RAY_HEAP_FILE_SPILL */ /* -------------------------------------------------------------------------- * Static asserts @@ -574,6 +590,9 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { if (!heap_anon_would_exceed(pool_size)) mem = ray_vm_alloc_aligned(pool_size, pool_size); +#if !RAY_HEAP_FILE_SPILL + if (!mem) return false; +#else if (!mem) { /* Anonymous mmap refused — usually means RAM+swap can't satisfy * pool_size right now. Fall back to file-backed mmap: create a @@ -668,6 +687,7 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { ray_sys_free(swap_path); swap_path = NULL; } +#endif /* RAY_HEAP_FILE_SPILL */ /* Enable transparent huge pages on anon pools (Linux). Self-aligned * 32MB pools are 2MB-aligned, hence THP-eligible. Never on file-backed @@ -1184,6 +1204,10 @@ static void ray_detach_owned_refs(ray_t* v) { * failure. */ static void* heap_direct_map_file(ray_heap_t* h, size_t map_size, int* out_fd, char** out_path) { +#if !RAY_HEAP_FILE_SPILL + (void)h; (void)map_size; (void)out_fd; (void)out_path; + return NULL; +#else static _Atomic uint64_t direct_swap_counter = 0; uint64_t cnt = atomic_fetch_add_explicit(&direct_swap_counter, 1, memory_order_relaxed); @@ -1213,6 +1237,7 @@ static void* heap_direct_map_file(ray_heap_t* h, size_t map_size, *out_fd = fd; *out_path = path; return mapped; +#endif /* RAY_HEAP_FILE_SPILL */ } /* -------------------------------------------------------------------------- @@ -1713,6 +1738,7 @@ void ray_free(ray_t* v) { if (h) RAY_STAT(h->stats.free_count++); atomic_fetch_sub_explicit(&g_direct_bytes, (int64_t)map_size, memory_order_relaxed); atomic_fetch_sub_explicit(&g_direct_count, 1, memory_order_relaxed); +#if RAY_HEAP_FILE_SPILL if (swap_fd >= 0) { /* File-backed spill: mapped directly (not via ray_vm_alloc), so * unmap + uncount by hand, then close and unlink the spill file. */ @@ -1720,7 +1746,11 @@ void ray_free(ray_t* v) { ray_sys_track_sub((int64_t)map_size); close(swap_fd); if (swap_path) { unlink(swap_path); ray_sys_free(swap_path); } - } else if (direct_cache_put(base, map_size)) { + } else +#else + (void)swap_fd; (void)swap_path; +#endif + if (direct_cache_put(base, map_size)) { /* Stashed for reuse: pages stay resident, so the block keeps * its committed-RAM and watermark accounting; only the live * stats above dropped. Eviction (direct_cache_drain) performs diff --git a/src/store/aof.c b/src/store/aof.c index fe01b480b..e85831ae6 100644 --- a/src/store/aof.c +++ b/src/store/aof.c @@ -49,6 +49,15 @@ #include #include +/* ray_file_sync takes the platform handle: the descriptor itself on POSIX, + * the underlying HANDLE on Windows. */ +#ifdef RAY_OS_WINDOWS +#include +#define AOF_FP_HANDLE(fp) ((ray_fd_t)_get_osfhandle(fileno(fp))) +#else +#define AOF_FP_HANDLE(fp) ((ray_fd_t)fileno(fp)) +#endif + #define AOF_PATH_MAX 1024 /* Segment-path buffers are sized past the worst case (dir + '/' + 24-char * segment name) so gcc's -Wformat-truncation can prove snprintf fits even @@ -390,7 +399,7 @@ static ray_err_t aof_rotate(ray_aof_t* log) { if (err != RAY_OK) return err; } if (fflush(log->fp) != 0) return RAY_ERR_IO; - if (ray_file_sync((ray_fd_t)fileno(log->fp)) != RAY_OK) return RAY_ERR_IO; + if (ray_file_sync(AOF_FP_HANDLE(log->fp)) != RAY_OK) return RAY_ERR_IO; if (fclose(log->fp) != 0) { log->fp = NULL; return RAY_ERR_IO; } char path[AOF_SEGPATH_MAX]; @@ -442,7 +451,7 @@ ray_err_t ray_aof_commit(ray_aof_t* log) { ray_err_t err = aof_write_frame(log); if (err != RAY_OK) return err; if (fflush(log->fp) != 0) return RAY_ERR_IO; - return ray_file_sync((ray_fd_t)fileno(log->fp)); + return ray_file_sync(AOF_FP_HANDLE(log->fp)); } int64_t ray_aof_next_lsn(const ray_aof_t* log) { diff --git a/src/store/csr.c b/src/store/csr.c index 59f43b5ae..b042fb51b 100644 --- a/src/store/csr.c +++ b/src/store/csr.c @@ -24,6 +24,7 @@ #include "csr.h" #include "store/col.h" #include "mem/sys.h" +#include "store/fileio.h" /* ray_mkdir */ #include #include #include @@ -464,7 +465,7 @@ ray_err_t ray_rel_save(ray_rel_t* rel, const char* dir) { if (!rel || !dir) return RAY_ERR_IO; /* Create directory */ - if (mkdir(dir, 0755) != 0 && errno != EEXIST) return RAY_ERR_IO; + if (ray_mkdir(dir) != RAY_OK) return RAY_ERR_IO; ray_err_t err = csr_save(&rel->fwd, dir, "fwd"); if (err != RAY_OK) return err; diff --git a/src/store/fileio.h b/src/store/fileio.h index 658e56062..c6f954c82 100644 --- a/src/store/fileio.h +++ b/src/store/fileio.h @@ -24,10 +24,13 @@ #ifndef RAY_FILEIO_H #define RAY_FILEIO_H -#include +#include "core/platform.h" /* Cross-platform file I/O (locking, sync, atomic rename) */ #ifdef RAY_OS_WINDOWS + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN /* keep / macros out */ + #endif #include typedef HANDLE ray_fd_t; #define RAY_FD_INVALID INVALID_HANDLE_VALUE diff --git a/src/store/hnsw.c b/src/store/hnsw.c index 339119a19..a350c4335 100644 --- a/src/store/hnsw.c +++ b/src/store/hnsw.c @@ -23,6 +23,7 @@ #include "hnsw.h" #include "mem/sys.h" +#include "store/fileio.h" /* ray_mkdir */ #include #include #include @@ -818,7 +819,7 @@ typedef struct { ray_err_t ray_hnsw_save(const ray_hnsw_t* idx, const char* dir) { if (!idx || !dir) return RAY_ERR_IO; - if (mkdir(dir, 0755) != 0 && errno != EEXIST) return RAY_ERR_IO; + if (ray_mkdir(dir) != RAY_OK) return RAY_ERR_IO; char path[1024]; FILE* f; diff --git a/src/table/domain.c b/src/table/domain.c index ba87c492d..0e9f58697 100644 --- a/src/table/domain.c +++ b/src/table/domain.c @@ -210,6 +210,40 @@ static inline void dom_unlock(void) { /* ---- FILE domain construction / destruction ------------------------------- */ +/* realpath(3) contract: absolute path of an EXISTING file, else NULL. + * Windows has no realpath; _fullpath only normalizes (it succeeds for + * missing files too), so existence is checked separately. */ +static char* dom_realpath(const char* path, char resolved[PATH_MAX]) { +#if defined(RAY_OS_WINDOWS) + if (!_fullpath(resolved, path, PATH_MAX)) return NULL; + if (GetFileAttributesA(resolved) == INVALID_FILE_ATTRIBUTES) return NULL; + return resolved; +#else + return realpath(path, resolved); +#endif +} + +/* Do two resolved paths name the same file? On Windows one file is + * reachable as C:\db\sym, C:\db/sym or C:\DB\Sym (NTFS is case-insensitive + * and _fullpath keeps the caller's separators and case), so compare with + * '\\' == '/' and ASCII case folded — a plain strcmp would key one symfile + * twice and open two diverging domains for it. The paths themselves are + * left as given: they are also used to create the file. */ +static bool dom_path_eq(const char* a, const char* b) { +#if defined(RAY_OS_WINDOWS) + for (;; a++, b++) { + char ca = *a == '\\' ? '/' : *a; + char cb = *b == '\\' ? '/' : *b; + if (ca >= 'A' && ca <= 'Z') ca = (char)(ca - 'A' + 'a'); + if (cb >= 'A' && cb <= 'Z') cb = (char)(cb - 'A' + 'a'); + if (ca != cb) return false; + if (!ca) return true; + } +#else + return strcmp(a, b) == 0; +#endif +} + /* Resolved cache key for `path`. realpath of the file when it exists; * for to-be-created symfiles, realpath of the parent + "/" + basename * (the parent must exist). malloc'd. */ @@ -218,7 +252,7 @@ static char* dom_resolve_path(const char* path) { * realpath(NULL)/strdup's libc-malloc'd buffers, so the returned key is * uniformly buddy-allocated and the caller releases it with ray_free_raw. */ char resolved[PATH_MAX]; - if (realpath(path, resolved)) { + if (dom_realpath(path, resolved)) { size_t n = strlen(resolved); char* out = (char*)ray_sys_alloc(n + 1); if (out) memcpy(out, resolved, n + 1); @@ -238,7 +272,7 @@ static char* dom_resolve_path(const char* path) { memcpy(tmp, path, plen + 1); char* dir = dirname(tmp); char rdir[PATH_MAX]; - if (!realpath(dir, rdir)) return NULL; + if (!dom_realpath(dir, rdir)) return NULL; size_t dlen = strlen(rdir); char* out = (char*)ray_sys_alloc(dlen + 1 + blen + 1); if (!out) return NULL; @@ -519,7 +553,7 @@ static ray_sym_domain_t* dom_open_impl(const char* path, bool create) { dom_lock(); for (ray_sym_domain_t* d = g_domains; d; d = d->next) { - if (strcmp(d->path, rpath) == 0) { + if (dom_path_eq(d->path, rpath)) { /* Revalidate: external append-only growth extends in place; * any other divergence is loud (NULL). */ size_t cur_size = exists ? (size_t)st.st_size : 0; @@ -591,7 +625,7 @@ static ray_sym_domain_t* dom_open_impl(const char* path, bool create) { * the winner (pointer equality must hold for one resolved path). */ dom_lock(); for (ray_sym_domain_t* e = g_domains; e; e = e->next) { - if (strcmp(e->path, d->path) == 0) { + if (dom_path_eq(e->path, d->path)) { e->rc++; dom_unlock(); dom_destroy(d); From 9f5bbaf9995cbf9f771e3a652d0a7ec0d8a61bf3 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Tue, 22 Sep 2026 14:58:56 +0300 Subject: [PATCH 15/29] fix: REPL, profiler and system builtins build and work on Windows - term.h/profile.h include platform.h and a lean ; - term_write for the Windows console, errno.h and core count in the REPL; - .sys.info reports page-size and total-mem on Windows too; - KEY_READ no longer collides with . Co-Authored-By: Claude Opus 5 (1M context) --- src/app/repl.c | 6 +++++- src/app/term.c | 7 ++++++- src/app/term.h | 5 ++++- src/core/profile.h | 3 +++ src/ops/query.c | 4 +++- src/ops/system.c | 16 +++++++++++++++- 6 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/app/repl.c b/src/app/repl.c index 6775c8909..7036c63c4 100644 --- a/src/app/repl.c +++ b/src/app/repl.c @@ -51,6 +51,7 @@ #include #include #include +#include #if defined(RAY_OS_WINDOWS) #include @@ -59,7 +60,6 @@ #define STDIN_FD 0 #else #include -#include #include #define STDIN_FD STDIN_FILENO #endif @@ -385,7 +385,11 @@ static void print_banner(void) { char cpu[256]; get_cpu_name(cpu, sizeof(cpu)); int64_t mem_mb = get_total_mem_mb(); +#if defined(RAY_OS_WINDOWS) + int ncores = (int)ray_thread_count(); +#else int ncores = (int)sysconf(_SC_NPROCESSORS_ONLN); +#endif /* "Using" count reflects the actual worker-pool size, not ncores. * ray_pool_get() is a lazy initializer — callers might not have diff --git a/src/app/term.c b/src/app/term.c index ffae95482..79509f18a 100644 --- a/src/app/term.c +++ b/src/app/term.c @@ -67,7 +67,12 @@ typedef struct stat hist_stat_t; #define RAY_BLOCK_FROM_DATA(ptr) ((ray_t*)((char*)(ptr) - sizeof(ray_t))) /* Suppress -Wunused-result for terminal I/O writes to stdout. */ -#if !defined(RAY_OS_WINDOWS) +#if defined(RAY_OS_WINDOWS) +static inline void term_write(const void* buf, size_t len) { + int r = _write(1, buf, (unsigned)len); + (void)r; +} +#else static inline void term_write(const void* buf, size_t len) { ssize_t r = write(STDOUT_FILENO, buf, len); (void)r; diff --git a/src/app/term.h b/src/app/term.h index cf89457bf..8c7f23fa3 100644 --- a/src/app/term.h +++ b/src/app/term.h @@ -24,9 +24,12 @@ #ifndef RAY_TERM_H #define RAY_TERM_H -#include +#include "core/platform.h" #if defined(RAY_OS_WINDOWS) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN /* keep / macros out */ +#endif #include #define KEYCODE_RETURN '\r' #else diff --git a/src/core/profile.h b/src/core/profile.h index 02a71ab6a..cc5ab6ad7 100644 --- a/src/core/profile.h +++ b/src/core/profile.h @@ -28,6 +28,9 @@ #include #if defined(RAY_OS_WINDOWS) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN /* keep / macros out */ +#endif #include #else #include diff --git a/src/ops/query.c b/src/ops/query.c index 2008af99a..056d23882 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -11017,7 +11017,9 @@ ray_t* ray_select(ray_t** args, int64_t n) { /* Type-aware key element reader. Normalizes any * comparable scalar key into an int64_t so linear * scans can use equality. For floats we bitcast so - * NaN and -0/+0 match the DAG's hash-equality. */ + * NaN and -0/+0 match the DAG's hash-equality. + * (via ) owns the name on Windows. */ + #undef KEY_READ #define KEY_READ(dst, vec, base_type, idx) do { \ const void* _d = ray_data(vec); \ switch (base_type) { \ diff --git a/src/ops/system.c b/src/ops/system.c index 176415645..6d5a55cce 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -65,6 +65,7 @@ void* ray_runtime_get_sys_args(void); #define RAY_POPEN(c, m) popen((c), (m)) #define RAY_PCLOSE(f) pclose(f) #else +#include /* access, F_OK */ #define RAY_POPEN(c, m) _popen((c), (m)) #define RAY_PCLOSE(f) _pclose(f) #endif @@ -1532,10 +1533,23 @@ ray_t* ray_sysinfo_fn(ray_t** args, int64_t n) { ray_t* v3 = make_i64(ray_sys_total_ram()); vals = ray_list_append(vals, v3); ray_release(v3); #else + SYSTEM_INFO si; + GetSystemInfo(&si); + int64_t s1 = ray_sym_intern("cores", 5); keys = ray_vec_append(keys, &s1); - ray_t* v1 = make_i64(1); + ray_t* v1 = make_i64((int64_t)si.dwNumberOfProcessors); vals = ray_list_append(vals, v1); ray_release(v1); + + int64_t s2 = ray_sym_intern("page-size", 9); + keys = ray_vec_append(keys, &s2); + ray_t* v2 = make_i64((int64_t)si.dwPageSize); + vals = ray_list_append(vals, v2); ray_release(v2); + + int64_t s3 = ray_sym_intern("total-mem", 9); + keys = ray_vec_append(keys, &s3); + ray_t* v3 = make_i64(ray_sys_total_ram()); + vals = ray_list_append(vals, v3); ray_release(v3); #endif /* Process and host identity (#573). An embedded process previously had From 0807e1cb7b2f4fb4a7681a961c1904f2ab2cf4dd Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Tue, 22 Sep 2026 14:58:57 +0300 Subject: [PATCH 16/29] test: run the suite on Windows - runner: ';; @requires: posix' marks .rfl files whose fixtures or checks need a POSIX shell/filesystem; on Windows they are reported as SKIP; - shell-free ray_test_rm_rf / ray_test_mkdir_p replace system("rm -rf") and "mkdir -p" in C tests; test.h maps the few POSIX helpers tests use; - tests of POSIX-only behaviour (setrlimit, ENOTDIR, read-only dirs, AF_UNIX, file spill, Winsock send buffering) skip with the reason; - fixture fixes that were latent on any platform: binary-mode CSV fixtures, a per-test AOF dir, journal closed before the crash rename. Co-Authored-By: Claude Opus 5 (1M context) --- test/ipc_harness.h | 5 + test/main.c | 62 ++++++++++++ test/rfl/collection/atomic_map_coverage.rfl | 1 + test/rfl/collection/collection_branch_cov.rfl | 1 + test/rfl/collection/cov3.rfl | 1 + test/rfl/collection/cov4.rfl | 1 + test/rfl/collection/cov5.rfl | 1 + test/rfl/collection/cov6.rfl | 1 + test/rfl/group/group_key_types.rfl | 1 + test/rfl/io/csv_branch_cov.rfl | 1 + test/rfl/io/csv_parallel_scan.rfl | 1 + test/rfl/io/csv_rayfall_temporal.rfl | 1 + test/rfl/io/csv_types.rfl | 1 + test/rfl/io/read_until_eof.rfl | 1 + test/rfl/journal/ops_journal.rfl | 1 + test/rfl/journal/ops_journal_purge.rfl | 1 + test/rfl/lang/guid_entropy.rfl | 1 + test/rfl/lang/parse_branch_cov.rfl | 1 + test/rfl/linkop/coverage.rfl | 1 + test/rfl/null/slice_has_nulls.rfl | 1 + test/rfl/null/sort_null_placement.rfl | 1 + test/rfl/null/sym_str_null_compare.rfl | 1 + test/rfl/ops/internal_coverage.rfl | 1 + test/rfl/query/update_by_sym_width.rfl | 1 + test/rfl/regress/load_select_isnull_mask.rfl | 1 + test/rfl/sort/sort_coverage2.rfl | 1 + test/rfl/storage/shared_sym_domain.rfl | 1 + test/rfl/storage/splay_coverage.rfl | 1 + test/rfl/store/col_format_generation.rfl | 1 + test/rfl/store/indexed_col_aux_refs.rfl | 1 + test/rfl/strop/like_seen_proj.rfl | 1 + test/rfl/strop/string_branch_cov.rfl | 1 + test/rfl/symbol/sym_coverage.rfl | 1 + test/rfl/system/cli_flag_values.rfl | 1 + test/rfl/system/csv_auto_int_width.rfl | 1 + .../rfl/system/csv_explicit_numeric_types.rfl | 1 + test/rfl/system/db_get.rfl | 1 + test/rfl/system/db_parted_fill.rfl | 1 + test/rfl/system/db_sym_resolution.rfl | 1 + test/rfl/system/ipc_diff.rfl | 1 + test/rfl/system/ipc_first_last.rfl | 1 + test/rfl/system/ipc_open_errors.rfl | 1 + test/rfl/system/ipc_open_timeout.rfl | 1 + test/rfl/system/listen_fatal.rfl | 1 + test/rfl/system/load_errors.rfl | 1 + test/rfl/system/load_home.rfl | 1 + test/rfl/system/log_journal.rfl | 1 + test/rfl/system/log_journal_advanced.rfl | 1 + test/rfl/system/os_fs.rfl | 1 + test/rfl/system/part.rfl | 1 + test/rfl/system/part_branch_cov.rfl | 1 + test/rfl/system/piped_timers.rfl | 1 + test/rfl/system/process_identity.rfl | 1 + test/rfl/system/querylog_ipc.rfl | 1 + test/rfl/system/read_csv.rfl | 1 + test/rfl/system/startup_script_fatal.rfl | 1 + test/rfl/system/system_branch_cov.rfl | 1 + test/rfl/system/timer_overrun.rfl | 1 + test/stress_store.c | 36 +++++-- test/test.h | 54 +++++++++++ test/test_aof.c | 7 +- test/test_csv.c | 70 ++++++------- test/test_heap.c | 31 ++++++ test/test_ipc.c | 97 +++++++++++++------ test/test_journal.c | 64 +++++++++++- test/test_link.c | 24 +++-- test/test_mcast.c | 30 +++--- test/test_repl.c | 6 +- test/test_runtime.c | 14 ++- test/test_splay.c | 43 ++++---- test/test_store.c | 53 +++++----- test/test_traverse.c | 8 +- 72 files changed, 496 insertions(+), 164 deletions(-) diff --git a/test/ipc_harness.h b/test/ipc_harness.h index 5f9066dd3..8dad45aea 100644 --- a/test/ipc_harness.h +++ b/test/ipc_harness.h @@ -48,8 +48,13 @@ #include "core/runtime.h" #include "mem/sys.h" #include "lang/internal.h" +#ifdef RAY_OS_WINDOWS +#include +#include +#else #include #include +#endif #include #include diff --git a/test/main.c b/test/main.c index 6cf59894f..42426e6a0 100644 --- a/test/main.c +++ b/test/main.c @@ -50,6 +50,7 @@ #include "lang/format.h" #include "ops/internal.h" #include "ops/idxop.h" +#include "store/fileio.h" /* ray_mkdir_p — ray_test_mkdir_p */ /* __RUNTIME is internal test plumbing; runtime API declarations come from * . */ @@ -376,6 +377,16 @@ static test_result_t run_rfl_file(const char* path) { src[r] = '\0'; fclose(f); + /* ";; @requires: posix" anywhere in a file marks it as depending on a + * POSIX shell / filesystem (.sys.exec pipelines, /proc). Where that + * does not exist the file is reported as SKIP, never silently dropped. */ +#if defined(_WIN32) + if (strstr(src, ";; @requires: posix")) { + free(src); + SKIP("requires POSIX shell/filesystem"); + } +#endif + int line_no = 0; int assert_count = 0; /* tallies LHS -- RHS and EXPR !- SUBSTR lines */ char* p = src; @@ -848,7 +859,58 @@ static int name_matches_filter(const char* name, const char* filter) { return strstr(name, filter) != NULL; } +/* ---- Shell-free filesystem helpers (declared in test.h) ---- */ + +int ray_test_rm_rf(const char* path) { + struct stat st; + if (lstat(path, &st) != 0) return 0; /* already gone */ + if (S_ISDIR(st.st_mode)) { + DIR* d = opendir(path); + if (d) { + struct dirent* ent; + char child[4096]; + while ((ent = readdir(d)) != NULL) { + if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) + continue; + snprintf(child, sizeof(child), "%s/%s", path, ent->d_name); + ray_test_rm_rf(child); + } + closedir(d); + } + return rmdir(path); + } + return unlink(path); +} + +int ray_test_mkdir_p(const char* path) { + return ray_mkdir_p(path) == RAY_OK ? 0 : -1; +} + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +long ray_test_sysconf(int name) { + SYSTEM_INFO si; + GetSystemInfo(&si); + switch (name) { + case _SC_PAGESIZE: return (long)si.dwPageSize; + case _SC_NPROCESSORS_ONLN: return (long)si.dwNumberOfProcessors; + case _SC_PHYS_PAGES: { + MEMORYSTATUSEX ms; + ms.dwLength = sizeof(ms); + if (!GlobalMemoryStatusEx(&ms)) return -1; + return (long)(ms.ullTotalPhys / si.dwPageSize); + } + default: errno = EINVAL; return -1; + } +} +#endif + int main(int argc, char** argv) { +#if defined(_WIN32) + (void)_mkdir("/tmp"); /* tests use "/tmp/..." paths (see test.h) */ +#endif ray_expr_stats_init(); ray_idx_stats_init(); g_color = isatty(fileno(stdout)); diff --git a/test/rfl/collection/atomic_map_coverage.rfl b/test/rfl/collection/atomic_map_coverage.rfl index 7eba0de75..28c7e7b27 100644 --- a/test/rfl/collection/atomic_map_coverage.rfl +++ b/test/rfl/collection/atomic_map_coverage.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; atomic_map_binary_op / atomic_map_unary coverage. ;; Exercises boxed-list paths, empty collections, nested auto-map, ;; recursive map, and error propagation. diff --git a/test/rfl/collection/collection_branch_cov.rfl b/test/rfl/collection/collection_branch_cov.rfl index b187b9e05..dc0e28bb8 100644 --- a/test/rfl/collection/collection_branch_cov.rfl +++ b/test/rfl/collection/collection_branch_cov.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; collection_branch_cov.rfl — branch coverage for src/ops/collection.c ;; ;; Targets uncovered branches identified at 64.84% baseline. Each section diff --git a/test/rfl/collection/cov3.rfl b/test/rfl/collection/cov3.rfl index 0c2e08f59..dc23bea6d 100644 --- a/test/rfl/collection/cov3.rfl +++ b/test/rfl/collection/cov3.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; cov3.rfl — additional targeted coverage for collection.c remaining gaps ;; Focuses on: atom_eq LIST path, propagate_sym_dict, list_to_typed_vec empty SYM/STR, ;; take STR range out-of-bounds, take dict with typed vals, diff --git a/test/rfl/collection/cov4.rfl b/test/rfl/collection/cov4.rfl index 61b0a9bb0..07923cbf1 100644 --- a/test/rfl/collection/cov4.rfl +++ b/test/rfl/collection/cov4.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; cov4 — targeted coverage for collection.c remaining gaps ;; Focuses on: atom_eq different-length vecs, range-take type errors, ;; STR typed vec from CSV, STR range-take out-of-bounds, diff --git a/test/rfl/collection/cov5.rfl b/test/rfl/collection/cov5.rfl index 0dd92350a..2be5c80b5 100644 --- a/test/rfl/collection/cov5.rfl +++ b/test/rfl/collection/cov5.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; cov5 — targeted coverage: distinct_sort_cmp default branch (lines 282-291) ;; ;; F32 (type=6) is not in hs_hash_row switch → hashes by index (all "distinct"). diff --git a/test/rfl/collection/cov6.rfl b/test/rfl/collection/cov6.rfl index d6517d320..efd9d21bb 100644 --- a/test/rfl/collection/cov6.rfl +++ b/test/rfl/collection/cov6.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; cov6 — targeted coverage: parted_to_flat_vec STR path (lines 778-790) ;; ;; parted_to_flat_vec has two branches: diff --git a/test/rfl/group/group_key_types.rfl b/test/rfl/group/group_key_types.rfl index 8c868fe24..aca43f3fc 100644 --- a/test/rfl/group/group_key_types.rfl +++ b/test/rfl/group/group_key_types.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Coverage for group.c — key type diversity paths ;; ;; Targets: diff --git a/test/rfl/io/csv_branch_cov.rfl b/test/rfl/io/csv_branch_cov.rfl index 562e0e214..93eead2d6 100644 --- a/test/rfl/io/csv_branch_cov.rfl +++ b/test/rfl/io/csv_branch_cov.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Branch coverage for src/io/csv.c — targets reachable functional branches ;; left uncovered by csv_types.rfl, csv_round2.rfl, csv_splayed.rfl, ;; system/{read,write}_csv.rfl, and test/test_csv.c. diff --git a/test/rfl/io/csv_parallel_scan.rfl b/test/rfl/io/csv_parallel_scan.rfl index d8b0e7370..470235d49 100644 --- a/test/rfl/io/csv_parallel_scan.rfl +++ b/test/rfl/io/csv_parallel_scan.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Parallel row-offset scan (csv.c build_row_offsets_par) — exactness. ;; ;; The scan splits the file into chunks and reconciles quote parity across diff --git a/test/rfl/io/csv_rayfall_temporal.rfl b/test/rfl/io/csv_rayfall_temporal.rfl index 5163c1923..6f18420cd 100644 --- a/test/rfl/io/csv_rayfall_temporal.rfl +++ b/test/rfl/io/csv_rayfall_temporal.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; CSV type inference must recognize Rayfall's display temporal forms. ;; These are the forms users see when DATE/TIMESTAMP values are printed. (.sys.exec "printf 'd,ts\n2024.01.02,2024.01.02D01:02:03.004005006\n' > rf_test_csv_rayfall_temporal.csv") -- 0 diff --git a/test/rfl/io/csv_types.rfl b/test/rfl/io/csv_types.rfl index 671f73668..f2a63358a 100644 --- a/test/rfl/io/csv_types.rfl +++ b/test/rfl/io/csv_types.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Coverage for src/io/csv.c — type inference, edge cases, parted writer. ;; ;; Targets (by approximate line number): diff --git a/test/rfl/io/read_until_eof.rfl b/test/rfl/io/read_until_eof.rfl index a4ea55ab6..2fe117c3f 100644 --- a/test/rfl/io/read_until_eof.rfl +++ b/test/rfl/io/read_until_eof.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; `read` / `read-bytes` must read until EOF, not to the size the file ;; reports — issue #572. ;; diff --git a/test/rfl/journal/ops_journal.rfl b/test/rfl/journal/ops_journal.rfl index b962325c3..0c04bd193 100644 --- a/test/rfl/journal/ops_journal.rfl +++ b/test/rfl/journal/ops_journal.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Coverage extension for src/ops/journal.c. ;; ;; The bulk of src/ops/journal.c is exercised by diff --git a/test/rfl/journal/ops_journal_purge.rfl b/test/rfl/journal/ops_journal_purge.rfl index e24369c1c..f21da7139 100644 --- a/test/rfl/journal/ops_journal_purge.rfl +++ b/test/rfl/journal/ops_journal_purge.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Coverage for .log.purge (src/ops/journal.c ray_log_purge_fn -> ;; src/store/journal.c ray_journal_purge) — issue #279. ;; diff --git a/test/rfl/lang/guid_entropy.rfl b/test/rfl/lang/guid_entropy.rfl index b77ceadbe..6d4e5511d 100644 --- a/test/rfl/lang/guid_entropy.rfl +++ b/test/rfl/lang/guid_entropy.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; `guid` must be unique across processes — issue #571. ;; ;; The generator seeded its per-thread xorshift state from rand(), and diff --git a/test/rfl/lang/parse_branch_cov.rfl b/test/rfl/lang/parse_branch_cov.rfl index 046871d53..44ca9bf04 100644 --- a/test/rfl/lang/parse_branch_cov.rfl +++ b/test/rfl/lang/parse_branch_cov.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Branch-coverage extension for src/lang/parse.c — the Rayfall parser ;; (tokenizer, atom-literal parsing, list/dict/vector syntax, comments, ;; escape sequences, error recovery). diff --git a/test/rfl/linkop/coverage.rfl b/test/rfl/linkop/coverage.rfl index 6aebc2bb5..6bba5bea8 100644 --- a/test/rfl/linkop/coverage.rfl +++ b/test/rfl/linkop/coverage.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Coverage workout for src/ops/linkop.c ;; Targets the regions NOT exercised by test/test_link.c: ;; - ray_col_link_fn error paths (lines 291, 293) diff --git a/test/rfl/null/slice_has_nulls.rfl b/test/rfl/null/slice_has_nulls.rfl index c30a383ec..60e0e9808 100644 --- a/test/rfl/null/slice_has_nulls.rfl +++ b/test/rfl/null/slice_has_nulls.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; slice_has_nulls.rfl — a slice sees its parent's nulls, in memory and on ;; disk (#495). ;; diff --git a/test/rfl/null/sort_null_placement.rfl b/test/rfl/null/sort_null_placement.rfl index 7f11b4a47..6a71ba30b 100644 --- a/test/rfl/null/sort_null_placement.rfl +++ b/test/rfl/null/sort_null_placement.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Where a null lands in a sort, pinned for every path that can run. ;; ;; A null is the SMALLEST value: ascending puts nulls first, descending last. diff --git a/test/rfl/null/sym_str_null_compare.rfl b/test/rfl/null/sym_str_null_compare.rfl index 40a13b4fc..bde1fa4ef 100644 --- a/test/rfl/null/sym_str_null_compare.rfl +++ b/test/rfl/null/sym_str_null_compare.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Equality comparison on NULLABLE SYM / STR columns — fused path vs unfused. ;; ;; A SYM null is sym id 0 and a STR null is a zero-length descriptor: both are diff --git a/test/rfl/ops/internal_coverage.rfl b/test/rfl/ops/internal_coverage.rfl index 15633da0c..a033b33a6 100644 --- a/test/rfl/ops/internal_coverage.rfl +++ b/test/rfl/ops/internal_coverage.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Coverage for src/ops/internal.h static-inline helpers that are ;; instantiated in production TUs (exec.c, filter.c, expr.c, etc.) ;; but have never been exercised through the test suite. diff --git a/test/rfl/query/update_by_sym_width.rfl b/test/rfl/query/update_by_sym_width.rfl index dc52d0227..c9b3d38a9 100644 --- a/test/rfl/query/update_by_sym_width.rfl +++ b/test/rfl/query/update_by_sym_width.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Regression: `update ... by: ` on a narrow-width SYM key column. ;; ;; SYM columns use an adaptive dictionary-index width (W8/W16/W32/W64 in attrs, diff --git a/test/rfl/regress/load_select_isnull_mask.rfl b/test/rfl/regress/load_select_isnull_mask.rfl index d0fffb148..db46bbd4b 100644 --- a/test/rfl/regress/load_select_isnull_mask.rfl +++ b/test/rfl/regress/load_select_isnull_mask.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Regression: load → select ISNULL WHERE-mask corruption. ;; ;; exec_elementwise_unary once had dedicated ISNULL kernels for only some diff --git a/test/rfl/sort/sort_coverage2.rfl b/test/rfl/sort/sort_coverage2.rfl index 3d1dec16f..e0b34c284 100644 --- a/test/rfl/sort/sort_coverage2.rfl +++ b/test/rfl/sort/sort_coverage2.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Pass-7 additional sort.c coverage. ;; ;; Targets uncovered regions NOT hit by sort_coverage.rfl: diff --git a/test/rfl/storage/shared_sym_domain.rfl b/test/rfl/storage/shared_sym_domain.rfl index 119d49012..780677f79 100644 --- a/test/rfl/storage/shared_sym_domain.rfl +++ b/test/rfl/storage/shared_sym_domain.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; The client layout, end-to-end through the language surface (sym-domain ;; architecture, Task 7b): a parted `hist` plus a splayed `live` sharing ;; ONE symfile (root/.sym) — write, read, query, join (same-domain fast diff --git a/test/rfl/storage/splay_coverage.rfl b/test/rfl/storage/splay_coverage.rfl index ffc09d7f3..51b1be34d 100644 --- a/test/rfl/storage/splay_coverage.rfl +++ b/test/rfl/storage/splay_coverage.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Coverage extension for src/store/splay.c. ;; ;; src/store/splay.c is exercised by: diff --git a/test/rfl/store/col_format_generation.rfl b/test/rfl/store/col_format_generation.rfl index a5d3cccc0..d9b2de411 100644 --- a/test/rfl/store/col_format_generation.rfl +++ b/test/rfl/store/col_format_generation.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; On-disk column format generation (the header `order` byte, offset 17). ;; ;; Regression: an engine build briefly stamped the generation to 1 and demanded diff --git a/test/rfl/store/indexed_col_aux_refs.rfl b/test/rfl/store/indexed_col_aux_refs.rfl index 962539ea1..0d2731be5 100644 --- a/test/rfl/store/indexed_col_aux_refs.rfl +++ b/test/rfl/store/indexed_col_aux_refs.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; An indexed column still owns what sits at aux bytes 8-15. ;; ;; A SYM column keeps its resolution domain there, a STR column its pool. diff --git a/test/rfl/strop/like_seen_proj.rfl b/test/rfl/strop/like_seen_proj.rfl index 84aa9ec2d..5e78351f9 100644 --- a/test/rfl/strop/like_seen_proj.rfl +++ b/test/rfl/strop/like_seen_proj.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Targeted parallel SYM-LIKE coverage for like_seen_fn / like_proj_fn. ;; ;; Both kernels are the worker bodies dispatched by ray_pool_dispatch diff --git a/test/rfl/strop/string_branch_cov.rfl b/test/rfl/strop/string_branch_cov.rfl index 24838bfb4..27b26bb8b 100644 --- a/test/rfl/strop/string_branch_cov.rfl +++ b/test/rfl/strop/string_branch_cov.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; string_branch_cov.rfl -- targeted branch coverage for src/ops/string.c ;; ;; Baseline: 61.41% (345 uncovered branches). This file targets the diff --git a/test/rfl/symbol/sym_coverage.rfl b/test/rfl/symbol/sym_coverage.rfl index 1b9e2b4af..01a23e7dc 100644 --- a/test/rfl/symbol/sym_coverage.rfl +++ b/test/rfl/symbol/sym_coverage.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Coverage extension for src/table/sym.c. ;; ;; src/table/sym.c is exercised by many existing tests via CSV/splayed I/O. diff --git a/test/rfl/system/cli_flag_values.rfl b/test/rfl/system/cli_flag_values.rfl index c014eadac..2eb4e7039 100644 --- a/test/rfl/system/cli_flag_values.rfl +++ b/test/rfl/system/cli_flag_values.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; cli_flag_values.rfl — a value-taking flag must not swallow the next flag, ;; and an unknown option must not be mistaken for the script (#600). ;; diff --git a/test/rfl/system/csv_auto_int_width.rfl b/test/rfl/system/csv_auto_int_width.rfl index fd8ff1192..91c37ea77 100644 --- a/test/rfl/system/csv_auto_int_width.rfl +++ b/test/rfl/system/csv_auto_int_width.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; `INT` schema token → auto narrowest integer width on .csv.splayed. ;; ;; A column declared `INT` in a .csv.splayed schema is parsed as int64, diff --git a/test/rfl/system/csv_explicit_numeric_types.rfl b/test/rfl/system/csv_explicit_numeric_types.rfl index d053c5209..facf89284 100644 --- a/test/rfl/system/csv_explicit_numeric_types.rfl +++ b/test/rfl/system/csv_explicit_numeric_types.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Explicit numeric schemas must survive the streaming .csv.splayed writer ;; and the mmap-backed .db.splayed.get reload without widening. diff --git a/test/rfl/system/db_get.rfl b/test/rfl/system/db_get.rfl index cb03cd4ae..66f6cf336 100644 --- a/test/rfl/system/db_get.rfl +++ b/test/rfl/system/db_get.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Multi-table roots through the explicit .db trio — the surface left ;; after the .db.*.mount removal: every table is opened by name with ;; .db.splayed.get / .db.parted.get; nothing is discovered or bound diff --git a/test/rfl/system/db_parted_fill.rfl b/test/rfl/system/db_parted_fill.rfl index 2574b271a..b0e3a947a 100644 --- a/test/rfl/system/db_parted_fill.rfl +++ b/test/rfl/system/db_parted_fill.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; .db.parted.fill — fill missing tables across a parted db's partitions. ;; ;; For every table present in ANY partition, write an empty copy (schema diff --git a/test/rfl/system/db_sym_resolution.rfl b/test/rfl/system/db_sym_resolution.rfl index daed3ae87..56fce7170 100644 --- a/test/rfl/system/db_sym_resolution.rfl +++ b/test/rfl/system/db_sym_resolution.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; SYM-domain symfile resolution precedence, end-to-end (sym-domain ;; architecture spec, "Surface"): ;; explicit argument | dir/.sym | partition-shaped parent -> root/.sym diff --git a/test/rfl/system/ipc_diff.rfl b/test/rfl/system/ipc_diff.rfl index e02f1f08f..31f627bd5 100644 --- a/test/rfl/system/ipc_diff.rfl +++ b/test/rfl/system/ipc_diff.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Differential IPC oracle. ;; ;; Spawns a fresh `./rayforce -p PORT` process as an IPC server, then diff --git a/test/rfl/system/ipc_first_last.rfl b/test/rfl/system/ipc_first_last.rfl index fcd366424..b468e0bda 100644 --- a/test/rfl/system/ipc_first_last.rfl +++ b/test/rfl/system/ipc_first_last.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Regression: `first`/`last` returned over IPC used to hang the client ;; forever (issue #285). ;; diff --git a/test/rfl/system/ipc_open_errors.rfl b/test/rfl/system/ipc_open_errors.rfl index 525da04fd..7760319a0 100644 --- a/test/rfl/system/ipc_open_errors.rfl +++ b/test/rfl/system/ipc_open_errors.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; ipc_open_errors.rfl — `.ipc.open` names the failure it actually hit. ;; ;; Regression (#472): the connect and the wire handshake share one budget, diff --git a/test/rfl/system/ipc_open_timeout.rfl b/test/rfl/system/ipc_open_timeout.rfl index 6a525b1b6..896254d6b 100644 --- a/test/rfl/system/ipc_open_timeout.rfl +++ b/test/rfl/system/ipc_open_timeout.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Connect timeout argument for `.ipc.open` (issue #286). ;; ;; `.ipc.open` is now a variadic builtin accepting an optional second diff --git a/test/rfl/system/listen_fatal.rfl b/test/rfl/system/listen_fatal.rfl index 7417ae327..d4f93aa4a 100644 --- a/test/rfl/system/listen_fatal.rfl +++ b/test/rfl/system/listen_fatal.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; listen_fatal.rfl — a `-p` that cannot bind is fatal (#473). ;; ;; Regression: when ray_ipc_listen_at failed, main printed diff --git a/test/rfl/system/load_errors.rfl b/test/rfl/system/load_errors.rfl index f2fdcf822..99959bf6a 100644 --- a/test/rfl/system/load_errors.rfl +++ b/test/rfl/system/load_errors.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; load_errors.rfl — a failing `load` names the file and the OS cause (#505). ;; ;; Regression: ray_load_file_fn returned a bare `io` for every failure, so diff --git a/test/rfl/system/load_home.rfl b/test/rfl/system/load_home.rfl index 4ce8575eb..febcad8e4 100644 --- a/test/rfl/system/load_home.rfl +++ b/test/rfl/system/load_home.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; load_home.rfl — relative `load` paths fall back to RAYFORCE_HOME, and ;; (.sys.args) reports the file being evaluated as `source` (#506). ;; diff --git a/test/rfl/system/log_journal.rfl b/test/rfl/system/log_journal.rfl index bca8730fd..a6d1e7534 100644 --- a/test/rfl/system/log_journal.rfl +++ b/test/rfl/system/log_journal.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Journal end-to-end — transaction-log journaling (-l/-L). ;; ;; Two named processes are spawned in sequence under -l ; this diff --git a/test/rfl/system/log_journal_advanced.rfl b/test/rfl/system/log_journal_advanced.rfl index 7d1a7e228..e0916179c 100644 --- a/test/rfl/system/log_journal_advanced.rfl +++ b/test/rfl/system/log_journal_advanced.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Journal feature — invariants the basic test (log_journal.rfl) does ;; not cover. Each phase uses a distinct base + port so a phase ;; failing mid-run doesn't pollute the next one's state. diff --git a/test/rfl/system/os_fs.rfl b/test/rfl/system/os_fs.rfl index 9bccd27e9..76630f81f 100644 --- a/test/rfl/system/os_fs.rfl +++ b/test/rfl/system/os_fs.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; .fs.size and .fs.list — filesystem metadata primitives, issue #36. ;; ;; Two functions on purpose: every other predicate (exists, is-file, diff --git a/test/rfl/system/part.rfl b/test/rfl/system/part.rfl index 9084f24f3..0af053193 100644 --- a/test/rfl/system/part.rfl +++ b/test/rfl/system/part.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; src/store/part.c — exercise every reachable branch of ray_read_parted ;; (the function backing .db.parted.get) plus the ;; static helpers infer_mc_type, parse_date_dir, parse_int_dir, diff --git a/test/rfl/system/part_branch_cov.rfl b/test/rfl/system/part_branch_cov.rfl index 9553fc943..5b71277d4 100644 --- a/test/rfl/system/part_branch_cov.rfl +++ b/test/rfl/system/part_branch_cov.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; src/store/part.c — branch-coverage top-up for ray_read_parted and its ;; static helpers (is_date_dir, is_integer_str, infer_mc_type, ;; parse_date_dir, parse_int_dir, collect_part_dirs). diff --git a/test/rfl/system/piped_timers.rfl b/test/rfl/system/piped_timers.rfl index 83cb6a64b..689987ce2 100644 --- a/test/rfl/system/piped_timers.rfl +++ b/test/rfl/system/piped_timers.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; piped_timers.rfl — timers keep firing while a piped (non-TTY) stdin is ;; held open, and a process stays for its pending timers after input ends ;; (#493, the narrowed report). diff --git a/test/rfl/system/process_identity.rfl b/test/rfl/system/process_identity.rfl index d0baa387d..af3e5183c 100644 --- a/test/rfl/system/process_identity.rfl +++ b/test/rfl/system/process_identity.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Process and host identity, plus .sys.exec output capture — issue #573. ;; ;; An embedded process could not learn anything about itself: no PID, no diff --git a/test/rfl/system/querylog_ipc.rfl b/test/rfl/system/querylog_ipc.rfl index f65b18c20..08dd04fb2 100644 --- a/test/rfl/system/querylog_ipc.rfl +++ b/test/rfl/system/querylog_ipc.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Query-statistics ring end-to-end over IPC (the server / cloud path). ;; ;; The capture hook lives in eval_payload_core (src/core/ipc.c), so it only diff --git a/test/rfl/system/read_csv.rfl b/test/rfl/system/read_csv.rfl index 5ecd1080e..fcbe301f2 100644 --- a/test/rfl/system/read_csv.rfl +++ b/test/rfl/system/read_csv.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; Ported from test_lang_rf.inc::test_rf_read_csv. ;; Rayfall's str-pool hits "error: limit" when raze/fold accumulates ;; ~1000 strings, so we shell out via .sys.exec to write the 20k-row diff --git a/test/rfl/system/startup_script_fatal.rfl b/test/rfl/system/startup_script_fatal.rfl index 343738563..d935cc273 100644 --- a/test/rfl/system/startup_script_fatal.rfl +++ b/test/rfl/system/startup_script_fatal.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; startup_script_fatal.rfl — a failing startup script under -p is fatal ;; non-interactively (#507). ;; diff --git a/test/rfl/system/system_branch_cov.rfl b/test/rfl/system/system_branch_cov.rfl index 32adf1dd5..bb67d9ed6 100644 --- a/test/rfl/system/system_branch_cov.rfl +++ b/test/rfl/system/system_branch_cov.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; system_branch_cov.rfl — branch coverage for src/ops/system.c (part 1). ;; ;; Covers: ser/de, splayed set/get, parted get, os.size, os.list, diff --git a/test/rfl/system/timer_overrun.rfl b/test/rfl/system/timer_overrun.rfl index 9bd677297..125b2254d 100644 --- a/test/rfl/system/timer_overrun.rfl +++ b/test/rfl/system/timer_overrun.rfl @@ -1,3 +1,4 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) ;; timer_overrun.rfl — a periodic timer does not replay missed intervals, ;; and a failing callback's line carries the message (#474). ;; diff --git a/test/stress_store.c b/test/stress_store.c index 71ac326df..c92453e4b 100644 --- a/test/stress_store.c +++ b/test/stress_store.c @@ -4,6 +4,11 @@ * Rayforce heap under test. */ +#if !defined(_WIN32) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE /* lstat under strict -std=c17 */ +#endif + +#include "test.h" /* POSIX shims on Windows (lstat) */ #include "stress_store.h" #include "store/splay.h" #include "store/part.h" @@ -14,6 +19,9 @@ #include #include #include /* getpid — per-process scratch paths */ +#include +#include +#include "store/fileio.h" /* ray_mkdir_p */ const char* stress_db_path(const char* name) { static char buf[256]; @@ -148,10 +156,28 @@ void stress_part_dir(const stress_ctx_t* c, int i, char* buf, size_t n) { snprintf(buf, n, "%s/%s/hist", c->db_root, c->part_dates[i]); } +/* Recursive delete without a shell (portable to Windows, where system() + * runs cmd.exe and has no `rm -rf`). */ static void rm_rf(const char* path) { - char cmd[600]; - snprintf(cmd, sizeof(cmd), "rm -rf '%s'", path); - (void)!system(cmd); + struct stat st; + if (lstat(path, &st) != 0) return; /* never follow a symlink out */ + if (S_ISDIR(st.st_mode)) { + DIR* d = opendir(path); + if (d) { + struct dirent* ent; + char child[1024]; + while ((ent = readdir(d)) != NULL) { + if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) + continue; + snprintf(child, sizeof(child), "%s/%s", path, ent->d_name); + rm_rf(child); + } + closedir(d); + } + (void)rmdir(path); + } else { + (void)unlink(path); + } } /* ---- ray table <-> shadow rows ------------------------------------------ */ @@ -276,9 +302,7 @@ bool stress_init(stress_ctx_t* c, const char* db_root, uint64_t seed) { c->oplog = (char(*)[128])malloc((size_t)STRESS_OPLOG_CAP * 128); if (!c->oplog) return false; rm_rf(c->db_root); - char cmd[600]; - snprintf(cmd, sizeof(cmd), "mkdir -p '%s'", c->db_root); - if (system(cmd) != 0) { + if (ray_mkdir_p(c->db_root) != RAY_OK) { free(c->oplog); c->oplog = NULL; return false; diff --git a/test/test.h b/test/test.h index 8a54c42ee..8f67db58d 100644 --- a/test/test.h +++ b/test/test.h @@ -41,6 +41,60 @@ #include #include +/* Shell-free filesystem helpers (test/main.c). Tests must not depend on + * /bin/sh: on Windows system() runs cmd.exe. Both return 0 on success. */ +int ray_test_rm_rf(const char* path); /* rm -rf path */ +int ray_test_mkdir_p(const char* path); /* mkdir -p path */ + +#if defined(_WIN32) +/* POSIX helpers the tests rely on, mapped onto their MSVCRT equivalents. + * Test paths use "/tmp/...", which Windows resolves to :\tmp; the + * runner creates that directory at startup (see test/main.c). */ +#include +#include +#include +#include +static inline int setenv(const char* k, const char* v, int overwrite) { + if (!overwrite && getenv(k)) return 0; + return _putenv_s(k, v) == 0 ? 0 : -1; +} +static inline int unsetenv(const char* k) { + return _putenv_s(k, "") == 0 ? 0 : -1; /* "" removes the variable */ +} +static inline char* mkdtemp(char* tmpl) { + if (!_mktemp(tmpl)) return NULL; + return _mkdir(tmpl) == 0 ? tmpl : NULL; +} +static inline unsigned geteuid(void) { return 1; } /* never "root" */ +#define lstat stat /* no symlinks to skip */ +#include +#include +static inline int symlink(const char* target, const char* path) { + (void)target; (void)path; + errno = ENOSYS; /* callers skip when symlink fails */ + return -1; +} +#define mkdir(p, mode) _mkdir(p) +#define pipe(fds) _pipe((fds), 65536, _O_BINARY) +/* sysconf subset (page size, physical pages, CPUs); see test/main.c. */ +#define _SC_PAGESIZE 1 +#define _SC_PAGE_SIZE _SC_PAGESIZE +#define _SC_PHYS_PAGES 2 +#define _SC_NPROCESSORS_ONLN 3 +long ray_test_sysconf(int name); +#define sysconf ray_test_sysconf +/* MSVCRT's tmpfile() creates its file in the drive root, which needs admin + * rights. Use the temp directory instead; "D" deletes the file on close. */ +static inline FILE* ray_test_tmpfile(void) { + char* name = _tempnam("/tmp", "rayt"); + if (!name) return NULL; + FILE* f = fopen(name, "w+bD"); + free(name); + return f; +} +#define tmpfile ray_test_tmpfile +#endif + typedef enum { TEST_PASS = 0, TEST_FAIL, TEST_SKIP } test_status_t; typedef struct { diff --git a/test/test_aof.c b/test/test_aof.c index 4705436fc..469f5491e 100644 --- a/test/test_aof.c +++ b/test/test_aof.c @@ -58,7 +58,12 @@ static void aof_rm_rf(const char* dir) { } static void aof_setup(void) { - snprintf(g_aof_dir, sizeof g_aof_dir, "/tmp/ray_test_aof_%d", (int)getpid()); + /* A fresh dir per test: the crash test deliberately leaks an open + * writer, and on Windows an open file cannot be deleted, so a shared + * dir would hand its stale segment to every later test. */ + static int seq = 0; + snprintf(g_aof_dir, sizeof g_aof_dir, "/tmp/ray_test_aof_%d_%d", + (int)getpid(), seq++); aof_rm_rf(g_aof_dir); } diff --git a/test/test_csv.c b/test/test_csv.c index 9a964fc23..3f0156246 100644 --- a/test/test_csv.c +++ b/test/test_csv.c @@ -213,7 +213,7 @@ static test_result_t test_csv_null_i64(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "x\n10\n\n30\n"); fclose(f); @@ -245,7 +245,7 @@ static test_result_t test_csv_null_i64_unparseable(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "x\n10\nN/A\n30\n"); fclose(f); @@ -274,7 +274,7 @@ static test_result_t test_csv_null_f64(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "x\n1.5\n\n3.5\n"); fclose(f); @@ -305,7 +305,7 @@ static test_result_t test_csv_null_i16(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "x\n10\n\n30\n"); fclose(f); @@ -336,7 +336,7 @@ static test_result_t test_csv_null_i32(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "x\n10\n\n30\n"); fclose(f); @@ -367,7 +367,7 @@ static test_result_t test_csv_null_date(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "d\n2025-01-02\n\n2026-12-31\n"); fclose(f); @@ -396,7 +396,7 @@ static test_result_t test_csv_null_time(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "t\n12:34:56\n\n23:59:59\n"); fclose(f); @@ -425,7 +425,7 @@ static test_result_t test_csv_null_timestamp(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "ts\n2025-01-02T03:04:05\n\n2026-12-31T23:59:59\n"); fclose(f); @@ -455,7 +455,7 @@ static test_result_t test_csv_null_bool(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "flag\ntrue\n\nfalse\n"); fclose(f); @@ -484,7 +484,7 @@ static test_result_t test_csv_null_sym(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "name\nalice\n\nbob\n"); fclose(f); @@ -515,7 +515,7 @@ static test_result_t test_csv_no_nulls_no_null_bitmap(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "x\n10\n20\n30\n"); fclose(f); @@ -537,7 +537,7 @@ static test_result_t test_csv_null_mixed_columns(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "id,val,name\n1,1.5,alice\n,2.5,\n3,,bob\n"); fclose(f); @@ -579,7 +579,7 @@ static test_result_t test_csv_explicit_str_schema(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); /* Mix inline (<=12B), pooled (>12B), empty/null, and a short */ fprintf(f, "id,note\n" "1,hi\n" @@ -628,7 +628,7 @@ static test_result_t test_csv_escaped_str_roundtrip(void) { (void)ray_sym_init(); /* Write a CSV with fields that require quoting/escaping */ - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "s\n" "\"he,llo\"\n" "\"wo\"\"rld\"\n" @@ -748,7 +748,7 @@ static test_result_t test_csv_infer_date(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "d\n2025-01-02\n2026-12-31\n2000-03-15\n"); fclose(f); @@ -769,7 +769,7 @@ static test_result_t test_csv_infer_time(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "t\n12:34:56\n00:00:00\n23:59:59.123\n"); fclose(f); @@ -792,7 +792,7 @@ static test_result_t test_csv_infer_timestamp_promotion(void) { /* Mix of full timestamps with both 'T' and ' ' separators, plus a * date-only sentinel that should be promoted to TIMESTAMP. */ - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "ts\n2025-01-02T03:04:05\n2025-06-07 08:09:10.123456\n2024-12-31\n"); fclose(f); @@ -813,7 +813,7 @@ static test_result_t test_csv_infer_bool(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "b\ntrue\nfalse\nTRUE\nFALSE\n"); fclose(f); @@ -834,7 +834,7 @@ static test_result_t test_csv_infer_f64_specials(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "v\n1.0\n2e10\n-3.5E-2\nnan\nInf\n+inf\n-INF\n"); fclose(f); @@ -856,7 +856,7 @@ static test_result_t test_csv_infer_null_sentinels(void) { (void)ray_sym_init(); /* Sentinel rows alternating with i64 values; column should infer I64. */ - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "x\n10\nN/A\nNA\nnull\nNULL\nNone\nnone\nn/a\nna\n.\n42\n"); fclose(f); @@ -882,7 +882,7 @@ static test_result_t test_csv_infer_promotions(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "n,b\n1,true\n2,0\n3.5,1\n"); fclose(f); @@ -905,7 +905,7 @@ static test_result_t test_csv_tab_delimiter(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "a\tb\tc\n1\t2\t3\n4\t5\t6\n"); fclose(f); @@ -926,7 +926,7 @@ static test_result_t test_csv_no_header(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "10,20\n30,40\n50,60\n"); fclose(f); @@ -988,7 +988,7 @@ static test_result_t test_csv_invalid_schema_type(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "x\n1\n2\n"); fclose(f); @@ -1002,7 +1002,7 @@ static test_result_t test_csv_invalid_schema_type(void) { /* Schema too short for ncols also errors out. */ int8_t one_only[1] = { RAY_I64 }; - FILE* g = fopen(TMP_CSV, "w"); + FILE* g = fopen(TMP_CSV, "wb"); fprintf(g, "a,b\n1,2\n"); fclose(g); ray_t* loaded3 = ray_read_csv_opts(TMP_CSV, ',', true, one_only, 1); @@ -1044,7 +1044,7 @@ static test_result_t test_csv_truncated_row(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "a,b,c\n1,2,3\n4\n7,8,9\n"); fclose(f); @@ -1277,7 +1277,7 @@ static test_result_t test_csv_parallel_parse(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "i,s\n"); /* 9000 rows so n_rows > 8192. */ for (int i = 0; i < 9000; i++) @@ -1306,7 +1306,7 @@ static test_result_t test_csv_sym_narrowing(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "k\n"); /* Only three distinct values across many rows. */ for (int i = 0; i < 200; i++) @@ -1342,7 +1342,7 @@ static test_result_t test_csv_explicit_u8_schema(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "v\n"); /* 10 000 rows ⇒ parallel parse path; values 0..255 cycling so the * truncated bytes fully exercise the U8 range. */ @@ -1384,7 +1384,7 @@ static test_result_t test_csv_explicit_i16_schema_with_nulls(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "v\n"); const int N = 1500; for (int i = 0; i < N; i++) { @@ -1427,7 +1427,7 @@ static test_result_t test_csv_explicit_i32_schema(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "v\n"); const int N = 500; for (int i = 0; i < N; i++) fprintf(f, "%d\n", -100000 + i * 137); @@ -1460,7 +1460,7 @@ static test_result_t test_csv_explicit_u8_schema_serial(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "a,b\n"); /* 200 rows; second column missing on every 50th row → triggers * past-row-boundary fill in the parser. */ @@ -1501,7 +1501,7 @@ static test_result_t test_csv_infer_high_cardinality_str(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); fprintf(f, "payload\n"); for (int i = 0; i < 100; i++) fprintf(f, "unique_payload_%03d\n", i); @@ -1570,7 +1570,7 @@ static test_result_t test_csv_interrupt_mid_parse(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); TEST_ASSERT_NOT_NULL(f); fputs("id,payload\n", f); for (int i = 0; i < 200000; i++) { @@ -1610,7 +1610,7 @@ static test_result_t test_csv_progress_never_goes_backwards(void) { ray_heap_init(); (void)ray_sym_init(); - FILE* f = fopen(TMP_CSV, "w"); + FILE* f = fopen(TMP_CSV, "wb"); TEST_ASSERT_NOT_NULL(f); fputs("payload,symbol\n", f); for (int i = 0; i < 100000; i++) diff --git a/test/test_heap.c b/test/test_heap.c index 2054f7b15..0e14473f2 100644 --- a/test/test_heap.c +++ b/test/test_heap.c @@ -50,7 +50,33 @@ #include #include #include +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#include +/* Anonymous mmap for the fake file-mapped (mmod==1) blocks below: a + * pagefile-backed view, so the library's ray_vm_unmap_file + * (UnmapViewOfFile) releases it just as it would a real file mapping. */ +#define PROT_READ 1 +#define PROT_WRITE 2 +#define MAP_PRIVATE 2 +#define MAP_ANONYMOUS 0x20 +#define MAP_FAILED ((void*)-1) +static void* mmap(void* addr, size_t len, int prot, int flags, int fd, long off) { + (void)addr; (void)prot; (void)flags; (void)fd; (void)off; + HANDLE m = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, + 0, (DWORD)len, NULL); + if (!m) return MAP_FAILED; + void* p = MapViewOfFile(m, FILE_MAP_WRITE, 0, 0, len); + CloseHandle(m); + return p ? p : MAP_FAILED; +} +static int munmap(void* p, size_t len) { + (void)len; + return UnmapViewOfFile(p) ? 0 : -1; +} +#else #include +#endif #include #include @@ -2565,6 +2591,11 @@ static test_result_t test_direct_cache_concurrent_replacement(void) { /* Drive the anon-to-file crossing with a low watermark, independent of RAM. */ static test_result_t test_anon_watermark_spill(void) { +#if defined(_WIN32) + /* Windows takes only the anonymous path; the file-backed spill is + * POSIX-only (docs/architecture/memory.md, RAY_HEAP_FILE_SPILL). */ + SKIP("file-backed spill is POSIX-only"); +#endif size_t sz = 40 * 1024 * 1024 - 128; /* order 26 → direct path */ /* Start from an empty reuse cache: leftover cached blocks from earlier * tests would (a) inflate the baseline and (b) be drained by the diff --git a/test/test_ipc.c b/test/test_ipc.c index 21b3dfa1c..aa1752f06 100644 --- a/test/test_ipc.c +++ b/test/test_ipc.c @@ -54,11 +54,16 @@ #include "test.h" #include "ipc_harness.h" +#ifdef RAY_OS_WINDOWS +#include +#include +#else #include #include #include #include #include +#endif #include #include "core/ipc.h" #include "core/sock.h" @@ -1047,12 +1052,17 @@ static test_result_t test_ipc_send_large_compressible(void) { * Open a journal, then connect an IPC server on top; each SYNC message * should flow through ray_journal_write_bytes. */ +/* Drop a journal's .log / .qdb pair (no shell). */ +static void ipc_rm_journal(const char* jbase) { + char path[256]; + snprintf(path, sizeof(path), "%s.log", jbase); (void)remove(path); + snprintf(path, sizeof(path), "%s.qdb", jbase); (void)remove(path); +} + static test_result_t test_ipc_journal_path(void) { const char* jbase = "/tmp/rayforce_test_ipc_journal"; /* Remove stale files */ - char cmd[256]; - snprintf(cmd, sizeof(cmd), "rm -f %s.log %s.qdb", jbase, jbase); - system(cmd); + ipc_rm_journal(jbase); /* Open journal */ ray_err_t jerr = ray_journal_open(jbase, RAY_JOURNAL_ASYNC); @@ -1081,7 +1091,7 @@ static test_result_t test_ipc_journal_path(void) { ray_test_server_stop(&srv); ray_journal_close(); - system(cmd); /* cleanup */ + ipc_rm_journal(jbase); /* cleanup */ PASS(); } @@ -1453,9 +1463,7 @@ static test_result_t test_ipc_send_verbose_large_result(void) { */ static test_result_t test_ipc_journal_restricted(void) { const char* jbase = "/tmp/rayforce_test_ipc_jrestr"; - char cmd[256]; - snprintf(cmd, sizeof(cmd), "rm -f %s.log %s.qdb", jbase, jbase); - system(cmd); + ipc_rm_journal(jbase); ray_err_t jerr = ray_journal_open(jbase, RAY_JOURNAL_ASYNC); if (jerr != RAY_OK) { @@ -1486,7 +1494,7 @@ static test_result_t test_ipc_journal_restricted(void) { ray_test_server_stop(&srv); ray_journal_close(); - system(cmd); + ipc_rm_journal(jbase); PASS(); } @@ -1979,6 +1987,7 @@ static test_result_t test_ipc_addr_local_ipv6_remote(void) { PASS(); } +#ifndef RAY_OS_WINDOWS /* AF_UNIX locality is POSIX-only (see sock.c) */ static test_result_t test_ipc_addr_local_af_unix(void) { struct sockaddr_un sa; memset(&sa, 0, sizeof(sa)); @@ -1986,6 +1995,7 @@ static test_result_t test_ipc_addr_local_af_unix(void) { TEST_ASSERT_TRUE(ray_sock_addr_is_local(&sa, sizeof(sa))); PASS(); } +#endif static test_result_t test_ipc_addr_local_rejects_garbage(void) { struct sockaddr_in sa; @@ -1998,24 +2008,53 @@ static test_result_t test_ipc_addr_local_rejects_garbage(void) { PASS(); } -/* A real AF_UNIX pair resolves as local through getpeername. */ +/* A connected pair of sockets on this machine: an AF_UNIX socketpair on + * POSIX; Windows has no socketpair(2), so a loopback TCP pair there. */ +static int test_local_sock_pair(ray_sock_t sv[2]) { +#ifdef RAY_OS_WINDOWS + ray_sock_t srv = ray_sock_listen_at("127.0.0.1", 0); + if (srv == RAY_INVALID_SOCK) return -1; + struct sockaddr_in addr; + int len = sizeof(addr); + if (getsockname((SOCKET)srv, (struct sockaddr*)&addr, &len) != 0) { + ray_sock_close(srv); + return -1; + } + sv[0] = ray_sock_connect("127.0.0.1", ntohs(addr.sin_port), 0); + sv[1] = sv[0] == RAY_INVALID_SOCK ? RAY_INVALID_SOCK : ray_sock_accept(srv); + ray_sock_close(srv); + if (sv[1] == RAY_INVALID_SOCK) { + if (sv[0] != RAY_INVALID_SOCK) ray_sock_close(sv[0]); + return -1; + } + return 0; +#else + int fds[2]; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) != 0) return -1; + sv[0] = fds[0]; + sv[1] = fds[1]; + return 0; +#endif +} + +/* A real local pair resolves as local through getpeername. */ static test_result_t test_ipc_peer_is_local_socketpair(void) { - int sv[2]; - TEST_ASSERT_EQ_I(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0); - TEST_ASSERT_TRUE(ray_sock_peer_is_local((ray_sock_t)sv[0])); - TEST_ASSERT_TRUE(ray_sock_peer_is_local((ray_sock_t)sv[1])); - close(sv[0]); - close(sv[1]); + ray_sock_t sv[2]; + TEST_ASSERT_EQ_I(test_local_sock_pair(sv), 0); + TEST_ASSERT_TRUE(ray_sock_peer_is_local(sv[0])); + TEST_ASSERT_TRUE(ray_sock_peer_is_local(sv[1])); + ray_sock_close(sv[0]); + ray_sock_close(sv[1]); PASS(); } /* An unconnected socket has no peer: getpeername fails, and an unknown * peer must fall back to the compressing default, not to "local". */ static test_result_t test_ipc_peer_is_local_unconnected(void) { - int fd = socket(AF_INET, SOCK_STREAM, 0); - TEST_ASSERT_TRUE(fd >= 0); - TEST_ASSERT_FALSE(ray_sock_peer_is_local((ray_sock_t)fd)); - close(fd); + ray_sock_t fd = (ray_sock_t)socket(AF_INET, SOCK_STREAM, 0); + TEST_ASSERT_TRUE(fd != RAY_INVALID_SOCK); + TEST_ASSERT_FALSE(ray_sock_peer_is_local(fd)); + ray_sock_close(fd); PASS(); } @@ -2027,18 +2066,18 @@ static test_result_t test_ipc_peer_is_local_invalid_fd(void) { /* The policy the send paths consult: local links never compress, others * keep the compiled-in default. */ static test_result_t test_ipc_link_threshold_local_vs_remote(void) { - int sv[2]; - TEST_ASSERT_EQ_I(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0); - TEST_ASSERT_EQ_U(ray_ipc_link_threshold((ray_sock_t)sv[0]), + ray_sock_t sv[2]; + TEST_ASSERT_EQ_I(test_local_sock_pair(sv), 0); + TEST_ASSERT_EQ_U(ray_ipc_link_threshold(sv[0]), RAY_IPC_COMPRESS_NEVER); - close(sv[0]); - close(sv[1]); + ray_sock_close(sv[0]); + ray_sock_close(sv[1]); - int fd = socket(AF_INET, SOCK_STREAM, 0); - TEST_ASSERT_TRUE(fd >= 0); - TEST_ASSERT_EQ_U(ray_ipc_link_threshold((ray_sock_t)fd), + ray_sock_t fd = (ray_sock_t)socket(AF_INET, SOCK_STREAM, 0); + TEST_ASSERT_TRUE(fd != RAY_INVALID_SOCK); + TEST_ASSERT_EQ_U(ray_ipc_link_threshold(fd), (size_t)RAY_IPC_COMPRESS_THRESHOLD); - close(fd); + ray_sock_close(fd); PASS(); } @@ -2747,7 +2786,9 @@ const test_entry_t ipc_entries[] = { { "ipc/addr_local/ipv6_loopback", test_ipc_addr_local_ipv6_loopback, ipc_setup, ipc_teardown }, { "ipc/addr_local/ipv6_mapped_loopback",test_ipc_addr_local_ipv6_mapped_loopback, ipc_setup, ipc_teardown }, { "ipc/addr_local/ipv6_remote", test_ipc_addr_local_ipv6_remote, ipc_setup, ipc_teardown }, +#ifndef RAY_OS_WINDOWS { "ipc/addr_local/af_unix", test_ipc_addr_local_af_unix, ipc_setup, ipc_teardown }, +#endif { "ipc/addr_local/rejects_garbage", test_ipc_addr_local_rejects_garbage, ipc_setup, ipc_teardown }, { "ipc/peer_is_local/socketpair", test_ipc_peer_is_local_socketpair, ipc_setup, ipc_teardown }, { "ipc/peer_is_local/unconnected", test_ipc_peer_is_local_unconnected, ipc_setup, ipc_teardown }, diff --git a/test/test_journal.c b/test/test_journal.c index 8277a7290..9904893f6 100644 --- a/test/test_journal.c +++ b/test/test_journal.c @@ -40,7 +40,44 @@ #include #include #include +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#include +/* Minimal glob(3) for the archive checks below: wildcards only in the + * last path component, which is all ".*.log" needs. */ +typedef struct { size_t gl_pathc; char** gl_pathv; } glob_t; +static void globfree(glob_t* g) { + for (size_t i = 0; i < g->gl_pathc; i++) free(g->gl_pathv[i]); + free(g->gl_pathv); + g->gl_pathc = 0; g->gl_pathv = NULL; +} +static int glob(const char* pat, int flags, void* errfunc, glob_t* g) { + (void)flags; (void)errfunc; + g->gl_pathc = 0; g->gl_pathv = NULL; + const char* slash = strrchr(pat, '/'); + const char* bs = strrchr(pat, '\\'); + if (bs && (!slash || bs > slash)) slash = bs; + size_t dlen = slash ? (size_t)(slash - pat) + 1 : 0; + WIN32_FIND_DATAA fd; + HANDLE h = FindFirstFileA(pat, &fd); + if (h == INVALID_HANDLE_VALUE) return 3; /* GLOB_NOMATCH */ + do { + if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; + size_t nlen = strlen(fd.cFileName); + char* path = (char*)malloc(dlen + nlen + 1); + char** v = (char**)realloc(g->gl_pathv, (g->gl_pathc + 1) * sizeof(char*)); + if (!path || !v) { free(path); if (v) g->gl_pathv = v; FindClose(h); globfree(g); return 1; } + memcpy(path, pat, dlen); + memcpy(path + dlen, fd.cFileName, nlen + 1); + g->gl_pathv = v; + g->gl_pathv[g->gl_pathc++] = path; + } while (FindNextFileA(h, &fd)); + FindClose(h); + return g->gl_pathc ? 0 : 3; +} +#else #include +#endif /* ── Runtime fixture (same pattern as test_link.c) ─────────────────── */ @@ -98,8 +135,17 @@ static void cleanup_base(const char* base) { snprintf(path, sizeof(path), "%s.qdb", base); unlink(path); snprintf(path, sizeof(path), "%s.qdb.tmp", base); unlink(path); /* Archived rolls have the form base..log — remove with glob via shell. */ +#if defined(_WIN32) + snprintf(path, sizeof(path), "%s.*.log", base); /* no POSIX shell here */ + glob_t g; + if (glob(path, 0, NULL, &g) == 0) { + for (size_t i = 0; i < g.gl_pathc; i++) unlink(g.gl_pathv[i]); + globfree(&g); + } +#else snprintf(path, sizeof(path), "rm -f '%s'.*.log 2>/dev/null", base); (void)system(path); +#endif } /* ═══════════════════════════════════════════════════════════════════════ @@ -1041,15 +1087,19 @@ static test_result_t test_journal_crash_window_no_double_apply(void) { /* Simulate the crash IN the window: put the just-archived log back * under its live name, exactly the on-disk state a crash between - * the two renames leaves behind. */ + * the two renames leaves behind. The journal is closed first (the + * "process" is gone), and the live file removed before the rename: + * Windows can neither replace a file that is still open nor rename + * onto an existing one. */ + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); char pattern[300]; snprintf(pattern, sizeof(pattern), "%s.*.log", base); glob_t g; TEST_ASSERT_EQ_I(glob(pattern, 0, NULL, &g), 0); TEST_ASSERT_EQ_I((int64_t)g.gl_pathc, 1); + (void)remove(lpath); TEST_ASSERT_EQ_I(rename(g.gl_pathv[0], lpath), 0); globfree(&g); - TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); /* Restart: clobber the binding, recover. The covered log must be * skipped — jw_x comes back as the snapshot value, not value+1. */ @@ -2294,9 +2344,13 @@ static bool purge_write_one(int64_t x) { /* True iff at least one rolled archive (base..log) exists. */ static bool archive_exists(const char* base) { - char cmd[1200]; - snprintf(cmd, sizeof(cmd), "test -n \"$(ls '%s'.*.log 2>/dev/null)\"", base); - return system(cmd) == 0; + char pattern[1200]; + snprintf(pattern, sizeof(pattern), "%s.*.log", base); + glob_t g; + if (glob(pattern, 0, NULL, &g) != 0) return false; /* no match */ + bool found = g.gl_pathc > 0; + globfree(&g); + return found; } /* P1. Full purge while the journal is OPEN: closes it, unlinks the active diff --git a/test/test_link.c b/test/test_link.c index cd430538c..7f1c8d560 100644 --- a/test/test_link.c +++ b/test/test_link.c @@ -918,9 +918,7 @@ static ray_err_t write_link_partition(const char* part_dir, int64_t custs_sym) { char dir[1024]; snprintf(dir, sizeof(dir), TMP_LINK_PART_DB "/%s/" TMP_LINK_PART_TBL, part_dir); - char cmd[1100]; - snprintf(cmd, sizeof(cmd), "mkdir -p %s", dir); - if (system(cmd) != 0) return RAY_ERR_IO; + if (ray_test_mkdir_p(dir) != 0) return RAY_ERR_IO; ray_t* ridcol = ray_vec_from_raw(RAY_I64, (void*)rids, n_rid); if (!ridcol || RAY_IS_ERR(ridcol)) return RAY_ERR_OOM; @@ -954,7 +952,7 @@ static ray_err_t write_link_partition(const char* part_dir, static test_result_t test_link_parted_load_propagates(void) { int64_t custs_sym = setup_custs_dim(); - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); int64_t r1[] = { 0, 1, 2 }; int64_t q1[] = { 10, 20, 30 }; @@ -1020,7 +1018,7 @@ static test_result_t test_link_parted_load_propagates(void) { ray_release(ages1); ray_release(parted); - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); PASS(); } @@ -1032,7 +1030,7 @@ static test_result_t test_link_attach_rejects_parted_target(void) { /* Build a parted table on disk and load via ray_read_parted so we have a * real RAY_TABLE-with-RAY_PARTED-cols handle to point at. */ int64_t custs_sym = setup_custs_dim(); - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); int64_t r1[] = { 0, 1, 2 }; int64_t q1[] = { 10, 20, 30 }; @@ -1065,7 +1063,7 @@ static test_result_t test_link_attach_rejects_parted_target(void) { ray_release(w); ray_release(v); - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); PASS(); } @@ -1095,7 +1093,7 @@ static test_result_t test_link_deref_rejects_parted_after_rebind(void) { ray_release(good); /* Build a parted table on disk and rebind `custs` to it. */ - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); int64_t r1[] = { 0, 1 }; int64_t q1[] = { 10, 20 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.01", r1, 2, q1, 2, custs_sym), RAY_OK); @@ -1118,7 +1116,7 @@ static test_result_t test_link_deref_rejects_parted_after_rebind(void) { ray_release(w); ray_release(v); - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); PASS(); } @@ -1155,7 +1153,7 @@ static test_result_t test_link_dotted_resolve_propagates_parted_error(void) { ray_release(good); /* Rebind custs to a parted table on disk. */ - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); int64_t r1[] = { 0, 1 }; int64_t q1[] = { 10, 20 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.01", r1, 2, q1, 2, custs_sym), RAY_OK); @@ -1180,7 +1178,7 @@ static test_result_t test_link_dotted_resolve_propagates_parted_error(void) { ray_release(w); ray_release(v); - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); PASS(); } @@ -1212,7 +1210,7 @@ static test_result_t test_link_vm_eval_propagates_parted_error(void) { ray_release(good); /* Rebind custs to a parted table. */ - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); int64_t r1[] = { 0, 1 }; int64_t q1[] = { 10, 20 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.01", r1, 2, q1, 2, custs_sym), RAY_OK); @@ -1233,7 +1231,7 @@ static test_result_t test_link_vm_eval_propagates_parted_error(void) { ray_release(w); ray_release(v); - (void)!system("rm -rf " TMP_LINK_PART_DB); + (void)ray_test_rm_rf(TMP_LINK_PART_DB); PASS(); } diff --git a/test/test_mcast.c b/test/test_mcast.c index 8fa810535..e71e174bf 100644 --- a/test/test_mcast.c +++ b/test/test_mcast.c @@ -26,6 +26,9 @@ #include #include #include +#else + #include + #include #endif extern ray_runtime_t* __RUNTIME; @@ -631,7 +634,6 @@ static test_result_t test_mcast_large_payload_queues_until_writable(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); ray_release(sub); -#ifndef RAY_OS_WINDOWS ray_t* server_h = ray_env_get(ray_sym_intern("_mc_sub_handle", 14)); TEST_ASSERT_NOT_NULL(server_h); TEST_ASSERT_EQ_I(server_h->type, -RAY_I64); @@ -639,8 +641,7 @@ static test_result_t test_mcast_large_payload_queues_until_writable(void) { TEST_ASSERT_NOT_NULL(server_sel); int sndbuf = 4096; setsockopt((ray_sock_t)server_sel->fd, SOL_SOCKET, SO_SNDBUF, - &sndbuf, sizeof(sndbuf)); -#endif + (const char*)&sndbuf, sizeof(sndbuf)); const char* pub_src = "(.mc.pub \"big\" (+ (* (til 100000) 1103515245) 12345))"; @@ -728,7 +729,6 @@ static test_result_t test_mcast_shared_frame_across_subscribers(void) { int64_t hp = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); TEST_ASSERT((hp) >= (0), "publisher connected"); -#ifndef RAY_OS_WINDOWS ray_t* server_hs = ray_env_get(ray_sym_intern("_mc_handles", 11)); TEST_ASSERT_NOT_NULL(server_hs); TEST_ASSERT((ray_len(server_hs)) >= (3), "three server-side subscriber handles"); @@ -737,9 +737,8 @@ static test_result_t test_mcast_shared_frame_across_subscribers(void) { ray_selector_t* ssel = ray_poll_get(poll, sh); TEST_ASSERT_NOT_NULL(ssel); int sndbuf = 4096; - setsockopt((ray_sock_t)ssel->fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)); + setsockopt((ray_sock_t)ssel->fd, SOL_SOCKET, SO_SNDBUF, (const char*)&sndbuf, sizeof(sndbuf)); } -#endif const char* pub_src = "(.mc.pub \"big\" (+ (* (til 100000) 1103515245) 12345))"; ray_t* msg = ray_str(pub_src, strlen(pub_src)); @@ -802,6 +801,13 @@ static test_result_t test_mcast_shared_frame_across_subscribers(void) { * frame keeps receiving. The active limits and the high-water mark are * readable from .mc.stats and per handle from (.ipc.handle h). */ static test_result_t test_mcast_txlimit_overflow_disconnects(void) { +#if defined(_WIN32) + /* The backlog this test needs never forms on Windows: Winsock accepts a + * single non-blocking send() larger than SO_SNDBUF whole (it pins the + * caller's buffer), so the 800 KiB frame leaves at once and no + * subscriber crosses its tx limit. */ + SKIP("Winsock accepts oversized sends whole; no tx backlog forms"); +#endif ray_t* r = ray_eval_str( "(set _mc_count 0)" "(set _mc_close_count 0)" @@ -840,14 +846,12 @@ static test_result_t test_mcast_txlimit_overflow_disconnects(void) { TEST_ASSERT((ray_len(server_hs)) >= (2), "two server-side subscriber handles"); int64_t s1 = ((int64_t*)ray_data(server_hs))[0]; int64_t s2 = ((int64_t*)ray_data(server_hs))[1]; -#ifndef RAY_OS_WINDOWS for (int i = 0; i < 2; i++) { ray_selector_t* ssel = ray_poll_get(poll, i == 0 ? s1 : s2); TEST_ASSERT_NOT_NULL(ssel); int sndbuf = 4096; - setsockopt((ray_sock_t)ssel->fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)); + setsockopt((ray_sock_t)ssel->fd, SOL_SOCKET, SO_SNDBUF, (const char*)&sndbuf, sizeof(sndbuf)); } -#endif /* Process default: 64 KiB. h2 alone may hold 4 MiB. */ ray_t* msg = ray_str("(.ipc.txlimit 65536 0)", strlen("(.ipc.txlimit 65536 0)")); @@ -1040,14 +1044,12 @@ static test_result_t test_ipc_outbound_close_hook(void) { TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_oc_out", 7, 1, 1000)); /* B: the peer resets h2 (linger zero, then close → RST) */ -#ifndef RAY_OS_WINDOWS { ray_selector_t* ssel = ray_poll_get(poll, s2); TEST_ASSERT_NOT_NULL(ssel); struct linger lg = { 1, 0 }; - setsockopt((ray_sock_t)ssel->fd, SOL_SOCKET, SO_LINGER, &lg, sizeof(lg)); + setsockopt((ray_sock_t)ssel->fd, SOL_SOCKET, SO_LINGER, (const char*)&lg, sizeof(lg)); } -#endif n = snprintf(src, sizeof(src), "(.ipc.close %lld)", (long long)s2); msg = ray_str(src, (size_t)n); cr = ray_ipc_send(hc, msg); @@ -1224,7 +1226,6 @@ static test_result_t test_mcast_sync_reply_after_queued_frame(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); ray_release(sub); -#ifndef RAY_OS_WINDOWS /* Shrink the server->h1 send buffer so a big frame parks on sel->tx.buf * instead of leaving in a single write. */ ray_t* server_h = ray_env_get(ray_sym_intern("_mc_sub_handle", 14)); @@ -1234,8 +1235,7 @@ static test_result_t test_mcast_sync_reply_after_queued_frame(void) { TEST_ASSERT_NOT_NULL(server_sel); int sndbuf = 4096; setsockopt((ray_sock_t)server_sel->fd, SOL_SOCKET, SO_SNDBUF, - &sndbuf, sizeof(sndbuf)); -#endif + (const char*)&sndbuf, sizeof(sndbuf)); const char* pub_src = "(.mc.pub \"big\" (+ (* (til 100000) 1103515245) 12345))"; diff --git a/test/test_repl.c b/test/test_repl.c index a341cc4fa..5397c2070 100644 --- a/test/test_repl.c +++ b/test/test_repl.c @@ -88,10 +88,8 @@ extern void* ray_runtime_get_poll(void); * poll first (closes any leftover conns), runtime second. */ static void repl_setup(void) { ray_runtime_create(0, NULL); -#ifndef RAY_OS_WINDOWS ray_poll_t* p = ray_poll_create(); if (p) ray_runtime_set_poll(p); -#endif } static void repl_teardown(void) { @@ -103,7 +101,6 @@ static void repl_teardown(void) { ray_t* args = NULL; ray_release(ray_repl_disconnect_fn(&args, 0)); } -#ifndef RAY_OS_WINDOWS { ray_poll_t* p = (ray_poll_t*)ray_runtime_get_poll(); if (p) { @@ -111,7 +108,6 @@ static void repl_teardown(void) { ray_poll_destroy(p); } } -#endif ray_runtime_destroy(__RUNTIME); } @@ -670,7 +666,9 @@ static test_result_t test_repl_pty_ctrl_d(void) { * code proves it ran while the prompt was idle, and the helper's 5 s * timeout (-2) is what a starved timer would produce. Nothing after * the timer line is ever written to the pty. */ +#ifndef RAY_OS_WINDOWS static int run_pty_listen_with_poll(const char* input); +#endif static test_result_t test_repl_pty_timer_fires_while_idle(void) { #ifndef RAY_OS_WINDOWS int rc = run_pty_listen_with_poll("(.time.timer.set 150 1 (fn [t] (exit 7)))\n"); diff --git a/test/test_runtime.c b/test/test_runtime.c index 35160723b..e6bb4f068 100644 --- a/test/test_runtime.c +++ b/test/test_runtime.c @@ -37,8 +37,13 @@ #include #include #include +#ifdef RAY_OS_WINDOWS +#include +#include +#else #include #include +#endif static char* make_tmpdir(void) { char tmpl[] = "/tmp/rayforce-rt-test-XXXXXX"; @@ -70,6 +75,11 @@ static test_result_t test_create_with_sym_absent_is_ok(void) { * passing a path whose parent exists but isn't a directory (ENOTDIR) — * portable across Linux/macOS without needing root or chmod games. */ static test_result_t test_create_with_sym_io_error_surfaces(void) { +#if defined(_WIN32) + /* Win32 reports a path through a regular file as "path not found" + * (ENOENT, the missing-file case), never ENOTDIR. */ + SKIP("no ENOTDIR on Windows"); +#endif char* dir = make_tmpdir(); TEST_ASSERT_NOT_NULL(dir); @@ -1265,9 +1275,7 @@ static test_result_t test_syscov_splayed_set_with_sym_path(void) { } /* cleanup — no free(dir), it's a stack pointer */ - char cmd[512]; - snprintf(cmd, sizeof(cmd), "rm -rf %s", dir); - system(cmd); + (void)ray_test_rm_rf(dir); PASS(); } diff --git a/test/test_splay.c b/test/test_splay.c index 1137cbbd0..34188b468 100644 --- a/test/test_splay.c +++ b/test/test_splay.c @@ -65,9 +65,7 @@ static void splay_teardown(void) { /* Remove temp dir tree */ static void rm_rf(const char* path) { - char cmd[512]; - snprintf(cmd, sizeof(cmd), "rm -rf %s", path); - (void)!system(cmd); + (void)ray_test_rm_rf(path); } /* ========================================================================= @@ -181,9 +179,7 @@ static test_result_t test_load_missing_schema(void) { /* Directory exists but contains no .d file */ const char* dir = TMP_SPLAY_BASE "/no_schema"; rm_rf(dir); - char cmd[512]; - snprintf(cmd, sizeof(cmd), "mkdir -p %s", dir); - (void)!system(cmd); + (void)ray_test_mkdir_p(dir); ray_t* r = ray_splay_load(dir, NULL); /* ray_col_load of missing file returns an error object */ @@ -499,9 +495,7 @@ static test_result_t test_save_sym_error(void) { char sym_as_dir[512]; snprintf(sym_as_dir, sizeof(sym_as_dir), "%s/sym_dir", dir); /* Ensure parent dir exists first */ - char mk[600]; - snprintf(mk, sizeof(mk), "mkdir -p %s", sym_as_dir); - (void)!system(mk); + (void)ray_test_mkdir_p(sym_as_dir); ray_err_t err = ray_splay_save(tbl, dir, sym_as_dir); /* Either succeeds (some impls tolerate it) or returns an error — either @@ -732,8 +726,8 @@ static test_result_t test_save_bulk_with_sym_path(void) { * 19. splay_save_impl: snprintf overflow for the column / ".d" paths. * Requires strlen(dir) >= 1021 so that strlen(dir)+3 >= 1024. * Build a deeply nested path using short components (≤ 50 chars each) - * so the filesystem NAME_MAX (255) is not exceeded, then call mkdir_p - * via system(), then ray_splay_save → snprintf("%s/.d") fires range. + * so the filesystem NAME_MAX (255) is not exceeded, then create it + * with ray_test_mkdir_p, then ray_splay_save → snprintf("%s/.d") fires range. * * Path layout (each component 50 chars): * /tmp/rft_deep_save/ (18 chars) @@ -748,6 +742,10 @@ static test_result_t test_save_dir_path_too_long(void) { * fires under the same condition on Linux PATH_MAX = 4096. Skip * on Darwin — the Linux runner covers the regression. */ SKIP("PATH_MAX=1024 on macOS — deep-mkdir fixture not portable"); +#elif defined(_WIN32) + /* Win32 directory paths stop at MAX_PATH (~260) without long-path + * opt-in, far short of the 1021-char tree. */ + SKIP("MAX_PATH=260 on Windows — deep-mkdir fixture not portable"); #endif /* Construct the nested path in a buffer */ char long_dir[2048]; @@ -771,10 +769,8 @@ static test_result_t test_save_dir_path_too_long(void) { TEST_ASSERT_TRUE((size_t)off >= 1021); /* Create the directory tree so ray_mkdir_p inside save succeeds. - * system("mkdir -p ...") handles arbitrarily deep paths. */ - char mk[4096]; - snprintf(mk, sizeof(mk), "mkdir -p \"%s\"", long_dir); - (void)!system(mk); + * ray_test_mkdir_p handles arbitrarily deep paths. */ + (void)ray_test_mkdir_p(long_dir); int64_t id_v2 = ray_sym_intern("v2long", 6); int64_t raw[] = {1}; @@ -794,9 +790,7 @@ static test_result_t test_save_dir_path_too_long(void) { ray_release(col); ray_release(tbl); /* Cleanup entire nested tree from the base */ - char rm_cmd[256]; - snprintf(rm_cmd, sizeof(rm_cmd), "rm -rf /tmp/rft_deep_save"); - (void)!system(rm_cmd); + (void)ray_test_rm_rf("/tmp/rft_deep_save"); PASS(); } @@ -884,9 +878,7 @@ static test_result_t test_trace_missing_schema(void) { const char* dir = TMP_SPLAY_BASE "/trace_noschema"; rm_rf(dir); /* Create dir without .d file */ - char mk[512]; - snprintf(mk, sizeof(mk), "mkdir -p %s", dir); - (void)!system(mk); + (void)ray_test_mkdir_p(dir); setenv("RAY_CSV_TRACE", "1", 1); ray_t* r = ray_splay_load(dir, NULL); @@ -985,11 +977,14 @@ static test_result_t test_trace_fresh_load(void) { * (with .d last, the column save is the first write to hit the dir). * ========================================================================= */ static test_result_t test_save_schema_write_fails(void) { +#if defined(_WIN32) + /* chmod cannot make a Windows directory refuse new files: the + * read-only attribute is ignored for directories. */ + SKIP("read-only directories are not enforced on Windows"); +#endif const char* dir = TMP_SPLAY_BASE "/no_write_schema"; rm_rf(dir); - char mk[512]; - snprintf(mk, sizeof(mk), "mkdir -p %s", dir); - (void)!system(mk); + (void)ray_test_mkdir_p(dir); /* Make dir read-only so .d cannot be written */ chmod(dir, 0555); diff --git a/test/test_store.c b/test/test_store.c index f4ca10561..1e7d849a7 100644 --- a/test/test_store.c +++ b/test/test_store.c @@ -326,7 +326,7 @@ static test_result_t test_col_mmap_nofile(void) { static test_result_t test_splay_open_roundtrip(void) { /* Clean up any leftover splay dir */ - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); /* Build a 3-column table: I64, F64, I32 */ ray_t* tbl = ray_table_new(4); @@ -398,14 +398,14 @@ static test_result_t test_splay_open_roundtrip(void) { ray_release(tbl); /* Cleanup */ - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); PASS(); } /* ---- test_splay_str_column_roundtrip ----------------------------------- */ static test_result_t test_splay_str_column_roundtrip(void) { - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); ray_t* tbl = ray_table_new(2); TEST_ASSERT_NOT_NULL(tbl); @@ -471,7 +471,7 @@ static test_result_t test_splay_str_column_roundtrip(void) { ray_release(names); ray_release(tbl); - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); PASS(); } @@ -485,7 +485,7 @@ static test_result_t test_splay_str_column_roundtrip(void) { * ---------------------------------------------------------------------- */ static test_result_t test_splay_short_strv_roundtrip(void) { - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); int64_t id_short = ray_sym_intern("short", 5); int64_t id_empty = ray_sym_intern("empty", 5); @@ -547,13 +547,13 @@ static test_result_t test_splay_short_strv_roundtrip(void) { ray_release(tbl); ray_release(tbl2); - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); PASS(); } /* ---- test_splay_dict_column_roundtrip --------------------------------- */ static test_result_t test_splay_dict_column_roundtrip(void) { - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); int64_t ids_raw[] = {1, 2}; ray_t* ids = ray_vec_from_raw(RAY_I64, ids_raw, 2); @@ -608,13 +608,13 @@ static test_result_t test_splay_dict_column_roundtrip(void) { ray_release(tbl); ray_release(ids); ray_release(sched); - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); PASS(); } /* ---- test_splay_empty_list_column_roundtrip --------------------------- */ static test_result_t test_splay_empty_list_column_roundtrip(void) { - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); ray_t* ids = ray_vec_new(RAY_I64, 0); ray_t* who = ray_vec_new(RAY_SYM, 0); @@ -657,14 +657,14 @@ static test_result_t test_splay_empty_list_column_roundtrip(void) { ray_release(ids); ray_release(who); ray_release(sched); - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); PASS(); } /* A deterministic unsupported column must be rejected before an earlier * column can replace the committed generation. */ static test_result_t test_splay_save_preflight_preserves_generation(void) { - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); int64_t k_id = ray_sym_intern("k", 1); int64_t v_id = ray_sym_intern("v", 1); @@ -705,7 +705,7 @@ static test_result_t test_splay_save_preflight_preserves_generation(void) { ray_release(good); ray_release(old_v); ray_release(old_k); - (void)!system("rm -rf " TMP_SPLAY_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_DIR); PASS(); } @@ -838,9 +838,9 @@ static test_result_t test_parted_release(void) { static test_result_t test_part_open(void) { /* Setup: create a 2-partition db with 2 columns each */ - (void)!system("rm -rf " TMP_PART_DB); - (void)!system("mkdir -p " TMP_PART_DB "/2024.01.01/" TMP_TABLE_NAME); - (void)!system("mkdir -p " TMP_PART_DB "/2024.01.02/" TMP_TABLE_NAME); + (void)ray_test_rm_rf(TMP_PART_DB); + (void)ray_test_mkdir_p(TMP_PART_DB "/2024.01.01/" TMP_TABLE_NAME); + (void)ray_test_mkdir_p(TMP_PART_DB "/2024.01.02/" TMP_TABLE_NAME); /* Partition 1: 3 rows */ int64_t raw_a1[] = {10, 20, 30}; @@ -941,7 +941,7 @@ static test_result_t test_part_open(void) { /* Release — should unmap all segments */ ray_release(parted); - (void)!system("rm -rf " TMP_PART_DB); + (void)ray_test_rm_rf(TMP_PART_DB); PASS(); } @@ -949,7 +949,7 @@ static test_result_t test_part_open(void) { /* ray_parted_tables lists the splayed-table subdirectories of the first * partition as a sorted SYM vector usable with ray_read_parted. */ static test_result_t test_parted_tables(void) { - (void)!system("rm -rf " TMP_PART_DB); + (void)ray_test_rm_rf(TMP_PART_DB); /* Two tables (trades, quotes) across two partitions. */ const char* dirs[] = { TMP_PART_DB "/2024.01.01/trades", TMP_PART_DB "/2024.01.01/quotes", @@ -986,16 +986,17 @@ static test_result_t test_parted_tables(void) { /* An existing-but-empty root (no partition dirs) lists no tables — * an empty SYM vector, not an error. */ - (void)!system("rm -rf " TMP_PART_DB "_np && mkdir -p " TMP_PART_DB "_np"); + (void)ray_test_rm_rf(TMP_PART_DB "_np"); + (void)ray_test_mkdir_p(TMP_PART_DB "_np"); ray_t* empty = ray_parted_tables(TMP_PART_DB "_np"); TEST_ASSERT_NOT_NULL(empty); TEST_ASSERT_FALSE(RAY_IS_ERR(empty)); TEST_ASSERT_EQ_I(empty->type, RAY_SYM); TEST_ASSERT_EQ_I(empty->len, 0); ray_release(empty); - (void)!system("rm -rf " TMP_PART_DB "_np"); + (void)ray_test_rm_rf(TMP_PART_DB "_np"); - (void)!system("rm -rf " TMP_PART_DB); + (void)ray_test_rm_rf(TMP_PART_DB); PASS(); } @@ -1662,7 +1663,7 @@ static test_result_t test_sym_col_valid_roundtrip(void) { #define TMP_SYM_PATH "/tmp/rayforce_test_splay_sym_file" static test_result_t test_splay_load_with_sym(void) { - (void)!system("rm -rf " TMP_SPLAY_SYM_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); unlink(TMP_SYM_PATH); /* Intern symbols and build a table with a RAY_SYM column */ @@ -1711,7 +1712,7 @@ static test_result_t test_splay_load_with_sym(void) { ray_release(col_name); ray_release(col_age); ray_release(tbl); - (void)!system("rm -rf " TMP_SPLAY_SYM_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); unlink(TMP_SYM_PATH); unlink(TMP_SYM_PATH ".lk"); PASS(); @@ -1720,7 +1721,7 @@ static test_result_t test_splay_load_with_sym(void) { /* ---- test_splay_load_sym_missing_corrupt ------------------------------- */ static test_result_t test_splay_load_sym_missing_corrupt(void) { - (void)!system("rm -rf " TMP_SPLAY_SYM_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); unlink(TMP_SYM_PATH); /* Intern symbols and build a table with a RAY_SYM column */ @@ -1757,7 +1758,7 @@ static test_result_t test_splay_load_sym_missing_corrupt(void) { ray_release(col); ray_release(tbl); - (void)!system("rm -rf " TMP_SPLAY_SYM_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); unlink(TMP_SYM_PATH); unlink(TMP_SYM_PATH ".lk"); PASS(); @@ -1766,7 +1767,7 @@ static test_result_t test_splay_load_sym_missing_corrupt(void) { /* ---- test_read_splayed_bad_sym_fatal ----------------------------------- */ static test_result_t test_read_splayed_bad_sym_fatal(void) { - (void)!system("rm -rf " TMP_SPLAY_SYM_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); /* Build a simple table (no RAY_SYM columns needed) */ int64_t id_x = ray_sym_intern("x", 1); @@ -1793,7 +1794,7 @@ static test_result_t test_read_splayed_bad_sym_fatal(void) { ray_release(col_x); ray_release(tbl); - (void)!system("rm -rf " TMP_SPLAY_SYM_DIR); + (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); PASS(); } diff --git a/test/test_traverse.c b/test/test_traverse.c index db72da8da..d976d0d4b 100644 --- a/test/test_traverse.c +++ b/test/test_traverse.c @@ -33,7 +33,7 @@ #include #include #include -#ifndef __SANITIZE_ADDRESS__ +#if !defined(__SANITIZE_ADDRESS__) && !defined(_WIN32) /* setrlimit: POSIX only */ #include #endif @@ -3904,7 +3904,7 @@ static test_result_t test_k_shortest_found_path_dup(void) { /* -------------------------------------------------------------------------- * Helper: read VmSize from /proc/self/status; returns 0 on failure. * -------------------------------------------------------------------------- */ -#ifndef __SANITIZE_ADDRESS__ +#if !defined(__SANITIZE_ADDRESS__) && !defined(_WIN32) #include static size_t get_vmsize_bytes(void) { FILE* f = fopen("/proc/self/status", "r"); @@ -4241,7 +4241,7 @@ static test_result_t test_traverse_oom_paths(void) { ray_heap_destroy(); PASS(); } -#endif /* __SANITIZE_ADDRESS__ */ +#endif /* !__SANITIZE_ADDRESS__ && !_WIN32 */ /* -------------------------------------------------------------------------- * Test: exec_expand with SIP bitmap build where rev.n_nodes > fwd.n_nodes. @@ -5725,7 +5725,7 @@ const test_entry_t traverse_entries[] = { { "traverse/k_shortest_large_k", test_k_shortest_large_k, NULL, NULL }, { "traverse/betweenness_with_rev_edges", test_betweenness_with_rev_edges, NULL, NULL }, { "traverse/closeness_sampled_norm", test_closeness_sampled_norm, NULL, NULL }, -#ifndef __SANITIZE_ADDRESS__ +#if !defined(__SANITIZE_ADDRESS__) && !defined(_WIN32) { "traverse/traverse_oom_paths", test_traverse_oom_paths, NULL, NULL }, #endif { "traverse/shortest_path_exceeds_254", test_shortest_path_exceeds_254, NULL, NULL }, From fbf55cf8baaceea02c68eec4591fb7535de5e407 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Tue, 22 Sep 2026 14:58:57 +0300 Subject: [PATCH 17/29] docs: Windows build instructions and platform status Co-Authored-By: Claude Opus 5 (1M context) --- CONTRIBUTING.md | 22 ++++++++++++++++++++++ RELEASE.md | 8 ++++---- docs/docs/guides/memory.md | 4 ---- docs/docs/index.md | 2 +- docs/docs/namespaces/sys.md | 2 +- 5 files changed, 28 insertions(+), 10 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aea56e495..cbbaf68d7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,6 +69,28 @@ a focused subset with: ./rayforce.test -f ``` +A `.rfl` file that needs a POSIX shell or filesystem (fixtures built or +checked through `.sys.exec`, `/proc`, `/dev/tcp`, …) carries the line +`;; @requires: posix`; on Windows the runner reports it as `SKIP` rather +than running it. C tests use `#ifndef RAY_OS_WINDOWS` / `SKIP(...)` for the +same purpose. Prefer the shell-free helpers `ray_test_rm_rf` / +`ray_test_mkdir_p` (`test/test.h`) over `system("rm -rf …")` in C tests. + +### Windows + +Build with the MSYS2 CLANG64 (or MINGW64) toolchain — `pacman -S +mingw-w64-clang-x86_64-clang make` — from an MSYS2 shell or with +`C:\msys64\clang64\bin` and `C:\msys64\usr\bin` on `PATH`: + +```sh +make # debug build (ASan + UBSan) +make test +make release +``` + +The debug binaries load the ASan runtime DLL from `clang64\bin`, so keep it on +`PATH` when running them. + ## Stability tooling Beyond the ASan/UBSan test run, the repo carries a stability toolset. These diff --git a/RELEASE.md b/RELEASE.md index fb141e6e8..76421ebe8 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -136,7 +136,7 @@ Each release publishes, in addition to the source: ## Platform support -Linux and macOS binaries are published today. Windows is not build-ready yet -(IOCP backend is a stub, `main.c`/`heap.c` have unguarded POSIX calls, and the -Makefile has no Windows toolchain path); once ported, add a `windows-latest` row -to the `build` matrix in `.github/workflows/release.yml`. +Linux and macOS binaries are published today. Windows builds and passes the +test suite from source with the MSYS2 CLANG64 toolchain (see CONTRIBUTING.md), +but no Windows binary is published yet; to ship one, add a `windows-latest` +row (MSYS2 CLANG64) to the `build` matrix in `.github/workflows/release.yml`. diff --git a/docs/docs/guides/memory.md b/docs/docs/guides/memory.md index 998c1d2d6..a0050195e 100644 --- a/docs/docs/guides/memory.md +++ b/docs/docs/guides/memory.md @@ -104,10 +104,6 @@ total-mem | 16777216000 | `page-size` | OS page size in bytes | | `total-mem` | Total physical RAM in bytes | -!!! note "Note" - - On Windows, only `cores` is currently reported. - ## 5. Progress Monitoring Long-running queries display a progress bar automatically in the REPL. The bar appears after approximately 2 seconds of execution and shows real-time feedback. diff --git a/docs/docs/index.md b/docs/docs/index.md index 6550f46a3..162253e75 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -2,7 +2,7 @@ Embeddable columnar analytics and graph traversal engine in pure C. -Rayforce combines morsel-driven vectorized execution, a multi-pass query optimizer, and a native CSR graph engine in a single pipeline. It is queried through the **Rayfall** language, exposes a C API for embedding, and runs on Linux and macOS (Windows is planned — the IOCP backend is still a stub). +Rayforce combines morsel-driven vectorized execution, a multi-pass query optimizer, and a native CSR graph engine in a single pipeline. It is queried through the **Rayfall** language, exposes a C API for embedding, and runs on Linux and macOS, and builds on Windows from source (MSYS2 CLANG64). [Quick Start](getting-started/quick-start.md){ .md-button .md-button--primary } [Functions Reference](language/functions.md){ .md-button } diff --git a/docs/docs/namespaces/sys.md b/docs/docs/namespaces/sys.md index 5e13d189b..f6eefbffb 100644 --- a/docs/docs/namespaces/sys.md +++ b/docs/docs/namespaces/sys.md @@ -75,7 +75,7 @@ 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, 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. +Signature: `(.sys.info)`. Returns `{cores: i64, page-size: i64, total-mem: i64, pid: i64, hostname: str}` on every platform (on Windows from `GetSystemInfo` / `GlobalMemoryStatusEx`). ```lisp (.sys.info) From cfdbb34ed95a25789d173ef7687ad5aad2f021e3 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Wed, 23 Sep 2026 13:23:54 +0300 Subject: [PATCH 18/29] fix: readable REPL prompt and CPU name in the banner on Windows No console font Windows ships has U+2023 (checked Consolas, Cascadia Mono, Lucida Console, Courier New) and the classic console does no font fallback, so the prompt rendered as '?'. Use the nearest filled triangle they all do have, U+25BA, which is also three UTF-8 bytes. The banner's CPU line said 'unknown': read ProcessorNameString instead. Co-Authored-By: Claude Opus 5 (1M context) --- docs/docs/getting-started/quick-start.md | 2 +- src/app/repl.c | 13 ++++++++++++- src/app/term.c | 12 +++++++++++- test/test_term.c | 7 ++++++- 4 files changed, 30 insertions(+), 4 deletions(-) diff --git a/docs/docs/getting-started/quick-start.md b/docs/docs/getting-started/quick-start.md index 73a2dc04a..143da2053 100644 --- a/docs/docs/getting-started/quick-start.md +++ b/docs/docs/getting-started/quick-start.md @@ -58,7 +58,7 @@ The Rayfall REPL provides an interactive environment with syntax highlighting, b ./rayforce ``` -You will see the `‣` prompt (a green triangle bullet): +You will see the `‣` prompt (a green triangle bullet; `►` on Windows, whose console fonts have no `‣`): ```text ‣ diff --git a/src/app/repl.c b/src/app/repl.c index 7036c63c4..b5cd32d86 100644 --- a/src/app/repl.c +++ b/src/app/repl.c @@ -353,7 +353,18 @@ static void get_cpu_name(char* buf, size_t sz) { if (sysctlbyname("machdep.cpu.brand_string", buf, &len, NULL, 0) != 0) snprintf(buf, sz, "unknown"); #elif defined(RAY_OS_WINDOWS) - snprintf(buf, sz, "unknown"); + /* The brand string the firmware reported, same text as /proc/cpuinfo's + * "model name"; it is padded with trailing spaces, so trim them. */ + DWORD n = (DWORD)sz; + if (RegGetValueA(HKEY_LOCAL_MACHINE, + "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", + "ProcessorNameString", RRF_RT_REG_SZ, NULL, + buf, &n) == ERROR_SUCCESS) { + size_t len = strlen(buf); + while (len > 0 && buf[len - 1] == ' ') buf[--len] = '\0'; + } else { + snprintf(buf, sz, "unknown"); + } #else snprintf(buf, sz, "unknown"); #endif diff --git a/src/app/term.c b/src/app/term.c index 79509f18a..3b1560a69 100644 --- a/src/app/term.c +++ b/src/app/term.c @@ -1517,8 +1517,18 @@ int32_t ray_term_count_unmatched(ray_term_t* term) { /* ===== Prompt ===== */ -/* Green ‣ (U+2023) prompt, matching Rayforce style */ +/* Green ‣ (U+2023) prompt, matching Rayforce style. + * + * No console font Windows ships has U+2023 — not Consolas, Cascadia Mono, + * Lucida Console or Courier New — and the classic console does no font + * fallback, so the prompt renders as "?" there. Windows uses ► (U+25BA), + * the nearest filled triangle all four of them do have; it is also three + * UTF-8 bytes, so the byte and visual widths below are unchanged. */ +#if defined(RAY_OS_WINDOWS) +#define PROMPT_STR "\033[32m\xe2\x96\xba\033[0m " +#else #define PROMPT_STR "\033[32m\xe2\x80\xa3\033[0m " +#endif #define PROMPT_LEN 13 /* ESC[32m (5) + ‣ (3) + ESC[0m (4) + space (1) = 13 bytes */ #define PROMPT_VIS 2 /* visual: ‣ + space */ #define CONT_PROMPT_STR "\033[90m\xe2\x80\xa6\033[0m " /* gray … (U+2026) */ diff --git a/test/test_term.c b/test/test_term.c index f29ddc086..319c2f983 100644 --- a/test/test_term.c +++ b/test/test_term.c @@ -1185,7 +1185,12 @@ static test_result_t test_term_prompt_emits_bytes(void) { ray_term_prompt(t); fflush(stdout); int32_t n = capture_end(saved, path, cap, sizeof cap); - int saw_arrow = strstr(cap, "\xe2\x80\xa3") != NULL; /* ‣ */ + /* ‣ (U+2023), or ► (U+25BA) where no console font has ‣ — see term.c */ +#if defined(RAY_OS_WINDOWS) + int saw_arrow = strstr(cap, "\xe2\x96\xba") != NULL; +#else + int saw_arrow = strstr(cap, "\xe2\x80\xa3") != NULL; +#endif int saw_green = strstr(cap, "\033[32m") != NULL; TEST_ASSERT_FMT(n > 0, "no prompt output"); TEST_ASSERT_FMT(saw_arrow, "missing ‣ arrow in prompt: bytes=%d", n); From bb6b5d8875ad6eb4ed3b8b57d15e3b0e8771019b Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Wed, 23 Sep 2026 13:32:14 +0300 Subject: [PATCH 19/29] bench: build the micro-benchmarks on Windows, record a Windows/Linux check alloc and agg_v2 read peak RSS through getrusage; use GetProcessMemoryInfo there. windows_vs_linux.md records the numbers the port was checked against. Co-Authored-By: Claude Opus 5 (1M context) --- bench/agg_v2/main.c | 14 ++++++- bench/alloc/main.c | 14 ++++++- bench/bottleneck/windows_vs_linux.md | 56 ++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 bench/bottleneck/windows_vs_linux.md diff --git a/bench/agg_v2/main.c b/bench/agg_v2/main.c index 401365ce9..908fc3f44 100644 --- a/bench/agg_v2/main.c +++ b/bench/agg_v2/main.c @@ -46,7 +46,13 @@ #include #include #include -#include +#if defined(_WIN32) +# define WIN32_LEAN_AND_MEAN +# include +# include +#else +# include +#endif /* ---------- timing ---------- */ static double now_ms(void) { @@ -69,12 +75,18 @@ static double vmin(const double* arr, int n) { return m; } static long max_rss_kb(void) { +#if defined(_WIN32) + PROCESS_MEMORY_COUNTERS pmc; + if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) return 0; + return (long)(pmc.PeakWorkingSetSize / 1024); +#else struct rusage ru; getrusage(RUSAGE_SELF, &ru); #if defined(__APPLE__) return ru.ru_maxrss / 1024; #else return ru.ru_maxrss; #endif +#endif } /* ---------- deterministic PRNG (splitmix64) ---------- */ diff --git a/bench/alloc/main.c b/bench/alloc/main.c index 9bbefc124..3294e9189 100644 --- a/bench/alloc/main.c +++ b/bench/alloc/main.c @@ -11,7 +11,13 @@ #include #include #include -#include +#if defined(_WIN32) +# define WIN32_LEAN_AND_MEAN +# include +# include +#else +# include +#endif static double now_s(void) { struct timespec ts; @@ -66,6 +72,11 @@ static void* consumer(void* _) { } static long max_rss_kb(void) { +#if defined(_WIN32) + PROCESS_MEMORY_COUNTERS pmc; + if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) return 0; + return (long)(pmc.PeakWorkingSetSize / 1024); +#else struct rusage ru; getrusage(RUSAGE_SELF, &ru); /* Linux: ru_maxrss is KB; macOS: bytes. Normalize to KB. */ #if defined(__APPLE__) @@ -73,6 +84,7 @@ static long max_rss_kb(void) { #else return ru.ru_maxrss; #endif +#endif } int main(void) { diff --git a/bench/bottleneck/windows_vs_linux.md b/bench/bottleneck/windows_vs_linux.md new file mode 100644 index 000000000..92874cf84 --- /dev/null +++ b/bench/bottleneck/windows_vs_linux.md @@ -0,0 +1,56 @@ +# Windows vs Linux sanity check + +Not a performance study: a coarse check that the Windows port lands in the +same ballpark as Linux, run while porting (`serhii/windows-port`). The two +sides do not share a compiler, an allocator-visible kernel, or a filesystem, +so only order-of-magnitude gaps are meaningful here. + +## Environment + +**CPU**: 11th Gen Intel Core i7 (8 logical cores) — one laptop, both runs +**Windows**: Windows 11, clang 20.1.8 (MSYS2 CLANG64), 32 GiB +**Linux**: WSL2 (kernel 6.6.87.2-microsoft-standard-WSL2, Ubuntu 24.04), gcc 13.3.0, 15 GiB to the VM +**Build**: `make release` both sides (`-O3 -march=native`, no sanitizers — `nm bench-alloc | grep -ci asan` → 0) + +WSL2 is a virtual machine with its own memory budget and a virtualised +filesystem; that alone moves I/O and page-fault numbers. Treat the file-backed +rows as indicative only. + +## Allocator micro-benchmark (`bench/alloc`) + +| case | Windows | Linux | +|------|---------|-------| +| atom-64B | 85.7 Mops/s | 80.9 Mops/s | +| vec-256B | 85.5 Mops/s | 78.6 Mops/s | +| morsel-8K | 88.2 Mops/s | 80.3 Mops/s | +| morsel-16K | 88.4 Mops/s | 78.2 Mops/s | +| large-1M | 62.7 Mops/s | 56.4 Mops/s | +| producer-consumer | 9.2 Mops/s, peak RSS 28 MB | 6.0 Mops/s, peak RSS 68 MB | + +## Engine operations (5M rows, `timeit`, median of 3) + +| operation | Windows (ms) | Linux (ms) | Win/Lin | +|-----------|-------------:|-----------:|--------:| +| arith-f64 (`sum (* f 1.5)`) | 7.94 | 5.10 | 1.56 | +| sort-i64 | 9.89 | 8.78 | 1.13 | +| distinct-i64 | 2.96 | 4.69 | 0.63 | +| group-by sym | 3.44 | 3.93 | 0.88 | +| select where | 7.13 | 14.14 | 0.50 | +| inner-join | 108.6 | 108.3 | 1.00 | +| csv write (5M rows) | 2201 | 1654 | 1.33 | +| csv read | 155 | 186 | 0.83 | +| splayed set | 509 | 580 | 0.88 | +| splayed get + count | 5.9 | 0.28 | 21 | + +`sum`/`avg` are omitted: both platforms report ~0.005 ms, the DAG elides them. + +## Reading + +Compute paths agree within a factor of ~1.6 either way, which is compiler and +noise territory, and the allocator is slightly ahead on Windows. + +The one real gap is `splayed get + count` (5.9 ms vs 0.28 ms). It opens and +maps one file per column, so it measures file-open cost, not the engine: +`CreateFileA` + `CreateFileMapping` + `MapViewOfFile` per column, plus +whatever on-access scanning is installed. The absolute cost is small and it is +paid per table open, but a wide table opened in a loop would feel it. From fb392d92cb104f58904bbce23b5594f5f5612599 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Wed, 23 Sep 2026 14:11:18 +0300 Subject: [PATCH 20/29] bench: record the recent perf benches on Windows vs Linux Co-Authored-By: Claude Opus 5 (1M context) --- bench/bottleneck/windows_vs_linux.md | 36 ++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/bench/bottleneck/windows_vs_linux.md b/bench/bottleneck/windows_vs_linux.md index 92874cf84..c7b0e30a7 100644 --- a/bench/bottleneck/windows_vs_linux.md +++ b/bench/bottleneck/windows_vs_linux.md @@ -54,3 +54,39 @@ maps one file per column, so it measures file-open cost, not the engine: `CreateFileA` + `CreateFileMapping` + `MapViewOfFile` per column, plus whatever on-access scanning is installed. The absolute cost is small and it is paid per table open, but a wide table opened in a loop would feel it. + +## The benches recent PRs shipped + +Same binaries, built from the release objects on each side. + +**`bench/join_nullfree` (#598, null-free key fast path).** The optimisation +engages on Windows — the `nullfree` counter advances on the null-free cases +and stays put on the nullable one, as on Linux. + +| case | Windows median (baseline → fast) | Linux median | +|------|---------------------------------|--------------| +| SYM2 | 355.3 → 336.0 ms (-5.4%) | 413.6 → 408.4 ms (-1.3%) | +| SYM2-NULL (must not fire) | 348.2 → 349.8 ms (+0.5%) | 407.1 → 412.9 ms (+1.4%) | +| I64 | 102.7 → 89.2 ms (-13.2%) | 100.9 → 96.3 ms (-4.6%) | + +**`bench/join_dup` (duplicate-key fallback).** The pathological case is fixed +on both: CATASTROPHIC-INNER post-fix ~170 ms on Windows and ~230 ms on Linux, +against ~2.6 s pre-fix (Windows) — the same order-of-magnitude win. + +**`bench/join_buildside` (build-side swap).** The swap fires on Windows and +pays off by the same factor: MANY-TO-MANY 207 ms swapped vs 494 ms legacy +(2.4x); Linux 188 vs 431 (2.3x). HEAVY-DUP-WIN: 1.7 s vs 6.2 s (Windows), +1.8 s vs 8.2 s (Linux). + +**`bench/idx_route` Q3** (1000 lookups/rep): indexed 0.014 ms/batch on +Windows, 0.009 on Linux; the unindexed control is 0.004 on both. + +Not runnable as-is: + +- `bench/group_pushdown` and `bench/agg_v2` no longer compile **on either + platform** — they use `ray_op.inputs` and `ray_group2/3`, which the engine + no longer has. Pre-existing, unrelated to the port. +- `bench/groupby_shapes/*.py` needs python3, which a stock Windows lacks; the + `.rfl` cases in that directory run directly under `rayforce` on both. +- `scripts/soak.sh` and `scripts/fuzz-seed-*.sh` are bash and stay POSIX-only + (the fuzzing runtime is Linux-only anyway, see the Makefile). From 55430068b15aab977ae0b74b1703c7c136be4676 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Wed, 23 Sep 2026 14:43:41 +0300 Subject: [PATCH 21/29] fix(format): render i64 at full width, not through 32-bit long MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Interpolation (format/println), print and the pivot / column-name helpers formatted an i64 with "%ld" and a (long) cast. long is 64-bit on LP64 and 32-bit on Windows, so there 10^18 printed as -1486618624 and a pivot keyed on values above 2^31 produced truncated column NAMES — a data defect, not only a display one. Use PRId64 throughout; regression test included. Co-Authored-By: Claude Opus 5 (1M context) --- src/ops/builtins.c | 8 ++++---- src/ops/pivot.c | 5 +++-- src/ops/tblop.c | 4 ++-- test/rfl/regress/i64_text_width.rfl | 18 ++++++++++++++++++ 4 files changed, 27 insertions(+), 8 deletions(-) create mode 100644 test/rfl/regress/i64_text_width.rfl diff --git a/src/ops/builtins.c b/src/ops/builtins.c index 18dd8d35b..9b2fb31bf 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -110,7 +110,7 @@ void ray_lang_print(FILE* fp, ray_t* val) { return; } switch (val->type) { - case -RAY_I64: fprintf(fp, "%ld", (long)val->i64); break; + case -RAY_I64: fprintf(fp, "%" PRId64, val->i64); break; case -RAY_F64: { double fv = val->f64; fv = clear_neg_zero(fv); @@ -142,8 +142,8 @@ void ray_lang_print(FILE* fp, ray_t* val) { break; } case RAY_TABLE: - fprintf(fp, "", - (long)ray_table_nrows(val), (long)ray_table_ncols(val)); + fprintf(fp, "
", + ray_table_nrows(val), ray_table_ncols(val)); break; case RAY_UNARY: case RAY_BINARY: case RAY_VARY: { const char* name = ray_fn_name(val); @@ -204,7 +204,7 @@ static char* fmt_interpolate(const char* fmt, size_t flen, ray_t** args, int64_t RAY_ATOM_IS_NULL(a)) { tlen = snprintf(tmp, sizeof(tmp), "%s", null_literal_str(a->type)); } else if (a->type == -RAY_I64) { - tlen = snprintf(tmp, sizeof(tmp), "%ld", (long)a->i64); + tlen = snprintf(tmp, sizeof(tmp), "%" PRId64, a->i64); } else if (a->type == -RAY_F64) { double fv = a->f64; fv = clear_neg_zero(fv); diff --git a/src/ops/pivot.c b/src/ops/pivot.c index f3b6eb52c..0be4a5579 100644 --- a/src/ops/pivot.c +++ b/src/ops/pivot.c @@ -21,6 +21,7 @@ * SOFTWARE. */ +#include #include "ops/internal.h" #include "ops/hash.h" #include "ops/idxop.h" @@ -1910,9 +1911,9 @@ ray_t* exec_pivot(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { len = snprintf(buf, sizeof(buf), "%s", pval ? "true" : "false"); } else if (pt == RAY_I64 || pt == RAY_I32 || pt == RAY_I16 || pt == RAY_DATE || pt == RAY_TIME || pt == RAY_TIMESTAMP) { - len = snprintf(buf, sizeof(buf), "%ld", (long)pval); + len = snprintf(buf, sizeof(buf), "%" PRId64, pval); } else { - len = snprintf(buf, sizeof(buf), "col%ld", (long)pval); + len = snprintf(buf, sizeof(buf), "col%" PRId64, pval); } col_sym = ray_sym_intern(buf, (size_t)len); } diff --git a/src/ops/tblop.c b/src/ops/tblop.c index 7da33443a..375d4ae3b 100644 --- a/src/ops/tblop.c +++ b/src/ops/tblop.c @@ -627,7 +627,7 @@ static ray_t* pivot_fn_impl(ray_t* tbl, ray_t* index_arg, ray_t* pivot_col_name, if (pval->type == -RAY_SYM) { col_sym = pval->i64; } else if (pval->type == -RAY_I64) { - char buf[64]; int len = snprintf(buf, sizeof(buf), "%ld", (long)pval->i64); + char buf[64]; int len = snprintf(buf, sizeof(buf), "%" PRId64, pval->i64); col_sym = ray_sym_intern(buf, (size_t)len); } else if (pval->type == -RAY_F64) { double fv = clear_neg_zero(pval->f64); @@ -636,7 +636,7 @@ static ray_t* pivot_fn_impl(ray_t* tbl, ray_t* index_arg, ray_t* pivot_col_name, } else if (pval->type == -RAY_BOOL) { col_sym = ray_sym_intern(pval->b8 ? "true" : "false", pval->b8 ? 4 : 5); } else { - char buf[64]; int len = snprintf(buf, sizeof(buf), "col%ld", (long)pval->i64); + char buf[64]; int len = snprintf(buf, sizeof(buf), "col%" PRId64, pval->i64); col_sym = ray_sym_intern(buf, (size_t)len); } if (a1) ray_release(pval); diff --git a/test/rfl/regress/i64_text_width.rfl b/test/rfl/regress/i64_text_width.rfl new file mode 100644 index 000000000..8ae3affc2 --- /dev/null +++ b/test/rfl/regress/i64_text_width.rfl @@ -0,0 +1,18 @@ +;; An i64 must survive every text path in full 64-bit width. The +;; interpolation, print and pivot/column-name helpers used to render it with +;; "%ld" + (long), which is 32-bit on Windows (LLP64): 10^18 came back as +;; -1486618624, and a pivot keyed on large integers produced wrong column +;; names — a data defect, not just a display one. + +(format "%" 1000000000000000000) -- "1000000000000000000" +(format "%" 9223372036854775807) -- "9223372036854775807" +(format "%" -9223372036854775806) -- "-9223372036854775806" +(format "%" (count (til 3000000000))) -- "3000000000" +(format "%,%" 4294967296 4294967297) -- "4294967296,4294967297" + +;; as 'STR shares none of that code — pin it as the independent oracle. +(== (format "%" 1099511627776) (as 'STR 1099511627776)) -- true + +;; pivot builds column names from the key values +(set _t64 (table [g k v] (list ['a 'a 'b] [4294967296 4294967297 4294967296] [1.0 2.0 3.0]))) +(cols (pivot _t64 'g 'k 'v sum)) -- ['g '4294967296 '4294967297] From 7d370d481d72d67faf2a1f7ba405c737c9d43440 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Wed, 23 Sep 2026 16:17:25 +0300 Subject: [PATCH 22/29] fix(crash): format the banner with snprintf instead of macro string splicing The banner was spliced from string literals and the RAYFORCE_VERSION / RAYFORCE_GIT_COMMIT macros inside #ifdef arms; without the -D values a static analyser reads the literal followed by the bare macro name as two adjacent tokens and reports a syntax error. Format it with one snprintf at install time (the handler itself still never formats), with the macros defaulting to empty strings. Output unchanged. Co-Authored-By: Claude Fable 5.1 --- src/core/crash.c | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/core/crash.c b/src/core/crash.c index 76f894b2a..41da28900 100644 --- a/src/core/crash.c +++ b/src/core/crash.c @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -71,21 +72,20 @@ static void cw_int(int v) { /* Banner precomputed at install time so the handler doesn't format it. */ static char g_banner[128]; -static void crash_banner_init(void) { - const char* v = -#ifdef RAYFORCE_VERSION - "rayforce " RAYFORCE_VERSION -#else - "rayforce" +#ifndef RAYFORCE_VERSION +#define RAYFORCE_VERSION "" #endif -#ifdef RAYFORCE_GIT_COMMIT - " (" RAYFORCE_GIT_COMMIT ")" +#ifndef RAYFORCE_GIT_COMMIT +#define RAYFORCE_GIT_COMMIT "" #endif - "\n"; - size_t vl = strlen(v); - if (vl >= sizeof(g_banner)) vl = sizeof(g_banner) - 1; - memcpy(g_banner, v, vl); - g_banner[vl] = '\0'; + +static void crash_banner_init(void) { + const char* ver = RAYFORCE_VERSION; + const char* rev = RAYFORCE_GIT_COMMIT; + int n = snprintf(g_banner, sizeof(g_banner), "rayforce%s%s%s%s%s\n", + ver[0] ? " " : "", ver, + rev[0] ? " (" : "", rev, rev[0] ? ")" : ""); + if (n < 0) g_banner[0] = '\0'; } #if defined(_WIN32) From 6b4de91312000ab4b322b5344b3efd9b28338510 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Wed, 23 Sep 2026 16:28:19 +0300 Subject: [PATCH 23/29] test(regress): drop the 24 GB til from the i64 width probe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `til` is eager, so counting a three-billion-element range built a 24 GB vector for no extra coverage — the neighbouring literals already cross 2^31, 2^32 and 2^63. Co-Authored-By: Claude Fable 5.1 --- test/rfl/regress/i64_text_width.rfl | 1 - 1 file changed, 1 deletion(-) diff --git a/test/rfl/regress/i64_text_width.rfl b/test/rfl/regress/i64_text_width.rfl index 8ae3affc2..cde583f7e 100644 --- a/test/rfl/regress/i64_text_width.rfl +++ b/test/rfl/regress/i64_text_width.rfl @@ -7,7 +7,6 @@ (format "%" 1000000000000000000) -- "1000000000000000000" (format "%" 9223372036854775807) -- "9223372036854775807" (format "%" -9223372036854775806) -- "-9223372036854775806" -(format "%" (count (til 3000000000))) -- "3000000000" (format "%,%" 4294967296 4294967297) -- "4294967296,4294967297" ;; as 'STR shares none of that code — pin it as the independent oracle. From cf9aa2188f8f5836e4e146abee75ad5dd3917441 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Thu, 24 Sep 2026 21:00:26 +0300 Subject: [PATCH 24/29] fix(mem): hand workers their freed blocks back at the end of every dispatch (#621) * fix(mem): hand workers their freed blocks back at the end of every dispatch A parallel operator's workers allocate per-task buffers from their own heaps and the main thread frees them once the dispatch has completed, so each block lands on the owning worker's foreign list. The owner drained that list only when an allocation found its freelists empty, which a warm worker with a partly cut pool rarely does: it kept splitting fresh pool space instead, touching new pages every round while its own freed blocks waited. Under a steady stream of such operators (a join against a large table per incoming batch) the process grew by a full 32 MB pool per worker before any block was reused, and only the idle decay, which needs the process to sit quiet, drained it earlier. The dispatcher now drains every registered heap's foreign list at the end of each parallel region (ray_heap_reclaim_workers), under the same conditions the idle decay already relies on: the flag is clear, so every worker has finished its last task and neither allocates nor frees until the next dispatch. The blocks go back to freelists only, no pages are released, so the next round reuses them without faulting. Tests: heap/reclaim_workers_drains_owner (a block owned by one heap and freed from another leaves the owner's list on reclaim and is handed out again at the same address, no new pool) and pool/dispatch_reclaims_worker_blocks (blocks allocated by real workers and freed by the main thread are back with their owners by the end of the next dispatch). Co-Authored-By: Claude Fable 5.1 * fix(mem): reclaim only the pool's own worker heaps after a dispatch The heap registry holds every thread that ever allocated, not only pool workers: a server's poll thread or an embedding's own threads are there too, and they may be allocating while a dispatch on another thread ends. Draining such a heap's foreign list from the dispatcher coalesces into freelists their owner is using at that moment. Only a pool worker parked on its semaphore is known to touch nothing of its own until the next dispatch, so each worker now publishes its heap in the pool (worker_heaps, set after ray_heap_init, cleared before it exits) and the dispatcher reclaims exactly those, plus its own list on its own thread. ray_heap_reclaim_worker takes one heap; the registry walk is gone, which also removes its per-dispatch scan of every registry slot. The heap test now checks the block's bytes leave the owner's books only on reclaim, instead of expecting the next allocation at the same address; the pool test reads the worker heaps the pool publishes. Co-Authored-By: Claude Fable 5.1 * test(pool,heap): make the reclaim tests independent of worker start-up and adopted heaps The pool test read a worker's heap slot right after ray_pool_create, which returns before the workers have started, and passed vacuously when the main thread took every task. It now waits for each worker to publish its heap, records which worker allocated each block and repeats the round until a worker really allocated something, then checks that the next dispatch left no worker with a foreign list. The heap test drains whatever an adopted heap already held before taking its baseline. Co-Authored-By: Claude Fable 5.1 * fix(pool): allocate the worker heap slots without an _Atomic cast cppcheck cannot build an AST for a cast to `_Atomic(void*)*` and fails the static-analysis run on it. The cast is not needed in C: ray_sys_alloc returns void*, which converts to the slot pointer type on its own, and sizeof(*pool->worker_heaps) names the element size without spelling the type. Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- src/core/pool.c | 43 ++++++++++++++++++++++++++++--- src/core/pool.h | 10 ++++++++ src/mem/heap.c | 38 +++++++++++++++++++++++++++ src/mem/heap.h | 7 +++++ test/test_heap.c | 63 +++++++++++++++++++++++++++++++++++++++++++++ test/test_pool.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 225 insertions(+), 3 deletions(-) diff --git a/src/core/pool.c b/src/core/pool.c index c3cac8002..904600fdb 100644 --- a/src/core/pool.c +++ b/src/core/pool.c @@ -82,6 +82,10 @@ static void worker_loop(void* arg) { * by an earlier worker (pools and slab caches intact). */ ray_heap_init(); ray_rc_sync = true; /* workers always use atomic refcounting */ + /* Publish the heap for the dispatcher's post-dispatch reclaim (release + * pairs with its acquire: the heap is fully initialised when seen). */ + atomic_store_explicit(&pool->worker_heaps[wctx.worker_id - 1], ray_tl_heap, + memory_order_release); for (;;) { ray_sem_wait(&pool->work_ready); @@ -109,9 +113,10 @@ static void worker_loop(void* arg) { memory_order_acq_rel); } - /* No ray_heap_gc() here — removing worker GC between dispatch rounds - * ensures main can safely modify worker heaps in ray_parallel_end(). - * Eager madvise in heap_coalesce already releases pages on free. */ + /* No ray_heap_gc() here — a worker that neither allocates nor frees + * between its last pending-- and sem_wait is what lets the + * dispatcher drain worker foreign lists (ray_heap_reclaim_workers) + * and the idle decay walk worker heaps once the flag is clear. */ } /* Abandon, do not destroy. Another thread may still hold — and later @@ -120,9 +125,26 @@ static void worker_loop(void* arg) { * a heap that could be unregistered and munmapped underneath that lookup * would be a use-after-free. The heap stays registered with its pools * and is adopted by the next worker thread that starts. */ + atomic_store_explicit(&pool->worker_heaps[wctx.worker_id - 1], NULL, + memory_order_release); ray_heap_abandon(); } +/* End of a parallel region: hand every worker the blocks other threads + * freed to it since the last dispatch, so the next round reuses them + * instead of cutting fresh pool space (issue #619). Workers only — they + * are parked on the semaphore and touch nothing of their own until the + * next dispatch; any other registered heap may belong to a live thread. + * The dispatcher's own list is drained too, on its own thread. */ +static void pool_reclaim_worker_heaps(ray_pool_t* pool) { + for (uint32_t i = 0; i < pool->n_workers; i++) { + ray_heap_t* h = (ray_heap_t*)atomic_load_explicit(&pool->worker_heaps[i], + memory_order_acquire); + if (h) ray_heap_reclaim_worker(h); + } + ray_heap_flush_foreign(); +} + /* -------------------------------------------------------------------------- * ray_pool_create * -------------------------------------------------------------------------- */ @@ -192,6 +214,15 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, ray_sys_free(pool->tasks); return RAY_ERR_OOM; } + pool->worker_heaps = ray_sys_alloc(n_workers * sizeof(*pool->worker_heaps)); + if (!pool->worker_heaps) { + ray_sys_free(pool->threads); + ray_sem_destroy(&pool->work_ready); + ray_sys_free(pool->tasks); + return RAY_ERR_OOM; + } + for (uint32_t i = 0; i < n_workers; i++) + atomic_store_explicit(&pool->worker_heaps[i], NULL, memory_order_relaxed); for (uint32_t i = 0; i < n_workers; i++) { worker_ctx_t* wctx = (worker_ctx_t*)ray_sys_alloc(sizeof(worker_ctx_t)); @@ -204,6 +235,7 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, for (uint32_t j = 0; j < i; j++) { ray_thread_join(pool->threads[j]); } + ray_sys_free(pool->worker_heaps); ray_sys_free(pool->threads); ray_sem_destroy(&pool->work_ready); ray_sys_free(pool->tasks); @@ -222,6 +254,7 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, for (uint32_t j = 0; j < i; j++) { ray_thread_join(pool->threads[j]); } + ray_sys_free(pool->worker_heaps); ray_sys_free(pool->threads); ray_sem_destroy(&pool->work_ready); ray_sys_free(pool->tasks); @@ -255,6 +288,7 @@ void ray_pool_free(ray_pool_t* pool) { ray_thread_join(pool->threads[i]); } + ray_sys_free(pool->worker_heaps); ray_sys_free(pool->threads); ray_sem_destroy(&pool->work_ready); ray_sys_free(pool->tasks); @@ -392,6 +426,8 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, * be between pending-- and sem_wait. */ atomic_thread_fence(memory_order_seq_cst); ray_rc_sync = false; + + pool_reclaim_worker_heaps(pool); } /* One round of ray_pool_dispatch_n: tasks [first, first+n_tasks), each handed @@ -466,6 +502,7 @@ static void dispatch_n_round(ray_pool_t* pool, ray_pool_fn fn, void* ctx, atomic_store_explicit(&ray_parallel_flag, 0, memory_order_release); atomic_thread_fence(memory_order_seq_cst); ray_rc_sync = false; + pool_reclaim_worker_heaps(pool); } /* -------------------------------------------------------------------------- diff --git a/src/core/pool.h b/src/core/pool.h index db0ea49f3..f9914df02 100644 --- a/src/core/pool.h +++ b/src/core/pool.h @@ -52,6 +52,16 @@ struct ray_pool { uint32_t n_workers; /* number of background threads (nproc - 1) */ _Atomic(uint32_t) shutdown; + /* Heap of each worker thread [n_workers] (a ray_heap_t*), published by + * the worker once ray_heap_init has run and cleared before it exits. + * The dispatcher reads them at the end of every parallel region to hand + * each worker the blocks other threads freed to it (ray_heap_reclaim_ + * worker). Only these heaps: a worker parked on the semaphore is the + * one thread known to touch nothing of its own until the next dispatch, + * which is what makes draining its list from here sound. NULL until + * the worker is up. */ + _Atomic(void*)* worker_heaps; + /* SPMC task ring (single producer = main, multi consumer = workers + main). * * Claiming uses two MONOTONIC 64-bit cursors that are never reset, which diff --git a/src/mem/heap.c b/src/mem/heap.c index 906ef225e..452440569 100644 --- a/src/mem/heap.c +++ b/src/mem/heap.c @@ -2793,6 +2793,44 @@ void ray_heap_flush_foreign(void) { heap_drain_foreign(h); } +/* -------------------------------------------------------------------------- + * Post-dispatch reclaim (dispatcher side) + * + * A parallel operator's workers allocate their per-task buffers from their + * own heaps and the main thread frees them once the dispatch has completed, + * so every such block ends up on the owning worker's foreign list. The + * owner takes that list back only when an allocation finds its freelists + * empty at the order it needs — and a warm worker with a partly cut pool + * rarely does: it keeps splitting fresh pool space instead, touching new + * pages every round while its own freed blocks wait on the list. Under a + * steady stream of such operators the process grows by one full pool per + * worker before any block is reused, and nothing short of the idle decay + * (which needs the process to sit quiet) drains it earlier. + * + * So the dispatcher drains each worker's list at the end of each parallel + * region. The conditions are the ones the decay sweep relies on: the flag + * is clear, so every worker has done its last pending-- and is claiming + * nothing, allocating nothing and freeing nothing until the next dispatch; + * a concurrent push onto a foreign list from some other thread is safe + * because the drain takes the whole list in one exchange and leaves later + * arrivals for the next round. Only pool workers qualify: the registry + * also holds the heaps of other live threads (a server's poll thread, an + * embedding's own threads), whose freelists only their owner may touch, so + * the pool names the heaps rather than this walking the registry. No + * pages are released here — the blocks only go back to freelists, so the + * next round reuses them without faulting. Cost: one load per worker and + * the coalescing of whatever was freed cross-thread since the last + * dispatch, work the owner would otherwise do on its next dry allocation. + * -------------------------------------------------------------------------- */ + +void ray_heap_reclaim_worker(ray_heap_t* h) { + if (!h) return; + if (atomic_load_explicit(&ray_parallel_flag, memory_order_acquire) != 0) + return; + if (!atomic_load_explicit(&h->foreign, memory_order_relaxed)) return; + heap_drain_foreign(h); +} + /* -------------------------------------------------------------------------- * Pending-merge queue (lock-free LIFO) * diff --git a/src/mem/heap.h b/src/mem/heap.h index 9b8b61293..84a258285 100644 --- a/src/mem/heap.h +++ b/src/mem/heap.h @@ -226,6 +226,13 @@ void ray_heap_destroy(void); void ray_heap_abandon(void); void ray_heap_merge(ray_heap_t* src); void ray_heap_flush_foreign(void); +/* Give a parked worker's heap the blocks other threads freed to it. For the + * dispatcher, once a parallel region has ended: a worker only drains its own + * list when its freelists run dry, so between dispatches the blocks the main + * thread freed sit unused while the worker keeps cutting fresh pool space. + * The caller vouches that the owning thread is idle (a pool worker on its + * semaphore); must run with ray_parallel_flag clear, does nothing otherwise. */ +void ray_heap_reclaim_worker(ray_heap_t* h); void ray_heap_push_pending(ray_heap_t* heap); void ray_heap_drain_pending(void); uint8_t ray_order_for_size(size_t data_size); diff --git a/test/test_heap.c b/test/test_heap.c index 0e14473f2..975eb7f66 100644 --- a/test/test_heap.c +++ b/test/test_heap.c @@ -41,6 +41,7 @@ #include "test.h" #include #include "mem/heap.h" +#include "core/platform.h" #include "core/pool.h" /* Restore the shipped policy after a test drives it. */ @@ -640,6 +641,67 @@ static test_result_t test_free_routes_to_owner_list(void) { PASS(); } +/* ---- The dispatcher hands a foreign block back to its owner -------------- + * + * Issue #619: a parallel operator's workers allocate per-task buffers and the + * main thread frees them after the dispatch, so they land on the owning + * worker's foreign list, where they sit until that worker's freelists run + * dry — which a warm worker's rarely do. ray_heap_reclaim_worker, run by + * the dispatcher on each worker's heap at the end of every parallel region, + * drains that list into the worker's freelists. Model it with two heaps: a + * block owned by heap_b and freed from heap_a stays parked (still on heap_b's + * books) until heap_a reclaims heap_b — and is left alone while the parallel + * flag is set. */ + +static test_result_t test_reclaim_worker_drains_owner_list(void) { + ray_heap_t* heap_a = ray_tl_heap; + + ray_tl_heap = NULL; + ray_heap_init(); + ray_heap_t* heap_b = ray_tl_heap; + TEST_ASSERT_NOT_NULL(heap_b); + /* heap_b may be a heap abandoned by an earlier test's worker, with blocks + * freed to it since; take them back first so the books below move only + * for the block this test frees. */ + ray_heap_flush_foreign(); +#if RAY_MEM_STATS + size_t booked0 = heap_b->stats.bytes_allocated; +#endif + ray_t* blk = ray_alloc(256u << 10); /* above the slab orders */ + TEST_ASSERT_NOT_NULL(blk); +#if RAY_MEM_STATS + size_t booked1 = heap_b->stats.bytes_allocated; + TEST_ASSERT(booked1 > booked0, "allocation charged to heap_b"); +#endif + + ray_tl_heap = heap_a; + ray_free(blk); + TEST_ASSERT_EQ_U((uintptr_t)atomic_load(&heap_b->foreign), (uintptr_t)blk); +#if RAY_MEM_STATS + /* Parked, not yet returned: heap_b still carries the bytes. */ + TEST_ASSERT_EQ_U(heap_b->stats.bytes_allocated, booked1); +#endif + + /* Inside a parallel region the reclaim is a no-op. */ + ray_parallel_begin(); + ray_heap_reclaim_worker(heap_b); + TEST_ASSERT_EQ_U((uintptr_t)atomic_load(&heap_b->foreign), (uintptr_t)blk); + atomic_store(&ray_parallel_flag, 0); + + /* Once it is over, another thread reclaims heap_b: the list is empty and + * the block is back on heap_b's freelists, off its books. */ + ray_heap_reclaim_worker(heap_b); + TEST_ASSERT_NULL(atomic_load(&heap_b->foreign)); +#if RAY_MEM_STATS + TEST_ASSERT_EQ_U(heap_b->stats.bytes_allocated, booked0); +#endif + + ray_tl_heap = heap_b; + ray_heap_destroy(); + ray_tl_heap = heap_a; + PASS(); +} + /* ---- A cross-thread free cycle must not grow the owner's pools ---------- * * The regression for issue #439. Workers allocate per-group temporaries from @@ -2961,6 +3023,7 @@ const test_entry_t heap_entries[] = { { "heap/gc_serial", test_heap_gc_serial, heap_setup, heap_teardown }, { "heap/gc_parallel", test_heap_gc_parallel, heap_setup, heap_teardown }, { "heap/free_routes_to_owner", test_free_routes_to_owner_list, heap_setup, heap_teardown }, + { "heap/reclaim_worker_drains_owner", test_reclaim_worker_drains_owner_list, heap_setup, heap_teardown }, { "heap/cross_heap_cycle_bounds", test_cross_heap_cycle_bounds_pools, heap_setup, heap_teardown }, { "heap/abandon_is_adopted", test_heap_abandon_is_adopted, heap_setup, heap_teardown }, { "heap/alloc_copy_list", test_alloc_copy_list_retains, heap_setup, heap_teardown }, diff --git a/test/test_pool.c b/test/test_pool.c index 8eb499a1e..6a3069f14 100644 --- a/test/test_pool.c +++ b/test/test_pool.c @@ -397,6 +397,72 @@ static void pool_count_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t } } +/* -------------------------------------------------------------------------- + * Test: blocks a worker allocated inside a dispatch and the main thread freed + * after it are back with their owners by the end of the next dispatch — no + * registered heap carries a foreign list across a parallel region (issue + * #619: a stream of parallel joins grew the process by a pool per worker + * while the freed per-task buffers waited on those lists). + * -------------------------------------------------------------------------- */ + +typedef struct { + ray_t* blocks[64]; + uint32_t owner[64]; /* worker_id that allocated blocks[i]; 0 = main */ +} pool_alloc_ctx_t; + +static void pool_alloc_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + pool_alloc_ctx_t* c = (pool_alloc_ctx_t*)ctx; + for (int64_t i = start; i < end && i < 64; i++) { + c->blocks[i] = ray_alloc(256u << 10); /* 256 KB from the caller's heap */ + c->owner[i] = worker_id; + } +} + +static test_result_t test_dispatch_reclaims_worker_blocks(void) { + ray_heap_init(); + + ray_pool_t pool; + ray_err_t err = ray_pool_create(&pool, 3); + TEST_ASSERT_EQ_I(err, RAY_OK); + + /* ray_pool_create returns before the workers have started; a worker + * publishes its heap once it has run ray_heap_init. Wait for all three + * on that published state, so every slot below is a real heap. */ + for (uint32_t w = 0; w < pool.n_workers; w++) + while (!atomic_load(&pool.worker_heaps[w])) RAY_CPU_RELAX(); + + /* Rounds of "workers allocate, main frees" until a round in which at + * least one block really came from a worker (main is worker 0 and can + * take every task when the others are slow to wake). Rounds are cheap; + * 64 of them without a worker allocation would mean the pool is not + * running its workers at all. */ + pool_alloc_ctx_t ctx = {0}; + int worker_blocks = 0; + for (int round = 0; round < 64 && worker_blocks == 0; round++) { + ray_pool_dispatch_n(&pool, pool_alloc_fn, &ctx, 64); + for (int i = 0; i < 64; i++) { + TEST_ASSERT_NOT_NULL(ctx.blocks[i]); + if (ctx.owner[i] != 0) worker_blocks++; + ray_free(ctx.blocks[i]); /* cross-thread for worker blocks */ + ctx.blocks[i] = NULL; + } + } + TEST_ASSERT(worker_blocks > 0, "some blocks were allocated by workers"); + + /* Those frees happened after the last dispatch ended, so the blocks sit + * on their owners' foreign lists now; the next dispatch hands them back. */ + pool_count_ctx_t cctx = {0}; + ray_pool_dispatch_n(&pool, pool_count_fn, &cctx, 4); + for (uint32_t w = 0; w < pool.n_workers; w++) { + ray_heap_t* wh = (ray_heap_t*)atomic_load(&pool.worker_heaps[w]); + TEST_ASSERT_NOT_NULL(wh); + TEST_ASSERT_NULL(atomic_load(&wh->foreign)); + } + + ray_pool_free(&pool); + PASS(); +} + /* -------------------------------------------------------------------------- * Test: dispatch with total_elems <= 0 returns immediately, no calls fire * -------------------------------------------------------------------------- */ @@ -1400,6 +1466,7 @@ const test_entry_t pool_entries[] = { { "pool/auto_all_logical_cpus", test_auto_all_logical_cpus, NULL, NULL }, #endif { "pool/parallel_sum", test_parallel_sum, NULL, NULL }, + { "pool/dispatch_reclaims_worker_blocks", test_dispatch_reclaims_worker_blocks, NULL, NULL }, { "pool/parallel_add", test_parallel_add, NULL, NULL }, { "pool/parallel_group_sum", test_parallel_group_sum, NULL, NULL }, { "pool/parallel_min_max", test_parallel_min_max, NULL, NULL }, From a3ba5553e6eed059b1e1d457ff77019716b82f54 Mon Sep 17 00:00:00 2001 From: Evgen Belozerov Date: Thu, 24 Sep 2026 21:01:07 +0300 Subject: [PATCH 25/29] fix(serde): reject trailing payload bytes (#622) --- src/store/serde.c | 8 +++++++- test/test_store.c | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/store/serde.c b/src/store/serde.c index 6bed0ad41..ecfa2c103 100644 --- a/src/store/serde.c +++ b/src/store/serde.c @@ -1250,7 +1250,13 @@ ray_t* ray_de(ray_t* bytes) { return ray_error("domain", "deserialize: ipc header size %lld + header != buffer length %lld", (long long)hdr->size, (long long)total); int64_t len = hdr->size; - return ray_de_raw(buf + sizeof(ray_ipc_header_t), &len); + ray_t* result = ray_de_raw(buf + sizeof(ray_ipc_header_t), &len); + if (!result || RAY_IS_ERR(result)) return result; + if (len != 0) { + ray_release(result); + return ray_error("domain", "deserialize: %lld trailing payload bytes", (long long)len); + } + return result; } /* -------------------------------------------------------------------------- diff --git a/test/test_store.c b/test/test_store.c index 1e7d849a7..190a3eaef 100644 --- a/test/test_store.c +++ b/test/test_store.c @@ -3061,6 +3061,25 @@ static test_result_t test_serde_de_raw_default_and_errors(void) { TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_TRUE(RAY_IS_ERR(r)); ray_release(r); ray_release(w); } + /* A top-level frame must contain exactly one serialized object. Extra + * payload bytes are not valid framing and must not be silently ignored. */ + { + ray_t* w = ray_ser(ray_i64(42)); + TEST_ASSERT_NOT_NULL(w); TEST_ASSERT_FALSE(RAY_IS_ERR(w)); + int64_t total = w->len; + ray_t* trailing = ray_vec_new(RAY_U8, total + 1); + TEST_ASSERT_NOT_NULL(trailing); TEST_ASSERT_FALSE(RAY_IS_ERR(trailing)); + trailing->len = total + 1; + memcpy(ray_data(trailing), ray_data(w), (size_t)total); + ((uint8_t*)ray_data(trailing))[total] = 0xa5; + ray_ipc_header_t* hdr = (ray_ipc_header_t*)ray_data(trailing); + hdr->size += 1; + + ray_t* r = ray_de(trailing); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_TRUE(RAY_IS_ERR(r)); + TEST_ASSERT_MEM_EQ(7, r->sdata, "domain"); + ray_release(r); ray_release(trailing); ray_release(w); + } /* SYM vector where an element has no null terminator within bounds: * craft a payload: type=RAY_SYM(12), attrs=0, len=1, then 4 non-null * bytes and nothing else → safe_strlen returns 4 = *len, domain error */ From 31f45a72b5e086257a535041404a0f6a23cc33d2 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Fri, 25 Sep 2026 10:11:51 +0300 Subject: [PATCH 26/29] fix(select): a projection sees the projections before it (#620) --- docs/docs/queries/select.md | 56 ++ src/lang/env.c | 7 + src/lang/env.h | 3 + src/lang/eval.c | 9 +- src/ops/agg_engine.c | 12 +- src/ops/graph.c | 2 + src/ops/ops.h | 26 + src/ops/query.c | 905 +++++++++++++++++++++++++++++++- test/rfl/agg/parted_f64_agg.rfl | 8 +- test/rfl/regress/issue_617.rfl | 158 ++++++ 10 files changed, 1146 insertions(+), 40 deletions(-) create mode 100644 test/rfl/regress/issue_617.rfl diff --git a/docs/docs/queries/select.md b/docs/docs/queries/select.md index aa2f4d36a..9009fb7c8 100644 --- a/docs/docs/queries/select.md +++ b/docs/docs/queries/select.md @@ -35,6 +35,62 @@ Select specific columns with computed expressions: ; MSFT 378000 ``` +### Projections that build on earlier projections + +A projection sees every projection defined before it in the same `select`, +by its alias — as a bare name or as a literal symbol: + +```lisp +(select {from: t sym: sym notional: (* price volume) nn: (+ notional 1)}) +; sym notional nn +; --- -------- ------ +; AAPL 75000 75001 +; GOOG 112000 112001 +; MSFT 378000 378001 +``` + +The alias is bound after its own expression, so an alias that shadows a +source column reads the source in its own definition and the new column in +every projection after it: + +```lisp +(select {from: t price: (* price 2) p2: (+ price 1)}) +; price p2 +; ----- --- +; 300 301 +; 560 561 +; 840 841 +``` + +Only projections see aliases. `where:` and `by:` are evaluated against the +source table, so `where: (> notional 100000)` raises `schema` — filter on +the expression itself, or on a nested select. + +In a grouped select a later output may build on an earlier aggregate. An +alias that is one value per group — an aggregate, or an output built on one +— is read from the group result, so `nn` below is computed from the +per-group sum, and a chain of such outputs costs one column each. An alias +of a per-row expression (`vals: price`) is substituted where it is named, +so `m: (max vals)` is `(max price)`. + +```lisp +(select {from: t by: sym notional: (sum (* price volume)) nn: (+ notional 1)}) +``` + +Three rules follow from an alias being one value per group. Inside an +aggregate's argument a name that is a source column is always the source +column, so `s: (sum s) mx: (max s)` takes the maximum of the rows, not of a +sum. An aggregate cannot be aggregated again, through an alias or written +out: `s: (sum price) mx: (max s)` and `mx: (max (sum price))` both raise +`domain`. And an output may not put a source column beside a per-group +value outside an aggregate: `f: (* price n)` with `n: (count price)` raises +`domain`; write `(* (sum price) n)` or whichever aggregate is meant. + +A literal symbol inside a select resolves to an earlier alias or a source +column of that name, in that order; one naming neither stays a constant +symbol. Arithmetic on a symbol — a literal or a symbol column — is a `type` +error inside a select, as it is outside. + ### Whole-column projections A projection may be a whole-column verb — `distinct`, `asc`, `desc`, or diff --git a/src/lang/env.c b/src/lang/env.c index 65ba600a6..9fe76eee3 100644 --- a/src/lang/env.c +++ b/src/lang/env.c @@ -112,6 +112,13 @@ static struct { * threads with no bound VM, so plain __VM derefs are safe below. */ int32_t ray_env_scope_depth(void) { return __VM ? __VM->scope_depth : 0; } + +bool ray_env_query_scope_above(int32_t depth) { + if (!__VM) return false; + for (int32_t d = depth < 0 ? 0 : depth; d < __VM->scope_depth; d++) + if (__VM->scope_stack[d].kind == RAY_SCOPE_QUERY) return true; + return false; +} int32_t ray_env_global_count(void) { return g_env.count; } /* Reverse-map a builtin function object to the symbol it is bound under in the diff --git a/src/lang/env.h b/src/lang/env.h index 95ccad7d3..5054a155c 100644 --- a/src/lang/env.h +++ b/src/lang/env.h @@ -143,6 +143,9 @@ ray_err_t ray_env_push_scope(void); ray_err_t ray_env_push_query_scope(void); void ray_env_pop_scope(void); int32_t ray_env_scope_depth(void); +/* True when a query scope frame sits at index >= depth: a nested query has + * bound its own columns since the frame that was at depth-1 was pushed. */ +bool ray_env_query_scope_above(int32_t depth); ray_err_t ray_env_set_local(int64_t sym_id, ray_t* val); ray_t* ray_env_get_lexical_local(int64_t sym_id); bool ray_env_has_lexical_local(int64_t sym_id); diff --git a/src/lang/eval.c b/src/lang/eval.c index ced4f8ad1..4e1b53429 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -3824,11 +3824,10 @@ ray_t* ray_eval(ray_t* obj) { * the rule fires only while a query is active (ray_active_query_table * is NULL otherwise). A literal naming no column returns itself. */ if (obj->type == -RAY_SYM) { - ray_t* qt = ray_active_query_table(); - if (qt && qt->type == RAY_TABLE) { - ray_t* col = ray_table_get_col(qt, obj->i64); - if (col) { ray_retain(col); ret = col; goto out; } - } + /* The column — or, during a per-row evaluation, its cell in the + * current row (ray_active_query_literal). */ + ray_t* v = ray_active_query_literal(obj->i64); + if (v) { ret = v; goto out; } } ray_retain(obj); ret = obj; goto out; diff --git a/src/ops/agg_engine.c b/src/ops/agg_engine.c index 8f414c611..9f19eb1ab 100644 --- a/src/ops/agg_engine.c +++ b/src/ops/agg_engine.c @@ -928,8 +928,8 @@ static bool agg_desc_init(agg_desc_t* d, ray_graph_t* g, ray_op_ext_t* ext, for (uint32_t k = 0; k < nk; k++) d->key_data[k] = ray_data(key_cols[k]); for (uint32_t a = 0; a < na; a++) { ray_op_ext_t* ie = find_ext(g, ext->agg_ins[a]); - d->agg_syms[a] = ie->sym; - ray_t* vc = (ext->agg_ops[a] != OP_COUNT) ? ray_table_get_col(tbl, ie->sym) : NULL; + d->agg_syms[a] = ie ? ie->sym : 0; + ray_t* vc = (ext->agg_ops[a] != OP_COUNT && ie) ? ray_table_get_col(tbl, ie->sym) : NULL; d->val_data[a] = vc ? ray_data(vc) : NULL; d->val_types[a] = vc ? vc->type : RAY_I64; d->val_hasnull[a] = vc ? ray_vec_may_have_nulls(vc) : false; @@ -966,7 +966,7 @@ static bool agg_vo_init(agg_vo_t* vo, ray_graph_t* g, ray_op_ext_t* ext, ray_t* vo->block = 0; for (uint32_t a = 0; a < na; a++) { ray_op_ext_t* ie = find_ext(g, ext->agg_ins[a]); - ray_t* vc = (ext->agg_ops[a] != OP_COUNT) ? ray_table_get_col(tbl, ie->sym) : NULL; + ray_t* vc = (ext->agg_ops[a] != OP_COUNT && ie) ? ray_table_get_col(tbl, ie->sym) : NULL; int8_t in_type = vc ? vc->type : RAY_I64; vo->vts[a] = agg_resolve(ext->agg_ops[a], in_type); vo->off[a] = vo->block; @@ -5285,13 +5285,15 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, const agg_vtable_t* vt = agg_resolve(ext->agg_ops[a], x_col->type); col = agg_run_one_bin(vt, x_col, y_col, groups.gids, nrows, groups.ngroups, kparam); } else { - ray_t* val_col = (ext->agg_ops[a] != OP_COUNT) ? ray_table_get_col(tbl, ie->sym) : NULL; + ray_t* val_col = (ext->agg_ops[a] != OP_COUNT && ie) ? ray_table_get_col(tbl, ie->sym) : NULL; int8_t in_type = val_col ? val_col->type : RAY_I64; const agg_vtable_t* vt = agg_resolve(ext->agg_ops[a], in_type); col = agg_run_one(vt, val_col, groups.gids, nrows, groups.ngroups, kparam); } if (!col || RAY_IS_ERR(col)) { agg_groups_free(&groups); ray_release(result); return col ? col : ray_error("oom", NULL); } - int64_t agg_name = agg_result_col_name(ie->sym, ext->agg_ops[a]); + /* A COUNT reads no input column, so its input node need not be a + * scan (`(count (* price 2))`) and has no ext to name it by. */ + int64_t agg_name = agg_result_col_name(ie ? ie->sym : 0, ext->agg_ops[a]); result = ray_table_add_col(result, agg_name, col); ray_release(col); } diff --git a/src/ops/graph.c b/src/ops/graph.c index 5608332dd..7efba810b 100644 --- a/src/ops/graph.c +++ b/src/ops/graph.c @@ -140,6 +140,8 @@ ray_graph_t* ray_graph_new(ray_t* tbl) { void ray_graph_free(ray_graph_t* g) { if (!g) return; + if (g->compile_err) { ray_release(g->compile_err); g->compile_err = NULL; } + /* Unconsumed slice-group hint (error paths / shapes that never * reached exec_group). */ if (g->sg_col) { ray_release(g->sg_col); g->sg_col = NULL; } diff --git a/src/ops/ops.h b/src/ops/ops.h index 33a50f5dc..656b4fd57 100644 --- a/src/ops/ops.h +++ b/src/ops/ops.h @@ -547,6 +547,31 @@ typedef struct ray_graph { uint32_t node_id; } cexpr_env[32]; int cexpr_env_top; + + /* Output aliases of the select being compiled (src/ops/query.c): + * the projections compiled so far, in order. A name reference or a + * literal symbol consults them after the lambda/let env and before + * the source table's columns. Borrowed views into the projection + * loop's scratch arrays: set and cleared by that loop, never freed + * here. Kept apart from cexpr_env so a wide select does not eat the + * slots lambda inlining needs. */ + const int64_t* sel_alias_syms; + const uint32_t* sel_alias_ids; + int sel_alias_n; + + /* Set by compile_expr_dag when it declines an expression that can + * only fail (arithmetic on a symbol column). A caller with an + * evaluation fallback ignores it — the evaluator raises the same + * error; one without reports it instead of a generic compile + * failure. Owned; released by ray_graph_free. */ + ray_t* compile_err; + + /* > 0 while compile_expr_dag is inside a branch of `if`/`cond`. The + * DAG evaluates both arms element-wise and the condition picks one, so + * an arm's value is observable only where it is selected; the checks + * that reject an expression outright (arithmetic on a symbol) stay + * quiet inside an arm and let the arm compile as it always did. */ + int if_arm_depth; } ray_graph_t; /* ===== Morsel Iterator ===== */ @@ -918,6 +943,7 @@ ray_t* ray_lazy_append(ray_t* lazy, uint16_t opcode); * so a literal never captures a lambda/let local and resolution fires only * inside a query. Returns NULL when no query is active. */ ray_t* ray_active_query_table(void); +ray_t* ray_active_query_literal(int64_t sym); #ifdef __cplusplus } diff --git a/src/ops/query.c b/src/ops/query.c index 056d23882..f5bc3071e 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -314,6 +314,36 @@ static bool dag_type_is_temporal(int8_t t) { return t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP; } +/* Arithmetic on a symbol has no meaning — the eval path rejects it + * (`cannot add sym and i64`, arith.c). The DAG used to admit it because + * `promote` folds RAY_SYM into I64 and the constant folder reads a symbol + * atom as its interned id, so `(+ 'name 1)` and `(+ sym_col 1)` returned + * ids plus one without a word. Declining here sends the projection to the + * per-row eval fallback, which raises the same error as outside a query. + * Comparisons and membership keep SYM: they are not arithmetic. */ +static const char* dag_arith_verb(const char* fname, size_t fname_len) { + if (fname_len == 1) { + switch (fname[0]) { + case '+': return "add"; + case '-': return "subtract"; + case '*': return "multiply"; + case '/': return "divide"; + case '%': return "mod"; + } + } + return fname_len == 3 && memcmp(fname, "pow", 3) == 0 ? "pow" : "div"; +} + +static bool dag_arith_rejects_sym(const char* fname, size_t fname_len, + int8_t lt, int8_t rt) { + bool arith = (fname_len == 1 && (fname[0] == '+' || fname[0] == '-' || + fname[0] == '*' || fname[0] == '/' || + fname[0] == '%')) || + (fname_len == 3 && (memcmp(fname, "div", 3) == 0 || + memcmp(fname, "pow", 3) == 0)); + return arith && (lt == RAY_SYM || rt == RAY_SYM); +} + static bool dag_temporal_arith_needs_eval(const char* name, size_t len, int8_t left_type, int8_t right_type) { if (!dag_type_is_temporal(left_type) && !dag_type_is_temporal(right_type)) @@ -977,6 +1007,26 @@ static void cexpr_env_pop(ray_graph_t* g, int n) { if (g->cexpr_env_top < 0) g->cexpr_env_top = 0; /* defensive */ } +/* The projections of the select being compiled that precede the one + * being compiled now (g->sel_alias_*, published by the projection loop). + * Latest binding wins, so an alias that shadows an earlier alias — or a + * source column — is the one a later projection sees. */ +static ray_op_t* sel_alias_lookup(ray_graph_t* g, int64_t sym) { + for (int i = g->sel_alias_n - 1; i >= 0; i--) + if (g->sel_alias_syms[i] == sym) + return &g->nodes[g->sel_alias_ids[i]]; + return NULL; +} + +/* Takes the error compile_expr_dag left on the graph (see ops.h), or + * NULL. Callers that report a compile failure use it so the message + * names the actual problem when there is one. */ +static ray_t* graph_take_compile_err(ray_graph_t* g) { + ray_t* e = g->compile_err; + g->compile_err = NULL; + return e; +} + static int const_str_expr_len(ray_t* expr, size_t* out_len) { if (!expr || !out_len) return 0; if (expr->type == -RAY_STR && !(expr->attrs & ATTR_QUOTED)) { @@ -1062,6 +1112,8 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { if (expr->type == -RAY_SYM && !(expr->attrs & ATTR_QUOTED)) { ray_op_t* bound = cexpr_env_lookup(g, expr->i64); if (bound) return bound; + ray_op_t* alias = sel_alias_lookup(g, expr->i64); + if (alias) return alias; ray_t* local = ray_env_get_lexical_local(expr->i64); if (local) { if (ray_is_atom(local)) return ray_const_atom(g, local); @@ -1157,6 +1209,13 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { * the rule fires only when a query table is bound. A literal naming no * column stays a const atom node. */ if (expr->type == -RAY_SYM) { + /* A literal naming an EARLIER PROJECTION of the same select resolves + * to it, exactly as the bare name does — and ahead of a source + * column of the same name, as the bare name does. The alias store + * holds projections only, never lambda formals or let bindings, so + * a literal still never captures those. */ + ray_op_t* alias = sel_alias_lookup(g, expr->i64); + if (alias) return alias; if (g->table && g->table->type == RAY_TABLE && ray_table_get_col(g->table, expr->i64)) { ray_t* s = ray_sym_str(expr->i64); @@ -1276,7 +1335,16 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { g->cexpr_env_top++; pushed++; } + /* The body was written outside this select: a free + * name in it is a global (or a column), never an + * output alias of the select that happens to call + * the lambda. Hide the alias store while the body + * compiles; the actuals above were compiled in the + * projection's own scope and keep seeing aliases. */ + int saved_aliases = g->sel_alias_n; + g->sel_alias_n = 0; ray_op_t* result = compile_expr_dag(g, body); + g->sel_alias_n = saved_aliases; cexpr_env_pop(g, pushed); return result; } @@ -1342,11 +1410,12 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { ray_op_t* c = compile_expr_dag(g, elems[1]); if (!c) return NULL; uint32_t c_id = c->id; + g->if_arm_depth++; ray_op_t* t = compile_expr_dag(g, elems[2]); - if (!t) return NULL; - uint32_t t_id = t->id; - ray_op_t* e = compile_expr_dag(g, elems[3]); - if (!e) return NULL; + uint32_t t_id = t ? t->id : 0; + ray_op_t* e = t ? compile_expr_dag(g, elems[3]) : NULL; + g->if_arm_depth--; + if (!t || !e) return NULL; c = &g->nodes[c_id]; t = &g->nodes[t_id]; return ray_if(g, c, t, e); @@ -1575,7 +1644,9 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { } if (is_else) { if (i != n - 1) return NULL; + g->if_arm_depth++; ray_op_t* c = compile_expr_dag(g, cpair[1]); + g->if_arm_depth--; if (!c) return NULL; chain_id = c->id; } else { @@ -1583,7 +1654,9 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { ray_op_t* pred = compile_expr_dag(g, cpair[0]); if (!pred) return NULL; uint32_t pred_id = pred->id; + g->if_arm_depth++; ray_op_t* body = compile_expr_dag(g, cpair[1]); + g->if_arm_depth--; if (!body) return NULL; pred = &g->nodes[pred_id]; ray_op_t* chain = &g->nodes[chain_id]; @@ -1689,6 +1762,16 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { left->out_type, right->out_type)) return NULL; + if (g->if_arm_depth == 0 && + dag_arith_rejects_sym(fname, fname_len, + left->out_type, right->out_type)) { + if (!g->compile_err) + g->compile_err = ray_error("type", "cannot %s %s and %s", + dag_arith_verb(fname, fname_len), + ray_type_name((int8_t)-left->out_type), + ray_type_name((int8_t)-right->out_type)); + return NULL; + } if (fname_len == 3 && memcmp(fname, "pow", 3) == 0 && (!dag_pow_type_admitted(left->out_type) || !dag_pow_type_admitted(right->out_type))) @@ -1761,6 +1844,15 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { * Column-membership scoped and query-only by construction — see * ray_active_query_table. */ static _Thread_local ray_t* g_active_query_table = NULL; +/* The per-row evaluation in progress, if any: the row, the table it indexes + * and the scope depth just above its own query frame. A literal column + * name stands for the row's cell only while the active table is that table + * and no nested query has opened a scope since — a nested select, a + * per-group evaluation or a where-mask over any table (the same one + * included) binds whole columns and must see whole columns. */ +static _Thread_local int64_t g_active_query_row = -1; +static _Thread_local ray_t* g_active_query_row_tbl = NULL; +static _Thread_local int32_t g_active_query_row_depth = 0; ray_t* ray_active_query_table(void) { return g_active_query_table; } @@ -2026,6 +2118,18 @@ static int hidden_agg_shape_ok(ray_t* expr) { return op == OP_QUANTILE; } +static bool agg_arith_head_is_control(int64_t sym) { + static const char* const forms[] = { "if", "while", "times", + "do", "let", "set", "try" }; + ray_t* s = ray_sym_str(sym); + if (!s) return false; + const char* p = ray_str_ptr(s); + size_t l = ray_str_len(s); + for (size_t i = 0; i < sizeof forms / sizeof forms[0]; i++) + if (l == strlen(forms[i]) && memcmp(p, forms[i], l) == 0) return true; + return false; +} + static ray_t* agg_arith_rewrite(ray_t* expr, ray_t* tbl, ray_t** hexprs, int64_t* hnames, int* n_hidden, int cap, int* ok) { @@ -2053,6 +2157,15 @@ static ray_t* agg_arith_rewrite(ray_t* expr, ray_t* tbl, * Reject the whole output; it keeps the per-group scatter path. */ if (n > 0 && el[0] && el[0]->type == -RAY_SYM && el[0]->i64 == ray_sym_intern("fn", 2)) { *ok = 0; return NULL; } + /* `if` (and the loops) take one condition, not a vector of them: + * evaluated once over the n_groups-row result they would pick a + * single branch for every group. The scope-making forms (do, let, + * set, try) evaluate their body outside the scope the hidden slots + * are bound in. Reject such outputs so they keep the per-group + * evaluation, where the condition is a scalar and names are plain. */ + if (n > 0 && el[0] && el[0]->type == -RAY_SYM && + !(el[0]->attrs & ATTR_QUOTED) && agg_arith_head_is_control(el[0]->i64)) + { *ok = 0; return NULL; } ray_t* out = ray_list_new(0); if (!out || RAY_IS_ERR(out)) { *ok = 0; return out && RAY_IS_ERR(out) ? NULL : NULL; } for (int64_t i = 0; i < n && *ok; i++) { @@ -3448,6 +3561,29 @@ static ray_t* nonagg_eval_per_group_buf(ray_t* expr, ray_t* tbl, return res; } +/* The value a literal column-name symbol stands for while a query is + * active (see the literal rule in eval.c): the whole column, or — while a + * per-row evaluation is running — that column's cell in the current row, + * so `'price` reads what `price` reads wherever the expression is + * evaluated. Owned ref; NULL when no query is active or the name is not a + * column of it. */ +ray_t* ray_active_query_literal(int64_t sym) { + ray_t* qt = g_active_query_table; + if (!qt || qt->type != RAY_TABLE) return NULL; + ray_t* col = ray_table_get_col(qt, sym); + if (!col) return NULL; + if (g_active_query_row < 0 || qt != g_active_query_row_tbl || + g_active_query_row >= ray_len(col) || + ray_env_query_scope_above(g_active_query_row_depth)) { + ray_retain(col); return col; + } + int allocated = 0; + ray_t* cell = collection_elem(col, g_active_query_row, &allocated); + if (!cell || RAY_IS_ERR(cell)) return cell; + if (!allocated) ray_retain(cell); + return cell; +} + static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { /* Exact-size carve, mirrors nonagg_eval_per_group_core: ncols(tbl) is * a hard upper bound for collect_col_refs's deduplicated table-column @@ -3471,7 +3607,12 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { * the previous value and restore it before EVERY exit from this scope * (including error returns), exactly as the bind_all_columns sites do. */ ray_t* _aqt = g_active_query_table; - g_active_query_table = tbl; + int64_t _aqr = g_active_query_row; + ray_t* _aqrt = g_active_query_row_tbl; + int32_t _aqrd = g_active_query_row_depth; + g_active_query_table = tbl; + g_active_query_row_tbl = tbl; + g_active_query_row_depth = ray_env_scope_depth(); /* just above our own frame */ ray_t* result = NULL; int direct_typed = 0; @@ -3482,7 +3623,7 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { int allocated = 0; ray_t* arg = collection_elem(cols[i], row, &allocated); if (!arg || RAY_IS_ERR(arg)) { - g_active_query_table = _aqt; + g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; ray_env_pop_scope(); if (result) ray_release(result); scratch_free(refs_hdr); @@ -3492,9 +3633,10 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { if (allocated) ray_release(arg); } + g_active_query_row = row; ray_t* cell = ray_eval(expr); if (!cell || RAY_IS_ERR(cell)) { - g_active_query_table = _aqt; + g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; ray_env_pop_scope(); if (result) ray_release(result); scratch_free(refs_hdr); @@ -3507,7 +3649,7 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { if (collapsable) { result = ray_vec_new((int8_t)-t, nrows); if (!result || RAY_IS_ERR(result)) { - g_active_query_table = _aqt; + g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; ray_env_pop_scope(); ray_release(cell); scratch_free(refs_hdr); @@ -3527,7 +3669,7 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { if (!collapsable) { result = ray_alloc(nrows * sizeof(ray_t*)); if (!result) { - g_active_query_table = _aqt; + g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; ray_env_pop_scope(); ray_release(cell); scratch_free(refs_hdr); @@ -3547,7 +3689,7 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { ray_t* list_col = typed_vec_to_list(result, row, nrows); ray_release(result); if (RAY_IS_ERR(list_col)) { - g_active_query_table = _aqt; + g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; ray_env_pop_scope(); ray_release(cell); scratch_free(refs_hdr); @@ -3564,7 +3706,7 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { } } - g_active_query_table = _aqt; + g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; ray_env_pop_scope(); scratch_free(refs_hdr); if (!result) { @@ -3587,6 +3729,10 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { static ray_t* eval_expr_whole_column(ray_t* expr, ray_t* tbl) { if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); ray_t* _aqt = bind_all_columns(tbl); + /* Whole columns here, even when a per-row evaluation of an outer select + * is in progress (a nested select inside one of its outputs). */ + int64_t _aqr = g_active_query_row; + g_active_query_row = -1; ray_t* result = ray_eval(expr); /* distinct/asc/desc/reverse return a lazy DAG chain (RAY_LAZY) — force it * to a concrete vector while the source columns it captured are still @@ -3594,6 +3740,7 @@ static ray_t* eval_expr_whole_column(ray_t* expr, ray_t* tbl) { if (result && !RAY_IS_ERR(result)) result = ray_lazy_materialize(result); g_active_query_table = _aqt; + g_active_query_row = _aqr; ray_env_pop_scope(); if (!result) return ray_error("domain", "select: whole-column expression evaluation failed"); @@ -5135,6 +5282,7 @@ static ray_t* eval_scalar_agg_outputs(ray_t** dict_elems, int64_t dict_n, /* (select {from: t [where: pred] [by: key] [col: expr ...]}) * Special form — receives unevaluated dict arg. */ ray_t* ray_select(ray_t** args, int64_t n); +static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved); ray_t* ray_update(ray_t** args, int64_t n); ray_t* ray_insert(ray_t** args, int64_t n); ray_t* ray_upsert(ray_t** args, int64_t n); @@ -6196,7 +6344,7 @@ static ray_t* try_temporal_group_materialize(ray_t* dict, ray_t* tbl) { rewritten = ray_dict_upsert(rewritten, from, extended); ray_release(from); ray_release(extended); extended = NULL; MAT_CHECK(rewritten); - ray_t* result = ray_select(&rewritten, 1); + ray_t* result = ray_select_impl(&rewritten, 1, true); ray_release(rewritten); return result; oom: @@ -6207,7 +6355,595 @@ static ray_t* try_temporal_group_materialize(ray_t* dict, ray_t* tbl) { #undef MAT_CHECK } +/* -------------------------------------------------------------------------- + * Grouped select: a projection may refer to an earlier projection. + * + * In a grouped select every output is an aggregate (or a per-group value) + * over the SOURCE rows, so a later output cannot read an earlier one as a + * column the way the ungrouped path does through the compile-time env. + * The reference is resolved at the expression level instead: each output + * value is rewritten with every earlier alias replaced by that alias's + * (already rewritten) expression, and the rewritten dict goes through the + * ordinary classification — `nn: (+ notional 1)` after + * `notional: (sum (* price volume))` becomes `(+ (sum (* price volume)) 1)`, + * which the arith-of-aggs decomposition evaluates over the group result. + * + * Two places keep the source column instead of the alias. An alias is + * visible only to the outputs after it, so its own definition reads the + * source column of the same name. And inside an AGGREGATE's argument a + * name that is a source column stays the source column — an aggregate + * consumes rows, an alias is one value per group, so `s: (sum s) mx: (max s)` + * asks for the max of the rows, not of a sum. Outside aggregates the alias + * wins, as it does in an ungrouped select. where:, by: and the sort keys + * are not outputs and are never rewritten. A literal symbol naming an + * earlier alias resolves like the bare name; any other literal is left + * alone. Nothing is rewritten inside a lambda, a quote or a let, whose own + * bindings could shadow the alias. + * -------------------------------------------------------------------------- */ +/* Binds output `kid` = `col` in `tbl` for the projections still to be + * evaluated: replaces the column of that name when there is one, appends + * otherwise. Consumes one ref of `tbl`, returns an owned (possibly + * copied) table; `col` is retained by the table, the caller keeps its ref. */ +static ray_t* select_fallback_bind_alias(ray_t* tbl, int64_t kid, ray_t* col) { + int64_t ncols = ray_table_ncols(tbl); + for (int64_t c = 0; c < ncols; c++) { + if (ray_table_col_name(tbl, c) != kid) continue; + ray_t* t2 = ray_cow(tbl); /* a failed copy leaves `tbl` untouched */ + if (!t2 || RAY_IS_ERR(t2)) { ray_release(tbl); return t2; } + ray_table_set_col_idx(t2, c, col); + if (ray_table_get_col_idx(t2, c) != col) { ray_release(t2); return ray_error("oom", NULL); } + return t2; + } + return ray_table_add_col(tbl, kid, col); +} + +static bool select_alias_skip_form(ray_t* head) { + if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return false; + ray_t* s = ray_sym_str(head->i64); + if (!s) return false; + const char* p = ray_str_ptr(s); + size_t l = ray_str_len(s); + return (l == 2 && memcmp(p, "fn", 2) == 0) || + (l == 3 && memcmp(p, "let", 3) == 0) || + (l == 5 && memcmp(p, "quote", 5) == 0); +} + +static bool select_alias_head_is_agg(ray_t* head) { + if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return false; + if (resolve_agg_opcode(head->i64) != 0) return true; + ray_t* s = ray_sym_str(head->i64); + return s && ray_str_len(s) == 8 && memcmp(ray_str_ptr(s), "distinct", 8) == 0; +} + +/* The first aggregate call in `expr` that sits inside another aggregate's + * argument, or NULL. In a grouped select the inner one is already one + * value per group, so the outer one has no rows left to fold; evaluated + * anyway it collapses over the whole table and every group gets the same + * number. A lambda or let body is its own scope and is not descended. */ +static ray_t* grouped_output_nested_agg(ray_t* expr, bool inside_agg) { + if (!expr || expr->type != RAY_LIST || expr->len < 1) return NULL; + ray_t** el = (ray_t**)ray_data(expr); + if (select_alias_skip_form(el[0])) return NULL; + bool agg = is_agg_expr(expr) != 0; + if (agg && inside_agg) return expr; + for (int64_t i = 1; i < expr->len; i++) { + ray_t* hit = grouped_output_nested_agg(el[i], inside_agg || agg); + if (hit) return hit; + } + return NULL; +} + +/* ── Grouped alias planning ─────────────────────────────────────────────── + * A grouped select's outputs may name earlier outputs. Two kinds of alias: + * + * ROW — the expression aggregates nothing (`vals: price`, `s: sym`, + * `p2: (* price 2)`): a value per source row. Substituted by + * value where referenced, so `m: (max vals)` is `(max price)`. + * GROUP — the expression contains an aggregate, or refers to a GROUP + * alias: one value per group. Never substituted. An output + * that refers to one outside an aggregate becomes a DERIVED + * output: it leaves the engine's dict and is evaluated after + * grouping, over the group result, where the alias is a column + * (by reference — copying the expression made a chain like + * `a3: (+ a2 a1)` double in size at every step). Aggregates + * inside a derived output are computed by the engine under + * hidden names and read back from the result. Inside an + * aggregate's argument a GROUP alias has no rows left to fold + * and is rejected. + * + * A lambda's formals shadow aliases in its body; `let` and `quote` forms + * are not descended. */ + +enum { SEL_ALIAS_ROW = 0, SEL_ALIAS_GROUP = 1 }; +#define SEL_ALIAS_MAX_NODES 65536 + +typedef struct { + int64_t n_derived; + int64_t* derived_names; /* [n_derived] */ + ray_t** derived_exprs; /* [n_derived], owned */ + int64_t n_hidden; + int64_t* hidden_names; /* [n_hidden]: engine outputs to drop from the result */ + bool sort_after; /* asc:/desc:/take: taken out of the engine's dict */ + ray_t* hdr; /* scratch block behind the arrays */ +} select_alias_plan_t; + +static void select_alias_plan_free(select_alias_plan_t* p) { + for (int64_t i = 0; i < p->n_derived; i++) + if (p->derived_exprs[i]) ray_release(p->derived_exprs[i]); + if (p->hdr) scratch_free(p->hdr); + memset(p, 0, sizeof(*p)); +} + +static bool select_sym_is(ray_t* s, const char* name, size_t len) { + if (!s || s->type != -RAY_SYM || (s->attrs & ATTR_QUOTED)) return false; + ray_t* str = ray_sym_str(s->i64); + return str && ray_str_len(str) == len && memcmp(ray_str_ptr(str), name, len) == 0; +} + +static bool select_lambda_form(ray_t* expr) { + if (!expr || expr->type != RAY_LIST || expr->len < 3) return false; + ray_t** el = (ray_t**)ray_data(expr); + return select_sym_is(el[0], "fn", 2) && ray_is_vec(el[1]) && el[1]->type == RAY_SYM; +} + +/* Aggregate calls anywhere in `expr` (is_agg_expr, the predicate + * select_extract_aggs extracts on — wider than the DAG-shaped count that + * sizes the engine's own hidden slots). */ +static int64_t count_agg_calls(ray_t* expr) { + if (!expr || expr->type != RAY_LIST) return 0; + int64_t c = is_agg_expr(expr) ? 1 : 0; + ray_t** e = (ray_t**)ray_data(expr); + for (int64_t i = 0; i < expr->len; i++) c += count_agg_calls(e[i]); + return c; +} + +/* True when `expr` reads a column of `tbl` (bare or literal name; a + * lambda's formals shadow). Used on a ROW alias's expression when it is + * substituted outside an aggregate: the source column it carries is then + * read per row, whatever name it came in under. */ +static bool select_expr_reads_col(ray_t* expr, ray_t* tbl, const int64_t* shadow, int n_shadow) { + if (!expr) return false; + if (expr->type == -RAY_SYM) { + for (int i = 0; i < n_shadow; i++) if (shadow[i] == expr->i64) return false; + return ray_table_get_col(tbl, expr->i64) != NULL; + } + if (expr->type != RAY_LIST || expr->len < 1) return false; + ray_t** el = (ray_t**)ray_data(expr); + if (select_sym_is(el[0], "quote", 5)) return false; + if (select_lambda_form(expr)) { + int64_t nf = ray_len(el[1]); + ray_t* hdr = NULL; + int64_t* merged = (int64_t*)scratch_alloc(&hdr, (size_t)(n_shadow + nf + 1) * sizeof(int64_t)); + if (!merged) return true; /* cannot tell: report the safe answer */ + for (int i = 0; i < n_shadow; i++) merged[i] = shadow[i]; + for (int64_t i = 0; i < nf; i++) merged[n_shadow + i] = sym_cell_runtime_id(el[1], i); + bool r = false; + for (int64_t i = 2; i < expr->len && !r; i++) + r = select_expr_reads_col(el[i], tbl, merged, n_shadow + (int)nf); + scratch_free(hdr); + return r; + } + for (int64_t i = 0; i < expr->len; i++) + if (select_expr_reads_col(el[i], tbl, shadow, n_shadow)) return true; + return false; +} + +static int64_t expr_node_count(ray_t* expr, int64_t cap) { + if (!expr) return 0; + if (expr->type != RAY_LIST) return 1; + int64_t n = 1; + ray_t** el = (ray_t**)ray_data(expr); + for (int64_t i = 0; i < expr->len && n < cap; i++) + n += expr_node_count(el[i], cap - n); + return n; +} + +/* Rebuilds `expr` with element i replaced by f(el[i]) for i >= from; the + * list is copied only once an element changes. `sub` returns an owned + * expression. Shared by the three walkers below. */ +typedef ray_t* (*select_alias_map_fn)(ray_t* e, void* ctx); + +static ray_t* select_alias_map_list(ray_t* expr, int64_t from, select_alias_map_fn fn, void* ctx) { + ray_t** el = (ray_t**)ray_data(expr); + ray_t* out = NULL; + for (int64_t i = from; i < expr->len; i++) { + ray_t* e2 = fn(el[i], ctx); + if (!e2 || RAY_IS_ERR(e2)) { if (out) ray_release(out); return e2 ? e2 : ray_error("oom", NULL); } + if (e2 != el[i] && !out) { + out = ray_list_new(expr->len); + if (!out || RAY_IS_ERR(out)) { ray_release(e2); return out ? out : ray_error("oom", NULL); } + for (int64_t j = 0; j < i; j++) { + out = ray_list_append(out, el[j]); + if (!out || RAY_IS_ERR(out)) { ray_release(e2); return out ? out : ray_error("oom", NULL); } + } + } + if (out) { + out = ray_list_append(out, e2); + ray_release(e2); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + } else { + ray_release(e2); + } + } + if (!out) { ray_retain(expr); return expr; } + return out; +} + +typedef struct { + const int64_t* names; + ray_t** exprs; + const uint8_t* kinds; + int n_alias; + ray_t* tbl; + bool in_agg; + const int64_t* shadow; + int n_shadow; + bool changed; + bool refs_group; + bool refs_row; /* a source column read outside an aggregate */ + const int64_t* keys; /* by: names — columns of the group result, not per-row reads */ + int n_keys; +} select_alias_subst_ctx_t; + +static bool select_sym_in(int64_t sym, const int64_t* syms, int n) { + for (int i = 0; i < n; i++) if (syms[i] == sym) return true; + return false; +} + +static ray_t* select_alias_subst(ray_t* expr, void* vctx) { + select_alias_subst_ctx_t* c = (select_alias_subst_ctx_t*)vctx; + if (!expr) return NULL; + if (expr->type == -RAY_SYM) { + for (int i = 0; i < c->n_shadow; i++) + if (c->shadow[i] == expr->i64) { ray_retain(expr); return expr; } + /* inside an aggregate's argument a source column is the source column */ + if (c->in_agg && ray_table_get_col(c->tbl, expr->i64)) { ray_retain(expr); return expr; } + for (int i = c->n_alias - 1; i >= 0; i--) { + if (c->names[i] != expr->i64) continue; + if (c->kinds[i] == SEL_ALIAS_GROUP) { + if (c->in_agg) { + ray_t* s = ray_sym_str(expr->i64); + return ray_error("domain", + "select by: `%.*s` is an aggregate of the group and cannot be aggregated again", + s ? (int)ray_str_len(s) : 1, s ? ray_str_ptr(s) : "?"); + } + c->refs_group = true; + ray_retain(expr); return expr; + } + c->changed = true; + if (!c->in_agg && select_expr_reads_col(c->exprs[i], c->tbl, c->keys, c->n_keys)) c->refs_row = true; + ray_retain(c->exprs[i]); + return c->exprs[i]; + } + if (!c->in_agg && !select_sym_in(expr->i64, c->keys, c->n_keys) && + ray_table_get_col(c->tbl, expr->i64)) c->refs_row = true; + ray_retain(expr); return expr; + } + if (expr->type != RAY_LIST || expr->len < 1) { ray_retain(expr); return expr; } + ray_t** el = (ray_t**)ray_data(expr); + if (select_sym_is(el[0], "let", 3) || select_sym_is(el[0], "quote", 5)) { ray_retain(expr); return expr; } + if (select_lambda_form(expr)) { + int64_t nf = ray_len(el[1]); + ray_t* sh_hdr = NULL; + int64_t* merged = (int64_t*)scratch_alloc(&sh_hdr, (size_t)(c->n_shadow + nf + 1) * sizeof(int64_t)); + if (!merged) return ray_error("oom", NULL); + for (int i = 0; i < c->n_shadow; i++) merged[i] = c->shadow[i]; + for (int64_t i = 0; i < nf; i++) merged[c->n_shadow + i] = sym_cell_runtime_id(el[1], i); + select_alias_subst_ctx_t inner = *c; + inner.shadow = merged; inner.n_shadow = c->n_shadow + (int)nf; + ray_t* out = select_alias_map_list(expr, 2, select_alias_subst, &inner); + scratch_free(sh_hdr); + c->changed |= inner.changed; c->refs_group |= inner.refs_group; c->refs_row |= inner.refs_row; + return out; + } + select_alias_subst_ctx_t inner = *c; + inner.in_agg = c->in_agg || select_alias_head_is_agg(el[0]); + /* a call whose head is itself a form — `((fn [x] …) 1)` — is walked + * from the head, which is where such a lambda's body lives */ + ray_t* out = select_alias_map_list(expr, el[0]->type == RAY_LIST ? 0 : 1, + select_alias_subst, &inner); + c->changed |= inner.changed; c->refs_group |= inner.refs_group; c->refs_row |= inner.refs_row; + return out; +} + +/* Replaces every aggregate call in a derived output by a hidden engine + * output `__ad` (added to `*engine`) and returns the rewritten + * expression, owned. Lambda, let and quote forms are left alone. */ +typedef struct { + ray_t** engine; + select_alias_plan_t* plan; + const int64_t* shadow; /* lambda formals in scope: an aggregate over one stays put */ + int n_shadow; +} select_extract_ctx_t; + +static bool select_expr_mentions(ray_t* expr, const int64_t* syms, int n) { + if (!expr) return false; + if (expr->type == -RAY_SYM) { + for (int i = 0; i < n; i++) if (syms[i] == expr->i64) return true; + return false; + } + if (expr->type != RAY_LIST) return false; + ray_t** el = (ray_t**)ray_data(expr); + for (int64_t i = 0; i < expr->len; i++) + if (select_expr_mentions(el[i], syms, n)) return true; + return false; +} + +static ray_t* select_extract_aggs(ray_t* expr, void* vctx) { + select_extract_ctx_t* c = (select_extract_ctx_t*)vctx; + if (!expr || expr->type != RAY_LIST || expr->len < 1) { ray_retain(expr); return expr; } + ray_t** el = (ray_t**)ray_data(expr); + if (select_sym_is(el[0], "let", 3) || select_sym_is(el[0], "quote", 5)) { ray_retain(expr); return expr; } + if (select_lambda_form(expr)) { + int64_t nf = ray_len(el[1]); + ray_t* hdr = NULL; + int64_t* merged = (int64_t*)scratch_alloc(&hdr, (size_t)(c->n_shadow + nf + 1) * sizeof(int64_t)); + if (!merged) return ray_error("oom", NULL); + for (int i = 0; i < c->n_shadow; i++) merged[i] = c->shadow[i]; + for (int64_t i = 0; i < nf; i++) merged[c->n_shadow + i] = sym_cell_runtime_id(el[1], i); + select_extract_ctx_t inner = *c; + inner.shadow = merged; inner.n_shadow = c->n_shadow + (int)nf; + ray_t* out = select_alias_map_list(expr, 2, select_extract_aggs, &inner); + scratch_free(hdr); + return out; + } + if (is_agg_expr(expr) && !select_expr_mentions(expr, c->shadow, c->n_shadow)) { + char buf[24]; + int bn = snprintf(buf, sizeof buf, "__ad%lld", (long long)c->plan->n_hidden); + int64_t hn = ray_sym_intern(buf, (size_t)bn); + ray_t* key = ray_sym(hn); + if (!key || RAY_IS_ERR(key)) return key ? key : ray_error("oom", NULL); + *c->engine = ray_dict_upsert(*c->engine, key, expr); /* retains expr */ + ray_release(key); + if (!*c->engine || RAY_IS_ERR(*c->engine)) { ray_t* e = *c->engine; *c->engine = NULL; return e ? e : ray_error("oom", NULL); } + c->plan->hidden_names[c->plan->n_hidden++] = hn; + return ray_sym(hn); + } + return select_alias_map_list(expr, el[0]->type == RAY_LIST ? 0 : 1, select_extract_aggs, c); +} + +/* Plans the grouped select: NULL when the dict has no by: or nothing refers + * to an earlier alias (nothing to do); an error; or an owned dict for the + * engine (ROW aliases substituted, derived outputs and — when there are + * any — asc:/desc:/take: removed, hidden aggregates added, from: replaced by + * the evaluated table) with `plan` filled in for select_apply_derived. */ +/* Does `expr` mention (bare or literal) any of the first `n` names? */ +static bool select_expr_mentions_key(ray_t* expr, ray_t* keys, int64_t n) { + if (!expr) return false; + if (expr->type == -RAY_SYM) { + for (int64_t i = 0; i < n; i++) if (sym_cell_runtime_id(keys, i) == expr->i64) return true; + return false; + } + if (expr->type != RAY_LIST) return false; + ray_t** el = (ray_t**)ray_data(expr); + for (int64_t i = 0; i < expr->len; i++) + if (select_expr_mentions_key(el[i], keys, n)) return true; + return false; +} + +static ray_t* select_plan_grouped_aliases(ray_t* dict, ray_t* tbl, select_alias_plan_t* plan) { + memset(plan, 0, sizeof(*plan)); + if (!dict || dict->type != RAY_DICT || !dict_get(dict, "by")) return NULL; + ray_t* keys = ray_dict_keys(dict); + ray_t* vals = ray_dict_vals(dict); + if (!keys || keys->type != RAY_SYM || !vals || vals->type != RAY_LIST) return NULL; + int64_t nd = ray_dict_len(dict); + /* Most grouped selects name no earlier output: leave before any + * allocation unless some value mentions a key that precedes it. */ + { + bool any = false; + for (int64_t i = 1; i < nd && !any; i++) + any = select_expr_mentions_key(((ray_t**)ray_data(vals))[i], keys, i); + if (!any) return NULL; + } + static const char* const reserved[] = { "from", "where", "by", "take", "asc", "desc", "nearest" }; + int64_t rid[7]; + for (int i = 0; i < 7; i++) rid[i] = ray_sym_intern(reserved[i], strlen(reserved[i])); + int64_t hidden_max = 1; + for (int64_t i = 0; i < nd; i++) + hidden_max += count_agg_calls(((ray_t**)ray_data(vals))[i]); + ray_t* work_hdr = NULL; + int64_t* names = (int64_t*)scratch_alloc(&work_hdr, + (size_t)(nd > 0 ? nd : 1) * (sizeof(int64_t) + sizeof(ray_t*) + sizeof(uint8_t))); + if (!names) return ray_error("oom", NULL); + ray_t** exprs = (ray_t**)(names + nd); + uint8_t* kinds = (uint8_t*)(exprs + nd); + plan->derived_names = (int64_t*)scratch_alloc(&plan->hdr, + (size_t)(nd > 0 ? nd : 1) * (sizeof(int64_t) + sizeof(ray_t*)) + (size_t)hidden_max * sizeof(int64_t)); + if (!plan->derived_names) { scratch_free(work_hdr); return ray_error("oom", NULL); } + plan->derived_exprs = (ray_t**)(plan->derived_names + nd); + plan->hidden_names = (int64_t*)(plan->derived_exprs + nd); + /* The by: names: a group key is a column of the group result (one value + * per group), so reading it beside a GROUP alias is not a per-row read. */ + ray_t* by_expr = dict_get(dict, "by"); + ray_t* keys_hdr = NULL; + int64_t* key_syms = NULL; + int n_key_syms = 0; + { + int64_t nk = 0; + if (by_expr && by_expr->type == -RAY_SYM) nk = 1; + else if (by_expr && ray_is_vec(by_expr) && by_expr->type == RAY_SYM) nk = ray_len(by_expr); + else if (by_expr && by_expr->type == RAY_DICT) nk = ray_dict_len(by_expr); + key_syms = (int64_t*)scratch_alloc(&keys_hdr, (size_t)(nk > 0 ? nk : 1) * sizeof(int64_t)); + if (!key_syms) { scratch_free(work_hdr); select_alias_plan_free(plan); return ray_error("oom", NULL); } + if (by_expr && by_expr->type == -RAY_SYM) key_syms[n_key_syms++] = by_expr->i64; + else if (by_expr && ray_is_vec(by_expr) && by_expr->type == RAY_SYM) + for (int64_t k = 0; k < nk; k++) key_syms[n_key_syms++] = sym_cell_runtime_id(by_expr, k); + else if (by_expr && by_expr->type == RAY_DICT) { + ray_t* bk = ray_dict_keys(by_expr); + if (bk && bk->type == RAY_SYM) + for (int64_t k = 0; k < nk; k++) key_syms[n_key_syms++] = sym_cell_runtime_id(bk, k); + } + } + int n_alias = 0; + ray_t* engine = NULL; /* owned once anything changes */ + ray_t* err = NULL; + for (int64_t i = 0; i < nd && !err; i++) { + int64_t kid = sym_cell_runtime_id(keys, i); + bool is_reserved = false; + for (int r = 0; r < 7; r++) if (rid[r] == kid) { is_reserved = true; break; } + if (is_reserved) continue; + ray_t* v = ((ray_t**)ray_data(vals))[i]; + select_alias_subst_ctx_t sc = { names, exprs, kinds, n_alias, tbl, false, NULL, 0, false, false, false, key_syms, n_key_syms }; + ray_t* v1 = select_alias_subst(v, &sc); + if (!v1 || RAY_IS_ERR(v1)) { err = v1 ? v1 : ray_error("oom", NULL); break; } + if (sc.refs_group && sc.refs_row) { + /* one value per group beside a value per row: the output has + * no single shape; the column needs an aggregate around it */ + ray_t* s = ray_sym_str(kid); + ray_release(v1); + err = ray_error("domain", "select by: output `%.*s` combines a source column with a per-group value; aggregate the column", + s ? (int)ray_str_len(s) : 1, s ? ray_str_ptr(s) : "?"); + break; + } + if (sc.changed && expr_node_count(v1, SEL_ALIAS_MAX_NODES) >= SEL_ALIAS_MAX_NODES) { + ray_t* s = ray_sym_str(kid); + ray_release(v1); + err = ray_error("limit", "select by: output `%.*s` grows too large once its aliases are expanded", + s ? (int)ray_str_len(s) : 1, s ? ray_str_ptr(s) : "?"); + break; + } + ray_t* key = ray_sym(kid); + if (!key || RAY_IS_ERR(key)) { ray_release(v1); err = key ? key : ray_error("oom", NULL); break; } + if (sc.refs_group) { + /* derived: out of the engine's dict, aggregates inside it in */ + if (!engine) { engine = dict; ray_retain(engine); } + engine = ray_dict_remove(engine, key); + if (!engine || RAY_IS_ERR(engine)) { ray_release(key); ray_release(v1); err = engine ? engine : ray_error("oom", NULL); engine = NULL; break; } + select_extract_ctx_t xc = { &engine, plan, NULL, 0 }; + ray_t* v2 = select_extract_aggs(v1, &xc); + ray_release(v1); + if (!v2 || RAY_IS_ERR(v2)) { ray_release(key); err = v2 ? v2 : ray_error("oom", NULL); break; } + plan->derived_names[plan->n_derived] = kid; + plan->derived_exprs[plan->n_derived] = v2; /* owned by the plan */ + plan->n_derived++; + names[n_alias] = kid; exprs[n_alias] = v2; kinds[n_alias] = SEL_ALIAS_GROUP; + n_alias++; + ray_release(key); + continue; + } + if (sc.changed) { + if (!engine) { engine = dict; ray_retain(engine); } + engine = ray_dict_upsert(engine, key, v1); /* retains v1 */ + if (!engine || RAY_IS_ERR(engine)) { ray_release(key); ray_release(v1); err = engine ? engine : ray_error("oom", NULL); engine = NULL; break; } + } + ray_release(key); + /* bind AFTER the value: visible to later outputs only. exprs[] + * borrows v1 from the dict it now lives in. */ + names[n_alias] = kid; + exprs[n_alias] = v1; + kinds[n_alias] = expr_contains_agg(v1) ? SEL_ALIAS_GROUP : SEL_ALIAS_ROW; + n_alias++; + ray_release(v1); + } + scratch_free(work_hdr); + scratch_free(keys_hdr); + if (err) { if (engine) ray_release(engine); select_alias_plan_free(plan); return err; } + if (!engine) { select_alias_plan_free(plan); return NULL; } + /* Sort keys and take: may name a derived output: apply them after. */ + if (plan->n_derived > 0) { + for (int r = 3; r <= 5; r++) { + ray_t* key = ray_sym(rid[r]); + if (!key || RAY_IS_ERR(key)) { ray_release(engine); select_alias_plan_free(plan); return key ? key : ray_error("oom", NULL); } + if (dict_get(dict, reserved[r])) plan->sort_after = true; + engine = ray_dict_remove(engine, key); + ray_release(key); + if (!engine || RAY_IS_ERR(engine)) { select_alias_plan_free(plan); return engine ? engine : ray_error("oom", NULL); } + } + } + ray_t* from_key = ray_sym(rid[0]); + if (!from_key || RAY_IS_ERR(from_key)) { ray_release(engine); select_alias_plan_free(plan); return from_key ? from_key : ray_error("oom", NULL); } + engine = ray_dict_upsert(engine, from_key, tbl); + ray_release(from_key); + if (!engine || RAY_IS_ERR(engine)) { select_alias_plan_free(plan); return engine ? engine : ray_error("oom", NULL); } + return engine; +} + +/* A derived output is evaluated once over the group result with every + * column bound (vector semantics) unless it holds a form that takes one + * condition or one value — `if` and the other control forms, a lambda + * body — in which case it is evaluated row by row. */ +static bool select_derived_needs_rows(ray_t* expr) { + if (!expr || expr->type != RAY_LIST || expr->len < 1) return false; + ray_t** el = (ray_t**)ray_data(expr); + if (el[0]->type != -RAY_SYM || (el[0]->attrs & ATTR_QUOTED)) return true; /* ((fn …) …) and friends */ + if (agg_arith_head_is_control(el[0]->i64) || select_sym_is(el[0], "cond", 4)) return true; + ray_t* gv = ray_env_get(el[0]->i64); + if (gv && gv->type == RAY_LAMBDA) return true; + for (int64_t i = 1; i < expr->len; i++) + if (select_derived_needs_rows(el[i])) return true; + return false; +} + +/* Evaluates the derived outputs over the engine's result (in order, each + * one visible to the next), drops the hidden aggregate columns, restores + * the dict's output order and applies the sort keys and take: that were + * held back. Consumes `result`. */ +static ray_t* select_apply_derived(ray_t* result, ray_t* dict, select_alias_plan_t* plan) { + if (!result || RAY_IS_ERR(result)) return result; + if (ray_is_lazy(result)) result = ray_lazy_materialize(result); + if (!result || RAY_IS_ERR(result)) return result; + if (result->type != RAY_TABLE) return result; + int64_t n_groups = ray_table_nrows(result); + for (int64_t d = 0; d < plan->n_derived; d++) { + ray_t* expr = plan->derived_exprs[d]; + ray_t* col = select_derived_needs_rows(expr) + ? eval_expr_per_row(expr, result, n_groups) + : eval_expr_whole_column(expr, result); + if (!col || RAY_IS_ERR(col)) { ray_release(result); return col ? col : ray_error("oom", NULL); } + if (ray_is_lazy(col)) col = ray_lazy_materialize(col); + if (!col || RAY_IS_ERR(col)) { ray_release(result); return col ? col : ray_error("oom", NULL); } + if (!(ray_is_vec(col) || col->type == RAY_LIST) || ray_len(col) != n_groups) { + ray_t* nm = ray_sym_str(plan->derived_names[d]); + ray_release(col); ray_release(result); + return ray_error("domain", "select by: output `%.*s` did not evaluate to one value per group", + nm ? (int)ray_str_len(nm) : 1, nm ? ray_str_ptr(nm) : "?"); + } + result = select_fallback_bind_alias(result, plan->derived_names[d], col); + ray_release(col); + if (!result || RAY_IS_ERR(result)) return result ? result : ray_error("oom", NULL); + } + /* Key columns first (whatever the engine emitted that is not an output), + * then the outputs in the dict's order, hidden aggregates dropped. */ + DICT_VIEW_DECL(dv); + DICT_VIEW_OPEN(dict, dv); + if (DICT_VIEW_OVERFLOW(dv)) { DICT_VIEW_CLOSE(dv); ray_release(result); return ray_error("oom", NULL); } + int64_t from_id = ray_sym_intern("from", 4), where_id = ray_sym_intern("where", 5), by_id = ray_sym_intern("by", 2); + int64_t take_id = ray_sym_intern("take", 4), asc_id = ray_sym_intern("asc", 3), desc_id = ray_sym_intern("desc", 4); + int64_t nearest_id = ray_sym_intern("nearest", 7); + int64_t ncols = ray_table_ncols(result); + ray_t* out = ray_table_new(ncols); + if (!out || RAY_IS_ERR(out)) { DICT_VIEW_CLOSE(dv); ray_release(result); return out ? out : ray_error("oom", NULL); } + for (int64_t c = 0; c < ncols && out && !RAY_IS_ERR(out); c++) { + int64_t cn = ray_table_col_name(result, c); + bool is_output = false, is_hidden = false; + for (int64_t i = 0; i + 1 < dv_n; i += 2) + if (dv[i]->i64 == cn && cn != from_id && cn != where_id && cn != by_id && cn != take_id && cn != asc_id && cn != desc_id && cn != nearest_id) { is_output = true; break; } + for (int64_t h = 0; h < plan->n_hidden; h++) if (plan->hidden_names[h] == cn) { is_hidden = true; break; } + if (is_output || is_hidden) continue; + out = ray_table_add_col(out, cn, ray_table_get_col_idx(result, c)); + } + for (int64_t i = 0; i + 1 < dv_n && out && !RAY_IS_ERR(out); i += 2) { + int64_t cn = dv[i]->i64; + if (cn == from_id || cn == where_id || cn == by_id || cn == take_id || cn == asc_id || cn == desc_id || cn == nearest_id) continue; + ray_t* col = ray_table_get_col(result, cn); + if (!col) continue; /* an output the engine folded away (e.g. a key projection) */ + out = ray_table_add_col(out, cn, col); + } + if (!out || RAY_IS_ERR(out)) { DICT_VIEW_CLOSE(dv); ray_release(result); return out ? out : ray_error("oom", NULL); } + ray_release(result); + result = out; + if (plan->sort_after) + result = apply_sort_take(result, dv, dv_n, asc_id, desc_id, take_id, NULL); + DICT_VIEW_CLOSE(dv); + return result; +} + ray_t* ray_select(ray_t** args, int64_t n) { + return ray_select_impl(args, n, false); +} + +static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (n < 1) return ray_error("arity", "select: expects a query dict, got %lld args", (long long)n); ray_t* dict = args[0]; if (!dict || dict->type != RAY_DICT) @@ -6261,6 +6997,20 @@ ray_t* ray_select(ray_t** args, int64_t n) { if (RAY_IS_ERR(tbl)) return tbl; if (tbl->type != RAY_TABLE) { int8_t tbl_t = tbl->type; ray_release(tbl); return ray_error("type", "select: `from:` must evaluate to a table, got %s", ray_type_name(tbl_t)); } + if (!aliases_resolved) { + select_alias_plan_t plan; + ray_t* engine = select_plan_grouped_aliases(dict, tbl, &plan); + if (engine && RAY_IS_ERR(engine)) { ray_release(tbl); return engine; } + if (engine) { + ray_t* r = ray_select_impl(&engine, 1, true); + if (plan.n_derived > 0) r = select_apply_derived(r, dict, &plan); + select_alias_plan_free(&plan); + ray_release(engine); + ray_release(tbl); + return r; + } + } + ray_t* temporal_result = try_temporal_group_materialize(dict, tbl); if (temporal_result) { ray_release(tbl); return temporal_result; } @@ -7128,7 +7878,8 @@ ray_t* ray_select(ray_t** args, int64_t n) { (size_t)hidden_max * (sizeof(ray_t*) + sizeof(int64_t)) + (size_t)nk_max * sizeof(ray_op_t*) + (size_t)aggs_max * (2 * sizeof(ray_op_t*) + 2 * sizeof(int64_t) + sizeof(uint16_t)) + - (size_t)2 * (size_t)n_dep_keys * sizeof(int64_t)); + (size_t)2 * (size_t)n_dep_keys * sizeof(int64_t) + + (size_t)(nk_max + 2 * aggs_max) * sizeof(uint32_t)); if (!nonagg_names) { scratch_free(dep_src_hdr); if (by_sym_vec_owned) ray_release(by_sym_vec_owned); @@ -7147,7 +7898,14 @@ ray_t* ray_select(ray_t** args, int64_t n) { int64_t* agg_names = agg_k + aggs_max; dep_key_names = agg_names + aggs_max; /* [n_dep_keys] */ dep_key_biases = dep_key_names + n_dep_keys; /* [n_dep_keys] */ - uint16_t* agg_ops = (uint16_t*)(dep_key_biases + n_dep_keys); + /* Node ids of key_ops / agg_ins / agg_ins2. g->nodes grows by realloc + * as expressions compile, so a pointer taken from one compile is stale + * after the next; the ids are captured with each compile and the + * pointers re-resolved from them right before the group node is built. */ + uint32_t* key_ids = (uint32_t*)(dep_key_biases + n_dep_keys); /* [nk_max] */ + uint32_t* agg_in_ids = key_ids + nk_max; /* [aggs_max] */ + uint32_t* agg_in2_ids = agg_in_ids + aggs_max; /* [aggs_max] */ + uint16_t* agg_ops = (uint16_t*)(agg_in2_ids + aggs_max); /* Copy the bridged dependent-key names/biases into this block, then release * the transient collector. n_dep_keys == 0 (non-dep path) → no-op, and * dep_src_hdr stays NULL. */ @@ -9183,6 +9941,16 @@ ray_t* ray_select(ray_t** args, int64_t n) { ray_t* expr = dict_elems[i + 1]; if (is_single_group_key_projection(by_expr, expr)) continue; + if (grouped_output_nested_agg(expr, false)) { + ray_t* nm = ray_sym_str(kid); + for (int ci = 0; ci < n_compound; ci++) + ray_release(compound_rw[ci]); + ray_graph_free(g); ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return ray_error("domain", + "select by: output `%.*s` aggregates an aggregate of the group", + nm ? (int)ray_str_len(nm) : 1, nm ? ray_str_ptr(nm) : "?"); + } if (is_group_dag_agg_expr_dag_safe(expr, tbl)) { /* dag-aggs claim output slots in order. Not a flat * forcer. */ @@ -9385,7 +10153,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { } for (int64_t i = 0; i < deferred_nk && n_keys < nk_max; i++) { key_ops[n_keys] = compile_expr_dag(g, dfv[i * 2 + 1]); - if (!key_ops[n_keys]) { DICT_VIEW_CLOSE(dfv); ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select by: failed to compile group key expression"); } + if (!key_ops[n_keys]) { ray_t* cerr = graph_take_compile_err(g); DICT_VIEW_CLOSE(dfv); ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return cerr ? cerr : ray_error("domain", "select by: failed to compile group key expression"); } n_keys++; } DICT_VIEW_CLOSE(dfv); @@ -9414,10 +10182,13 @@ ray_t* ray_select(ray_t** args, int64_t n) { /* Only a real expression is renamed: a bare column symbol lands * here too and keeps its own name. */ computed_single_key = (key_ops[0] != NULL && by_expr->type == RAY_LIST); - if (!key_ops[0]) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select by: failed to compile group key expression"); } + if (!key_ops[0]) { ray_t* cerr = graph_take_compile_err(g); ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return cerr ? cerr : ray_error("domain", "select by: failed to compile group key expression"); } n_keys = 1; } + for (int64_t ki = 0; ki < n_keys; ki++) + key_ids[ki] = key_ops[ki]->id; + /* Collect aggregation expressions from output columns. * Non-agg expressions are tracked separately for post-DAG scatter. * agg_ins2[] is parallel to agg_ins[] — NULL for unary aggs, @@ -9454,7 +10225,12 @@ ray_t* ray_select(ray_t** args, int64_t n) { agg_ops[n_aggs] = op; /* Compile the aggregation input (the column reference) */ agg_ins[n_aggs] = compile_expr_dag(g, agg_arg); - if (!agg_ins[n_aggs]) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select by: failed to compile aggregation argument"); } + agg_in_ids[n_aggs] = agg_ins[n_aggs] ? agg_ins[n_aggs]->id : RAY_OP_NONE; + if (!agg_ins[n_aggs]) { + ray_t* cerr = graph_take_compile_err(g); + ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return cerr ? cerr : ray_error("domain", "select by: failed to compile aggregation argument"); + } agg_names[n_aggs] = kid; /* Canonical aggregand type-admission (matches the scalar * builtins): reject non-numeric / absolute-temporal inputs so a @@ -9465,10 +10241,12 @@ ray_t* ray_select(ray_t** args, int64_t n) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("type", "select by: aggregation does not admit input type %s", ray_type_name(in_t)); } agg_ins2[n_aggs] = NULL; + agg_in2_ids[n_aggs] = RAY_OP_NONE; agg_k[n_aggs] = 0; if (agg_is_binary_agg(op)) { if (ray_len(val_expr) < 3) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("arity", "select by: binary aggregation requires two column arguments"); } agg_ins2[n_aggs] = compile_expr_dag(g, agg_elems[2]); + agg_in2_ids[n_aggs] = agg_ins2[n_aggs] ? agg_ins2[n_aggs]->id : RAY_OP_NONE; if (!agg_ins2[n_aggs]) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select by: failed to compile binary aggregation second argument"); } if (agg_ins2[n_aggs]->out_type > 0 && !agg_type_admitted(op, agg_ins2[n_aggs]->out_type)) { @@ -9528,11 +10306,14 @@ ray_t* ray_select(ray_t** args, int64_t n) { uint16_t hop = resolve_agg_opcode(he[0]->i64); agg_ops[n_aggs] = hop; agg_ins[n_aggs] = compile_expr_dag(g, he[1]); + agg_in_ids[n_aggs] = agg_ins[n_aggs] ? agg_ins[n_aggs]->id : RAY_OP_NONE; if (!agg_ins[n_aggs]) { for (int ci = 0; ci < n_compound; ci++) ray_release(compound_rw[ci]); + ray_t* cerr = graph_take_compile_err(g); ray_graph_free(g); ray_release(tbl); - scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select by: failed to compile aggregation argument"); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return cerr ? cerr : ray_error("domain", "select by: failed to compile aggregation argument"); } if (agg_ins[n_aggs]->out_type > 0 && !agg_type_admitted(hop, agg_ins[n_aggs]->out_type)) { @@ -9543,10 +10324,12 @@ ray_t* ray_select(ray_t** args, int64_t n) { scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("type", "select by: aggregation does not admit input type %s", ray_type_name(in_t)); } agg_ins2[n_aggs] = NULL; + agg_in2_ids[n_aggs] = RAY_OP_NONE; agg_k[n_aggs] = 0; if (agg_is_binary_agg(hop)) { /* hidden_agg_shape_ok admitted two bare column arguments */ agg_ins2[n_aggs] = compile_expr_dag(g, he[2]); + agg_in2_ids[n_aggs] = agg_ins2[n_aggs] ? agg_ins2[n_aggs]->id : RAY_OP_NONE; if (!agg_ins2[n_aggs]) { for (int ci = 0; ci < n_compound; ci++) ray_release(compound_rw[ci]); @@ -9610,6 +10393,15 @@ ray_t* ray_select(ray_t** args, int64_t n) { n_aggs++; } + /* Re-resolve the collected op pointers: every compile above may have + * moved g->nodes. */ + for (int64_t ki = 0; ki < n_keys; ki++) + key_ops[ki] = &g->nodes[key_ids[ki]]; + for (int64_t ai = 0; ai < n_aggs; ai++) { + agg_ins[ai] = &g->nodes[agg_in_ids[ai]]; + agg_ins2[ai] = agg_in2_ids[ai] != RAY_OP_NONE ? &g->nodes[agg_in2_ids[ai]] : NULL; + } + if (n_aggs > 0 || n_nonaggs > 0) { if (n_aggs > 0) { if (has_agg_k || has_binary_agg) { @@ -10380,13 +11172,27 @@ ray_t* ray_select(ray_t** args, int64_t n) { if (nc_max < 1) nc_max = 1; ray_t* colops_hdr = NULL; ray_op_t** col_ops = (ray_op_t**)scratch_alloc(&colops_hdr, - (size_t)nc_max * sizeof(ray_op_t*)); + (size_t)nc_max * (sizeof(ray_op_t*) + sizeof(int64_t) + sizeof(uint32_t))); if (!col_ops) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); } int64_t nc = 0; int use_eval_fallback = 0; + /* Projections see the projections before them: once an output + * expression has compiled, its alias is published on the graph + * (g->sel_alias_*), where a later projection's name reference + * or literal symbol finds it ahead of the source table's + * columns. The binding is made AFTER the expression compiles, + * so an alias that shadows a source column still reads the + * source in its own definition and the new value in every + * later one. where:, by: and the sort keys are compiled + * outside this window and stay alias-blind. */ + int64_t* alias_syms = (int64_t*)(col_ops + nc_max); + uint32_t* alias_ids = (uint32_t*)(alias_syms + nc_max); + g->sel_alias_syms = alias_syms; + g->sel_alias_ids = alias_ids; + g->sel_alias_n = 0; for (int64_t i = 0; i + 1 < dict_n; i += 2) { int64_t kid = dict_elems[i]->i64; if (kid == from_id || kid == where_id || kid == by_id || kid == take_id || kid == asc_id || kid == desc_id || kid == nearest_id) continue; @@ -10395,9 +11201,16 @@ ray_t* ray_select(ray_t** args, int64_t n) { use_eval_fallback = 1; break; } + alias_syms[nc] = kid; + alias_ids[nc] = col_ops[nc]->id; nc++; + g->sel_alias_n = (int)nc; } + g->sel_alias_syms = NULL; + g->sel_alias_ids = NULL; + g->sel_alias_n = 0; if (use_eval_fallback) { + if (g->compile_err) { ray_release(g->compile_err); g->compile_err = NULL; } /* The fallback evaluates projections directly over `tbl`, * bypassing the DAG's ray_execute — so a WHERE clause (wired * into `root` as ray_filter) would be silently ignored. @@ -10472,6 +11285,24 @@ ray_t* ray_select(ray_t** args, int64_t n) { scratch_free(colops_hdr); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("length", "select: output column length %lld does not match %lld", (long long)col_len, (long long)out_len); } + /* Later projections see this one: bind it in the table + * the remaining expressions are evaluated over, in place + * of a source column of the same name. A column of + * another length (`distinct`) cannot be a row of that + * table and stays unbound. */ + if (col_len == nrows) { + ray_t* bound = select_fallback_bind_alias(tbl, kid, col); + if (!bound || RAY_IS_ERR(bound)) { + ray_release(col); + ray_release(result); + if (nearest_handle_owned) ray_release(nearest_handle_owned); + if (nearest_query_owned) ray_free_raw(nearest_query_owned); + ray_graph_free(g); + scratch_free(colops_hdr); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return bound ? bound : ray_error("oom", NULL); + } + tbl = bound; + } result = ray_table_add_col(result, kid, col); ray_release(col); if (RAY_IS_ERR(result)) { @@ -10878,12 +11709,24 @@ ray_t* ray_select(ray_t** args, int64_t n) { ray_env_set_local(hidden_agg_names[hi], ray_table_get_col_idx(result, hbase + hi)); + int64_t n_groups = ray_table_nrows(result); for (int ci = 0; ci < n_compound && !cerr; ci++) { ray_t* v = ray_eval(compound_rw[ci]); - if (!v || RAY_IS_ERR(v)) + if (!v || RAY_IS_ERR(v)) { cerr = v ? v : ray_error("domain", "select by: failed to evaluate aggregate expression"); - else comp_cols[ci] = v; + } else if (ray_is_lazy(v) && + (!(v = ray_lazy_materialize(v)) || RAY_IS_ERR(v))) { + cerr = v ? v : ray_error("domain", + "select by: failed to evaluate aggregate expression"); + } else if (!(ray_is_vec(v) || v->type == RAY_LIST) || + ray_len(v) != n_groups) { + ray_t* nm = ray_sym_str(compound_names[ci]); + cerr = ray_error("domain", + "select by: output `%.*s` did not evaluate to one value per group", + nm ? (int)ray_str_len(nm) : 1, nm ? ray_str_ptr(nm) : "?"); + ray_release(v); + } else comp_cols[ci] = v; } ray_env_pop_scope(); } @@ -10911,14 +11754,22 @@ ray_t* ray_select(ray_t** args, int64_t n) { if (nt && !RAY_IS_ERR(nt)) { ray_release(result); result = nt; - } else if (nt) { - ray_release(nt); + } else { + /* An output that did not evaluate to one value per + * group (a scalar, say) cannot be appended: report it + * rather than hand back the hidden columns. */ + cerr = nt ? nt : ray_error("oom", NULL); } } for (int ci = 0; ci < n_compound; ci++) if (comp_cols[ci]) ray_release(comp_cols[ci]); scratch_free(cc_hdr); n_compound = 0; + if (cerr) { + ray_release(result); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return cerr; + } } } @@ -12828,7 +13679,7 @@ ray_t* ray_update(ray_t** args, int64_t n) { /* Evaluate expression on sub-table via DAG */ ray_graph_t* ug = ray_graph_new(sub_tbl); ray_op_t* expr_op = compile_expr_dag(ug, agg_expr); - if (!expr_op) { ray_graph_free(ug); ray_release(sub_tbl); ray_release(out_col); UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); return ray_error("domain", "update by: failed to compile aggregate expression"); } + if (!expr_op) { ray_t* cerr = graph_take_compile_err(ug); ray_graph_free(ug); ray_release(sub_tbl); ray_release(out_col); UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); return cerr ? cerr : ray_error("domain", "update by: failed to compile aggregate expression"); } expr_op = ray_optimize(ug, expr_op); ray_t* agg_result = ray_execute(ug, expr_op); ray_graph_free(ug); @@ -13498,7 +14349,7 @@ ray_t* ray_update(ray_t** args, int64_t n) { ray_t* update_expr = dict_elems[d + 1]; ray_graph_t* ug = ray_graph_new(tbl); ray_op_t* expr_op = compile_expr_dag(ug, update_expr); - if (!expr_op) { ray_release(result); ray_release(tbl); ray_graph_free(ug); DICT_VIEW_CLOSE(upda); return ray_error("domain", "update: failed to compile new column expression"); } + if (!expr_op) { ray_t* cerr = graph_take_compile_err(ug); ray_release(result); ray_release(tbl); ray_graph_free(ug); DICT_VIEW_CLOSE(upda); return cerr ? cerr : ray_error("domain", "update: failed to compile new column expression"); } expr_op = ray_optimize(ug, expr_op); ray_t* expr_vec = ray_execute(ug, expr_op); ray_graph_free(ug); @@ -18402,7 +19253,7 @@ static ray_t* asof_eval_select_segment(ray_t* dict, ray_t* parted_tbl, int32_t s ray_retain(keys); ray_t* ndict = ray_dict_new(keys, nvals); /* consumes both */ if (!ndict || RAY_IS_ERR(ndict)) return ndict ? ndict : ray_error("oom", NULL); - ray_t* r = ray_select(&ndict, 1); + ray_t* r = ray_select_impl(&ndict, 1, true); ray_release(ndict); return r; } @@ -18942,7 +19793,7 @@ static ray_t* asof_carry_recompute(ray_t* qtab, ray_t* template, ray_t* dict = ray_dict_new(keys, vals); /* consumes keys + vals */ if (!dict || RAY_IS_ERR(dict)) return dict ? dict : ray_error("oom", NULL); - ray_t* raw = ray_select(&dict, 1); + ray_t* raw = ray_select_impl(&dict, 1, true); ray_release(dict); if (!raw || RAY_IS_ERR(raw)) return raw ? raw : ray_error("type", NULL); diff --git a/test/rfl/agg/parted_f64_agg.rfl b/test/rfl/agg/parted_f64_agg.rfl index e8562613b..71d53fd86 100644 --- a/test/rfl/agg/parted_f64_agg.rfl +++ b/test/rfl/agg/parted_f64_agg.rfl @@ -101,16 +101,18 @@ (max (at Pi 'v)) -- 50 ;; ─── parted I64 sum wrap via raw-column expression fallback ────────── -;; `(first (list c))` deliberately defeats expr_compile today, leaving the -;; quoted raw column visible to the runtime agg_parted_sum path. If the +;; `(first (list …))` deliberately defeats expr_compile today, leaving the +;; raw parted column visible to the runtime agg_parted_sum path. If the ;; planner learns this shape later, this test may need a different wrapper. +;; (The column is taken with `at`: inside a select's per-row evaluation a +;; literal column name now stands for the row's cell, not the column.) (.sys.exec "rm -rf /tmp/rfl_agg_pwrap") (set Tw1 (table [v] (list [9223372036854775807]))) (set Tw2 (table [v] (list [9223372036854775807]))) (.db.splayed.set "/tmp/rfl_agg_pwrap/1/t/" Tw1) (.db.splayed.set "/tmp/rfl_agg_pwrap/2/t/" Tw2) (set Pw (.db.parted.get "/tmp/rfl_agg_pwrap/" 't)) -(at (select {r: ((fn [c] (sum (first (list c)))) 'v) from: Pw}) 'r) -- [-2 -2] +(sum (first (list (at Pw 'v)))) -- -2 ;; ─── parted DATE sum type error (agg_parted_sum line 129) ──────────── ;; DATE base type is explicitly excluded from sum — hits the type error path. diff --git a/test/rfl/regress/issue_617.rfl b/test/rfl/regress/issue_617.rfl new file mode 100644 index 000000000..9de7ab13d --- /dev/null +++ b/test/rfl/regress/issue_617.rfl @@ -0,0 +1,158 @@ +;; #617 — a select projection sees the projections before it. +;; +;; A projection is bound under its alias once its expression has compiled, +;; so every later projection can name it, bare or as a literal symbol. The +;; binding is made after the expression, so an alias that shadows a source +;; column still reads the source in its own definition and the new value in +;; every later one; where:, by: and the sort keys are compiled earlier and do +;; not see aliases. In a grouped select an alias of a per-row expression +;; is substituted where it is named; an alias that is one value per group +;; (an aggregate, or built on one) is read by reference from the group +;; result, so a chain of such outputs costs one column each, not a copy of +;; every expression before it. Arithmetic on a symbol inside a select +;; raises the type error it raises outside — it used to compute on the +;; symbol's interned id. +;; +;; Lines marked "guard" passed before the change and pin behaviour the change +;; must not alter. +(set t (table [sym price volume] (list [AAPL GOOG MSFT] [150 280 420] [500 400 900]))) + +;; the reported shape: bare name and literal symbol +(at (select {from: t sym: sym notional: (* price volume) nn: (+ notional 1)}) 'nn) -- [75001 112001 378001] +(at (select {from: t sym: sym notional: (* price volume) nn: (+ 'notional 1)}) 'nn) -- [75001 112001 378001] +(cols (select {from: t sym: sym notional: (* price volume) nn: (+ notional 1)})) -- [sym notional nn] + +;; a chain of aliases, each built on the previous +(at (select {from: t a: (* price 2) b: (+ a 1) c: (* b a)}) 'c) -- [90300 314160 706440] + +;; an alias that shadows a source column: its own definition reads the +;; source, every later projection reads the new column — bare or literal +(at (select {from: t price: (* price 2) p2: (+ price 1)}) 'price) -- [300 560 840] +(at (select {from: t price: (* price 2) p2: (+ price 1)}) 'p2) -- [301 561 841] +(at (select {from: t price: (* price 2) p2: (+ 'price 1)}) 'p2) -- [301 561 841] +;; guard: before the alias is defined the name is still the source column +(at (select {from: t p2: (+ price 1) price: (* price 2)}) 'p2) -- [151 281 421] +;; a lambda defined outside the select keeps its own free names: `rate` in +;; the body is the global, not the output of the select that calls it +(set rate 2) +(set scale (fn [x] (* x rate))) +(at (select {from: t rate: (+ price 1) v: (scale volume)}) 'v) -- [1000 800 1800] +(at (select {from: t rate: (+ price 1) r: (reverse volume) v: (scale volume)}) 'v) -- [1000 800 1800] + +;; guard: where: does not see aliases +(select {from: t notional: (* price volume) where: (> notional 100000)}) !- schema + +;; guard: a literal symbol that names no column and no alias stays a constant +(at (select {from: t o: 'price tag: 'nope}) 'tag) -- ['nope 'nope 'nope] +;; guard: a lambda formal is never captured by a literal, alias or not +(at (select {from: t o: ((fn [price] 'price) 999)}) 'o) -- [150 280 420] +(at (select {from: t n: (* price 2) f: ((fn [n] (+ n 100)) 1)}) 'f) -- [101 101 101] + +;; a projection beside a whole-column verb (evaluated outside the compiled +;; path) still sees the earlier aliases, shadowing included, as a literal too +(at (select {from: t a: (* price 2) r: (reverse volume) b: (+ a 1)}) 'b) -- [301 561 841] +(at (select {from: t a: (* price 2) r: (reverse volume) b: (+ 'a 1)}) 'b) -- [301 561 841] +(at (select {from: t r: (reverse volume) b: (+ 'price 1)}) 'b) -- [151 281 421] +(at (select {from: t price: (* price 2) r: (reverse volume) b: (+ price 1)}) 'b) -- [301 561 841] +(at (select {from: t a: (* price 2) d: (distinct sym) b: (+ a 1)}) 'b) -- [301 561 841] + +;; the number of projections does not limit what a later one can see, and +;; an inlined lambda with several formals still fits beside them +(set w (table [x y] (list [1 2 3] [10 20 30]))) +(set f5 (fn [a b c d e] (+ a (+ b (+ c (+ d e)))))) +(at (select {from: w c0: (+ x 0) c1: (+ x 1) c2: (+ x 2) c3: (+ x 3) c4: (+ x 4) c5: (+ x 5) c6: (+ x 6) c7: (+ x 7) c8: (+ x 8) c9: (+ x 9) c10: (+ x 10) c11: (+ x 11) c12: (+ x 12) c13: (+ x 13) c14: (+ x 14) c15: (+ x 15) c16: (+ x 16) c17: (+ x 17) c18: (+ x 18) c19: (+ x 19) c20: (+ x 20) c21: (+ x 21) c22: (+ x 22) c23: (+ x 23) c24: (+ x 24) c25: (+ x 25) c26: (+ x 26) c27: (+ x 27) c28: (+ x 28) c29: (+ x 29) c30: (+ x 30) c31: (+ x 31) c32: (+ x 32) c33: (+ x 33) c34: (+ x 34) z: (f5 x y x y c34)}) 'z) -- [57 80 103] +(count (cols (select {from: w c0: (+ x 0) c1: (+ x 1) c2: (+ x 2) c3: (+ x 3) c4: (+ x 4) c5: (+ x 5) c6: (+ x 6) c7: (+ x 7) c8: (+ x 8) c9: (+ x 9) c10: (+ x 10) c11: (+ x 11) c12: (+ x 12) c13: (+ x 13) c14: (+ x 14) c15: (+ x 15) c16: (+ x 16) c17: (+ x 17) c18: (+ x 18) c19: (+ x 19) c20: (+ x 20) c21: (+ x 21) c22: (+ x 22) c23: (+ x 23) c24: (+ x 24) c25: (+ x 25) c26: (+ x 26) c27: (+ x 27) c28: (+ x 28) c29: (+ x 29) c30: (+ x 30) c31: (+ x 31) c32: (+ x 32) c33: (+ x 33) c34: (+ x 34) z: (f5 x y x y c34)}))) -- 36 + +;; grouped: an output built on an aggregate alias, bare and literal, chained +(set g (table [sym price volume] (list [AAPL GOOG MSFT AAPL] [150 280 420 10] [500 400 900 100]))) +(at (select {from: g by: sym notional: (sum (* price volume)) nn: (+ notional 1)}) 'nn) -- [76001 112001 378001] +(at (select {from: g by: sym notional: (sum (* price volume)) nn: (+ 'notional 1)}) 'nn) -- [76001 112001 378001] +(at (select {from: g by: sym n: (count price) m: (* n 10) k: (+ m n)}) 'k) -- [22 11 11] +(cols (select {from: g by: sym n: (count price) m: (* n 10) k: (+ m n)})) -- [sym n m k] +;; a condition over an aggregate alias is decided per group +(at (select {from: g by: sym n: (count price) f: (if (> n 1) 1 0)}) 'f) -- [1 0 0] +(cols (select {from: g by: sym n: (count price) f: (if (> n 1) 1 0)})) -- [sym n f] +;; a chain where every output names the two before it: by reference, so the +;; expression does not double at each step (a copy of it crashed the process) +(at (select {from: g by: sym a0: (sum price) a1: (sum volume) a2: (+ a1 a0) a3: (+ a2 a1) a4: (+ a3 a2) a5: (+ a4 a3) a6: (+ a5 a4) a7: (+ a6 a5) a8: (+ a7 a6) a9: (+ a8 a7) a10: (+ a9 a8) a11: (+ a10 a9) a12: (+ a11 a10) a13: (+ a12 a11) a14: (+ a13 a12) a15: (+ a14 a13) a16: (+ a15 a14) a17: (+ a16 a15) a18: (+ a17 a16) a19: (+ a18 a17) a20: (+ a19 a18) a21: (+ a20 a19)}) 'a21) -- [7650000 6272600 12692700] +;; an output may combine an aggregate with an alias; outputs keep the +;; dict's order around a derived one; sort keys and take: may name one +(at (select {from: g by: sym n: (count price) f: (+ (sum volume) n)}) 'f) -- [602 401 901] +(cols (select {from: g by: sym n: (count price) f: (+ n 1) v: (sum volume)})) -- [sym n f v] +(at (select {from: g by: sym n: (count price) f: (+ n 1) desc: f take: 2}) 'sym) -- [AAPL GOOG] +;; a whole-column verb over an aggregate alias: one value per group still +(at (select {from: g by: sym n: (count price) f: (deltas n)}) 'f) -- [0Nl -1 0] +(at (select {from: g by: sym f: (deltas (sum price))}) 'f) -- [0Nl 120 140] +;; an inline lambda sees the alias in a grouped select as in an ungrouped one +(at (select {from: g by: sym n: (count price) f: ((fn [x] (+ x n)) 1)}) 'f) -- [3 2 2] +;; a per-row column beside a per-group value has no single shape — named +;; directly or carried in by an alias of a per-row expression +(select {from: g by: sym n: (count price) f: ((fn [x] (* x n)) price)}) !- domain +(select {from: g by: sym p2: (* price 2) n: (count price) f: (+ n p2)}) !- domain +;; aggregates inside a derived output are computed by the engine: any +;; number of them, of any shape, and inside a lambda body too +(at (select {from: g by: sym n: (count price) f: (+ n (+ (count (distinct price)) (+ (count (distinct price)) (+ (count (distinct price)) (+ (count (distinct price)) (+ (count (distinct price)) (+ (count (distinct price)) (+ (count (distinct price)) (count (distinct price))))))))))}) 'f) -- [18 9 9] +(at (select {from: g by: sym n: (count price) f: ((fn [x] (+ x (sum price))) n)}) 'f) -- [162 281 421] +;; a nested select inside a per-row output binds whole columns, whatever its +;; table and however few rows it has: the outer row never indexes into it +(set t2 (table [c d] (list [1 2 3 4 5] [10 20 30 40 50]))) +(first (at (select {from: t r: (reverse volume) b: (sum (at (select {from: t2 rr: (reverse 'd)}) 'rr))}) 'b)) -- 150 +(set t3 (table [c] (list [1 1]))) +(at (select {from: t r: (reverse volume) b: (count (select {from: t3 where: (== 'c 1)}))}) 'b) -- [2 2 2] +(at (select {from: t r: (reverse volume) b: (+ (count (select {from: t where: (> 'price 100)})) 'price)}) 'b) -- [153 283 423] +;; the same condition written out: it used to pick one branch for every +;; group; with constant branches the output went missing and the hidden +;; count appeared under a made-up name +(at (select {from: g by: sym f: (if (> (count price) 1) (count price) 0)}) 'f) -- [2 0 0] +(cols (select {from: g by: sym f: (if (> (count price) 1) 1 0)})) -- [sym f] +;; `try` evaluates its body in its own scope: decided per group as well +(at (select {from: g by: sym n: (count price) f: (try (+ n 1) 0)}) 'f) -- [3 2 2] +;; an output that is not one value per group is reported, not dropped +(select {from: g by: sym f: (at (sum price) 0)}) !- domain +;; grouped shadowing: outside an aggregate the alias wins ... +(at (select {from: g by: sym price: (sum price) p2: (+ price 1)}) 'p2) -- [161 281 421] +;; ... but inside an aggregate's argument a name that is a source column +;; stays the source column — an aggregate consumes rows, an alias is one +;; value per group (guard: this is what the query always meant) +(at (select {from: g by: sym price: (sum price) mx: (max price) av: (avg price)}) 'mx) -- [150 280 420] +(at (select {from: g by: sym price: (sum price) mx: (max price) av: (avg price)}) 'av) -- [80.0 280.0 420.0] +;; an alias that shadows nothing resolves inside an aggregate too +(at (select {from: g by: sym vals: price m: (max vals)}) 'm) -- [150 280 420] +;; a count over an expression (through an alias or written out) counts rows; +;; the written-out form used to crash the engine +(at (select {from: g by: sym p2: (* price 2) n: (count p2)}) 'n) -- [2 1 1] +(at (select {from: g by: sym n: (count (* price 2)) s: (sum price)}) 'n) -- [2 1 1] +;; a group key is one value per group: it may stand beside an alias +(at (select {from: g by: sym n: (count price) f: (if (== sym 'AAPL) n 0)}) 'f) -- [2 0 0] +(at (select {from: g by: [sym volume] n: (count price) f: (+ n volume)}) 'f) -- [501 401 901 101] +;; an aggregate alias has no rows left to aggregate — nor has the same +;; aggregate written out, which used to fold the whole table into every group +(select {from: g by: sym s: (sum price) mx: (max s)}) !- domain +(select {from: g by: sym mx: (max (sum price))}) !- domain +(select {from: g by: sym mx: (max (+ (sum price) 1))}) !- domain +;; guard: an aggregate over a whole-column verb is not a nested aggregate +(at (select {from: g by: sym c: (count (distinct price))}) 'c) -- [2 1 1] +;; the alias is not visible to an outer where:, but a nested select is +(at (select {from: (select {from: g by: sym n: (count price) nn: (+ n 1)}) where: (> nn 1)}) 'nn) -- [3 2 2] +;; a group-key alias is an alias like any other +(at (select {from: g by: sym s: sym n: (count s)}) 'n) -- [2 1 1] +;; guard: the lambda's own formal wins inside the lambda +(at (select {from: g by: sym n: (count price) f: ((fn [n] (+ n 100)) 1)}) 'f) -- [101 101 101] + +;; arithmetic on a symbol is a type error inside a select, as outside +(select {from: t nn: (+ 'nope 1)}) !- type +(select {from: t nn: (+ sym 1)}) !- type +(select {from: t nn: (* 'sym 2)}) !- type +(select {from: g by: sym s: (sum (+ sym 1))}) !- type +(update {from: t x: (+ sym 1)}) !- type +;; guard: inside a branch of `if` the arithmetic compiles as before — the +;; branch is evaluated element-wise and only read where it is selected +(at (select {from: t s: (if (> price 0) price (+ sym 1))}) 's) -- [150 280 420] +(at (select {from: g by: sym s: (sum (if (> price 0) price (+ sym 1)))}) 's) -- [160 280 420] +(select {from: t where: (< (+ sym 1) 5)}) !- type +;; guard +(select {from: g by: sym s: (sum price) x: (+ sym 1)}) !- type +(+ 'nope 1) !- type +;; guard: comparisons and membership on symbols are untouched +(count (select {from: t where: (== sym 'AAPL)})) -- 1 +(count (select {from: t where: (in sym [AAPL GOOG])})) -- 2 From d896a120bdca3a4f4bc7993b472b9d76df55bfa3 Mon Sep 17 00:00:00 2001 From: Serhii Savchuk Date: Fri, 25 Sep 2026 18:57:52 +0300 Subject: [PATCH 27/29] perf(like): one column kernel for the direct builtin and the executor, one row pass (#623) --- src/ops/internal.h | 2 + src/ops/string.c | 565 +++++++++------------------------ src/ops/strop.c | 161 +--------- test/rfl/strop/like_vector.rfl | 48 +++ 4 files changed, 215 insertions(+), 561 deletions(-) create mode 100644 test/rfl/strop/like_vector.rfl diff --git a/src/ops/internal.h b/src/ops/internal.h index 2bb8dd9e9..a1e1eeba8 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -1615,6 +1615,8 @@ ray_t* exec_date_trunc(ray_graph_t* g, ray_op_t* op); /* ── string_exec.c ── */ ray_t* exec_like(ray_graph_t* g, ray_op_t* op); +/* Shared LIKE kernel over a STR/SYM column (see string.c); selection may be NULL. */ +ray_t* ray_like_vec(ray_t* input, ray_t* pat_v, ray_t* selection); 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); diff --git a/src/ops/string.c b/src/ops/string.c index 7711a36bc..501e89431 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -44,208 +44,85 @@ #define LIKE_PAR_MIN_ROWS_STR 200000 #define LIKE_PAR_MIN_ROWS_SYM 100000 -/* Pattern-resolve worker for the SYM-LIKE fast path. Runs over a - * range of sym_ids; for each marked-as-seen sid, runs the matcher and - * writes the answer to lut[sid]. Pure read-only on the inputs after - * the seen-mark phase, so workers are independent. */ +/* SYM-LIKE row worker: one pass over the rows. lut[sid] is 0 while the + * symbol is unresolved, 1 for "no match", 2 for "match". A worker that + * meets an unresolved sid runs the matcher and publishes the answer, so the + * pattern runs once per distinct symbol the rows actually name — no seen + * pass, no sweep of the dictionary (which is the whole runtime symbol table, + * usually far larger than the column's vocabulary). Two workers may resolve + * the same sid at the same moment: they store the same value, the stores + * are relaxed atomics, and the duplicate work is bounded by the worker + * count. Serially this is the two-load-one-store loop the direct builtin + * always ran; the fused predicate (fused_pred.c) keeps its LUT the same way. + * Width-specialised on the SYM dictionary width. */ typedef struct { - ray_t** sym_strings; /* runtime-domain snapshot, or NULL */ - /* sym_strings == NULL ⇒ FILE-domain column (sym-domain Phase 2): - * resolve each sid through `dom` instead. The LUT is sized by - * that domain's count at setup (fused_group.c precedent). */ + const void* base; + uint8_t* dst; + uint8_t* lut; /* [dict_n], zeroed: 0 unresolved, 1 no, 2 yes */ + uint64_t dict_n; + int sym_w; + ray_t** sym_strings; /* runtime-domain snapshot, or NULL */ + /* sym_strings == NULL ⇒ FILE-domain column: resolve each sid through + * `dom`; when pinned, `raw` reads the file prefix straight from the + * mapping (no atom materialisation, no lock). */ 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; bool use_simple; const char* pat_str; size_t pat_len; -} like_resolve_ctx_t; - -/* Worker for the SYM-LIKE seen-mark phase. Marks `seen[sid] = 1` for - * every row's sym_id. Multiple workers can target the same byte, so - * the store is via __atomic_store_n with relaxed ordering — same - * machine code as a plain byte store on x86, but standard-defined - * (plain non-atomic concurrent writes are UB even when the value is - * idempotent). Width-specialised on the SYM dictionary width. */ -typedef struct { - const void* base; - uint8_t* seen; - uint64_t dict_n; - int sym_w; - /* Optional rowsel — when non-NULL, skip rows already filtered out - * by an earlier WHERE conjunct. Reduces seen[] population to just - * the surviving rows' sym_ids and short-circuits phase 2 work - * (resolve runs over the smaller seen set). */ + /* What an unknown symbol answers — an id past the dictionary, or one + * with no string — is the pattern matched against "", as for an atom + * whose string cannot be resolved. */ + uint8_t empty_match; + /* Optional rowsel — when non-NULL, rows filtered out earlier are left + * untouched (rowsel_refine reads pred[r] for surviving rows only). */ const uint8_t* sel_flg; const uint32_t* sel_offs; const uint16_t* sel_idx; uint32_t sel_n_segs; - int64_t total_rows; -} like_seen_ctx_t; - -/* Macro to mark seen[sid] for a single row at index `r`. The store - * is __atomic_store_n with relaxed ordering — workers can race on the - * same byte (different rows can resolve to the same dict ID), and the - * relaxed atomic gives UB-free semantics with the same x86 codegen as - * a plain byte store. */ -#define LIKE_SEEN_MARK(SID) \ - __atomic_store_n(&seen[(SID)], (uint8_t)1, __ATOMIC_RELAXED) -#define LIKE_SEEN_MARK_ROW(W) do { \ - if ((W) == RAY_SYM_W8) { \ - uint64_t sid = ((const uint8_t*)x->base)[r]; \ - if (sid < dict_n) LIKE_SEEN_MARK(sid); \ - } else if ((W) == RAY_SYM_W16) { \ - uint64_t sid = ((const uint16_t*)x->base)[r]; \ - if (sid < dict_n) LIKE_SEEN_MARK(sid); \ - } else if ((W) == RAY_SYM_W32) { \ - uint64_t sid = ((const uint32_t*)x->base)[r]; \ - if (sid < dict_n) LIKE_SEEN_MARK(sid); \ - } else { \ - int64_t sid = ((const int64_t*)x->base)[r]; \ - if ((uint64_t)sid < dict_n) LIKE_SEEN_MARK(sid); \ - } \ -} while (0) - -static void like_seen_fn(void* vctx, uint32_t worker_id, - int64_t start, int64_t end) { - (void)worker_id; - like_seen_ctx_t* x = (like_seen_ctx_t*)vctx; - uint8_t* seen = x->seen; - uint64_t dict_n = x->dict_n; - int sym_w = x->sym_w; - - /* Selection-aware path: walk per morsel segment and only mark - * surviving rows. When the segment is fully out, skip its row - * range entirely; when fully in, run the dense width-typed loop; - * MIX builds the per-segment in-bitmap and probes per row. */ - if (x->sel_flg) { - const uint8_t* flg = x->sel_flg; - const uint32_t* offs = x->sel_offs; - const uint16_t* lidx = x->sel_idx; - uint32_t seg_lo = (uint32_t)(start / RAY_MORSEL_ELEMS); - uint32_t seg_hi = (uint32_t)((end + RAY_MORSEL_ELEMS - 1) / RAY_MORSEL_ELEMS); - if (seg_hi > x->sel_n_segs) seg_hi = x->sel_n_segs; - for (uint32_t seg = seg_lo; seg < seg_hi; seg++) { - int64_t s_lo = (int64_t)seg * RAY_MORSEL_ELEMS; - int64_t s_hi = s_lo + RAY_MORSEL_ELEMS; - if (s_lo < start) s_lo = start; - if (s_hi > end) s_hi = end; - uint8_t f = flg[seg]; - if (f == RAY_SEL_NONE) continue; - if (f == RAY_SEL_ALL) { - for (int64_t r = s_lo; r < s_hi; r++) LIKE_SEEN_MARK_ROW(sym_w); - continue; - } - uint8_t in_seg[RAY_MORSEL_ELEMS / 8] = {0}; - uint32_t off = offs[seg]; - uint32_t cnt = offs[seg + 1] - off; - for (uint32_t i = 0; i < cnt; i++) { - uint16_t loc = lidx[off + i]; - in_seg[loc >> 3] |= (uint8_t)(1u << (loc & 7)); - } - int64_t base = (int64_t)seg * RAY_MORSEL_ELEMS; - for (int64_t r = s_lo; r < s_hi; r++) { - uint16_t loc = (uint16_t)(r - base); - if (!(in_seg[loc >> 3] & (1u << (loc & 7)))) continue; - LIKE_SEEN_MARK_ROW(sym_w); - } - } - return; - } - - /* No selection: dense width-typed loop. */ - switch (sym_w) { - case RAY_SYM_W8: { - const uint8_t* d = (const uint8_t*)x->base; - for (int64_t i = start; i < end; i++) { - uint64_t sid = d[i]; - if (sid < dict_n) LIKE_SEEN_MARK(sid); - } - break; - } - case RAY_SYM_W16: { - const uint16_t* d = (const uint16_t*)x->base; - for (int64_t i = start; i < end; i++) { - uint64_t sid = d[i]; - if (sid < dict_n) LIKE_SEEN_MARK(sid); - } - break; - } - case RAY_SYM_W32: { - const uint32_t* d = (const uint32_t*)x->base; - for (int64_t i = start; i < end; i++) { - uint64_t sid = d[i]; - if (sid < dict_n) LIKE_SEEN_MARK(sid); - } - break; - } - case RAY_SYM_W64: - default: { - const int64_t* d = (const int64_t*)x->base; - for (int64_t i = start; i < end; i++) { - int64_t sid = d[i]; - if ((uint64_t)sid < dict_n) LIKE_SEEN_MARK(sid); - } - break; - } - } +} like_rows_ctx_t; + +static inline uint8_t like_rows_resolve(const like_rows_ctx_t* x, uint64_t sid) { + uint8_t st = __atomic_load_n(&x->lut[sid], __ATOMIC_RELAXED); + if (st) return (uint8_t)(st - 1); + const char* sp = NULL; + size_t sl = 0; + if (x->raw_ok && (int64_t)sid < x->raw.count) { + sp = ray_sym_domain_raw_str(&x->raw, (int64_t)sid, &sl); + } else { + ray_t* str = x->sym_strings ? x->sym_strings[sid] + : ray_sym_domain_str(x->dom, (int64_t)sid); + if (str) { sp = ray_str_ptr(str); sl = ray_str_len(str); } + } + uint8_t m = x->empty_match; + if (sp) + m = (x->use_simple ? ray_glob_match_compiled(x->pc, sp, sl) + : ray_glob_match(sp, sl, x->pat_str, x->pat_len)) ? 1 : 0; + __atomic_store_n(&x->lut[sid], (uint8_t)(m + 1), __ATOMIC_RELAXED); + return m; } -#undef LIKE_SEEN_MARK_ROW -/* Worker for the SYM-LIKE row-projection phase. Reads the per-sid - * answer from `lut[]` and writes into the per-row bool destination. - * Workers write to disjoint slices of `dst`, so no synchronisation is - * needed. Width-specialised on the SYM dictionary width. */ -typedef struct { - const void* base; - uint8_t* dst; - const uint8_t* lut; - uint64_t dict_n; - int sym_w; - /* Optional rowsel — when non-NULL, leave dst[r] untouched for rows - * already filtered out (those positions don't matter to the caller - * since rowsel_refine only reads pred[r] for surviving rows). */ - const uint8_t* sel_flg; - const uint32_t* sel_offs; - const uint16_t* sel_idx; - uint32_t sel_n_segs; -} like_proj_ctx_t; - -#define LIKE_PROJ_SET_ROW(W) do { \ - if ((W) == RAY_SYM_W8) { \ - uint64_t sid = ((const uint8_t*)x->base)[r]; \ - dst[r] = (sid < dict_n) ? lut[sid] : 0; \ - } else if ((W) == RAY_SYM_W16) { \ - uint64_t sid = ((const uint16_t*)x->base)[r]; \ - dst[r] = (sid < dict_n) ? lut[sid] : 0; \ - } else if ((W) == RAY_SYM_W32) { \ - uint64_t sid = ((const uint32_t*)x->base)[r]; \ - dst[r] = (sid < dict_n) ? lut[sid] : 0; \ - } else { \ - int64_t sid = ((const int64_t*)x->base)[r]; \ - dst[r] = ((uint64_t)sid < dict_n) ? lut[sid] : 0; \ - } \ -} while (0) - -static void like_proj_fn(void* vctx, uint32_t worker_id, +#define LIKE_ROW(LOAD) do { \ + uint64_t sid = (uint64_t)(LOAD); \ + dst[r] = (sid < dict_n) ? like_rows_resolve(x, sid) : x->empty_match; \ + } while (0) +#define LIKE_ROW_W(W) do { \ + if ((W) == RAY_SYM_W8) LIKE_ROW(((const uint8_t*)x->base)[r]); \ + else if ((W) == RAY_SYM_W16) LIKE_ROW(((const uint16_t*)x->base)[r]); \ + else if ((W) == RAY_SYM_W32) LIKE_ROW(((const uint32_t*)x->base)[r]); \ + else LIKE_ROW(((const int64_t*)x->base)[r]); \ + } while (0) + +static void like_rows_fn(void* vctx, uint32_t worker_id, int64_t start, int64_t end) { (void)worker_id; - like_proj_ctx_t* x = (like_proj_ctx_t*)vctx; + like_rows_ctx_t* x = (like_rows_ctx_t*)vctx; uint8_t* dst = x->dst; - const uint8_t* lut = x->lut; - uint64_t dict_n = x->dict_n; - int sym_w = x->sym_w; - - /* Selection-aware path: only project rows still in the rowsel. - * Rows filtered out by an earlier WHERE conjunct have dst[r] - * undefined — that's fine because ray_rowsel_refine ignores them - * when chaining the next selection. */ + const uint64_t dict_n = x->dict_n; + const int sym_w = x->sym_w; + if (x->sel_flg) { const uint8_t* flg = x->sel_flg; const uint32_t* offs = x->sel_offs; @@ -261,7 +138,7 @@ static void like_proj_fn(void* vctx, uint32_t worker_id, uint8_t f = flg[seg]; if (f == RAY_SEL_NONE) continue; if (f == RAY_SEL_ALL) { - for (int64_t r = s_lo; r < s_hi; r++) LIKE_PROJ_SET_ROW(sym_w); + for (int64_t r = s_lo; r < s_hi; r++) LIKE_ROW_W(sym_w); continue; } uint8_t in_seg[RAY_MORSEL_ELEMS / 8] = {0}; @@ -275,7 +152,7 @@ static void like_proj_fn(void* vctx, uint32_t worker_id, for (int64_t r = s_lo; r < s_hi; r++) { uint16_t loc = (uint16_t)(r - base); if (!(in_seg[loc >> 3] & (1u << (loc & 7)))) continue; - LIKE_PROJ_SET_ROW(sym_w); + LIKE_ROW_W(sym_w); } } return; @@ -284,40 +161,29 @@ static void like_proj_fn(void* vctx, uint32_t worker_id, switch (sym_w) { case RAY_SYM_W8: { const uint8_t* d = (const uint8_t*)x->base; - for (int64_t i = start; i < end; i++) { - uint64_t sid = d[i]; - dst[i] = (sid < dict_n) ? lut[sid] : 0; - } + for (int64_t r = start; r < end; r++) LIKE_ROW(d[r]); break; } case RAY_SYM_W16: { const uint16_t* d = (const uint16_t*)x->base; - for (int64_t i = start; i < end; i++) { - uint64_t sid = d[i]; - dst[i] = (sid < dict_n) ? lut[sid] : 0; - } + for (int64_t r = start; r < end; r++) LIKE_ROW(d[r]); break; } case RAY_SYM_W32: { const uint32_t* d = (const uint32_t*)x->base; - for (int64_t i = start; i < end; i++) { - uint64_t sid = d[i]; - dst[i] = (sid < dict_n) ? lut[sid] : 0; - } + for (int64_t r = start; r < end; r++) LIKE_ROW(d[r]); break; } case RAY_SYM_W64: default: { const int64_t* d = (const int64_t*)x->base; - for (int64_t i = start; i < end; i++) { - int64_t sid = d[i]; - dst[i] = ((uint64_t)sid < dict_n) ? lut[sid] : 0; - } + for (int64_t r = start; r < end; r++) LIKE_ROW(d[r]); break; } } } -#undef LIKE_PROJ_SET_ROW +#undef LIKE_ROW_W +#undef LIKE_ROW /* Worker for the RAY_STR-LIKE parallel path. Each task scans its * row range against the (pre-compiled) glob pattern; rows are @@ -353,30 +219,6 @@ static int64_t parted_row_count(ray_t* input) { return total; } -static void like_resolve_fn(void* ctx, uint32_t worker_id, - int64_t start, int64_t end) { - (void)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; - 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)) - ? 1 : 0; - } -} - static void exec_like_parted_str(ray_t* input, uint8_t* dst, const ray_glob_compiled_t* pc, bool use_simple, @@ -402,8 +244,7 @@ static void exec_like_parted_str(ray_t* input, uint8_t* dst, .pat_str = pat_str, .pat_len = pat_len, }; - if (pool && seg_len >= LIKE_PAR_MIN_ROWS_STR && - ray_pool_total_workers(pool) >= 2) { + if (ray_pool_par_dispatch_ok(pool, seg_len, LIKE_PAR_MIN_ROWS_STR)) { ray_pool_dispatch(pool, str_like_par_fn, &lctx, seg_len); } else { str_like_par_fn(&lctx, 0, 0, seg_len); @@ -416,7 +257,7 @@ static void exec_like_parted_sym(ray_t* input, uint8_t* dst, const ray_glob_compiled_t* pc, bool use_simple, const char* pat_str, size_t pat_len, - int64_t total_len) { + uint8_t empty_match, int64_t total_len) { ray_t** segs = (ray_t**)ray_data(input); /* Cell ids are positions in the COLUMN's domain (sym-domain * Phase 2). All partitions of a parted SYM column share ONE @@ -441,83 +282,41 @@ static void exec_like_parted_sym(ray_t* input, uint8_t* dst, dict_n = (dn > 0 && dn <= (int64_t)UINT32_MAX) ? (uint32_t)dn : 0; } ray_t* lut_hdr = NULL; - ray_t* seen_hdr = NULL; - uint8_t* lut = NULL; - uint8_t* seen = NULL; - if (dict_n > 0) { - lut = (uint8_t*)scratch_alloc (&lut_hdr, (size_t)dict_n); - seen = (uint8_t*)scratch_calloc(&seen_hdr, (size_t)dict_n); - } + uint8_t* lut = dict_n > 0 ? (uint8_t*)scratch_calloc(&lut_hdr, (size_t)dict_n) : NULL; ray_pool_t* pool = ray_pool_get(); - if (lut && seen) { - for (int64_t s = 0; s < input->len; s++) { - ray_t* seg = segs[s]; - if (!seg) continue; - int64_t seg_len = seg->len; - like_seen_ctx_t sctx = { - .base = ray_data(seg), - .seen = seen, - .dict_n = (uint64_t)dict_n, - .sym_w = (int)(seg->attrs & RAY_SYM_W_MASK), - .sel_flg = NULL, - .sel_offs = NULL, - .sel_idx = NULL, - .sel_n_segs = 0, - .total_rows = seg_len, - }; - if (pool && seg_len >= LIKE_PAR_MIN_ROWS_SYM && - ray_pool_total_workers(pool) >= 2) { - ray_pool_dispatch(pool, like_seen_fn, &sctx, seg_len); - } else { - like_seen_fn(&sctx, 0, 0, seg_len); - } - } - - like_resolve_ctx_t rctx = { - .sym_strings = sym_strings, .dom = dom, .seen = seen, .lut = lut, - .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); - + if (lut) { + /* One LUT for every segment: the partitions share the domain, so a + * symbol resolved in one segment is known in the next. */ + ray_sym_domain_raw_t raw; + bool raw_ok = dom ? ray_sym_domain_raw_pin(dom, &raw) : false; int64_t out_off = 0; for (int64_t s = 0; s < input->len; s++) { ray_t* seg = segs[s]; if (!seg) continue; int64_t seg_len = seg->len; - like_proj_ctx_t pctx = { - .base = ray_data(seg), - .dst = dst + out_off, - .lut = lut, - .dict_n = (uint64_t)dict_n, - .sym_w = (int)(seg->attrs & RAY_SYM_W_MASK), - .sel_flg = NULL, - .sel_offs = NULL, - .sel_idx = NULL, - .sel_n_segs = 0, + like_rows_ctx_t rctx = { + .base = ray_data(seg), .dst = dst + out_off, .lut = lut, + .dict_n = (uint64_t)dict_n, + .sym_w = (int)(seg->attrs & RAY_SYM_W_MASK), + .sym_strings = sym_strings, .dom = dom, .raw = raw, .raw_ok = raw_ok, + .pc = pc, .use_simple = use_simple, + .pat_str = pat_str, .pat_len = pat_len, + .empty_match = empty_match, }; - if (pool && seg_len >= LIKE_PAR_MIN_ROWS_SYM && - ray_pool_total_workers(pool) >= 2) { - ray_pool_dispatch(pool, like_proj_fn, &pctx, seg_len); + if (ray_pool_par_dispatch_ok(pool, seg_len, LIKE_PAR_MIN_ROWS_SYM)) { + ray_pool_dispatch(pool, like_rows_fn, &rctx, seg_len); } else { - like_proj_fn(&pctx, 0, 0, seg_len); + like_rows_fn(&rctx, 0, 0, seg_len); } out_off += seg_len; } + if (raw_ok) ray_sym_domain_raw_unpin(dom); scratch_free(lut_hdr); - scratch_free(seen_hdr); return; } if (lut_hdr) scratch_free(lut_hdr); - if (seen_hdr) scratch_free(seen_hdr); int64_t out_off = 0; for (int64_t s = 0; s < input->len; s++) { @@ -529,7 +328,7 @@ static void exec_like_parted_sym(ray_t* input, uint8_t* dst, ray_t* str = dom ? ray_sym_domain_str(dom, sym_id) : (sym_strings && (uint64_t)sym_id < (uint64_t)dict_n) ? sym_strings[sym_id] : NULL; - if (!str) { dst[out_off + i] = 0; continue; } + if (!str) { dst[out_off + i] = empty_match; continue; } const char* sp = ray_str_ptr(str); size_t sl = ray_str_len(str); dst[out_off + i] = (use_simple @@ -571,30 +370,17 @@ static ray_t* exec_like_input(ray_graph_t* g, ray_op_t* input_op) { return exec_node(g, input_op); } -ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { - ray_t* input = exec_like_input(g, op_child(g, op, 0)); - ray_t* pat_v = exec_node(g, op_child(g, op, 1)); - if (!input || RAY_IS_ERR(input)) { if (pat_v && !RAY_IS_ERR(pat_v)) ray_release(pat_v); return input; } - if (!pat_v || RAY_IS_ERR(pat_v)) { ray_release(input); return pat_v; } - +/* LIKE over a whole STR / SYM column (flat or parted): the parallel kernel + * shared by the DAG executor (exec_like) and the direct builtin (ray_like_fn), + * so `(like col pat)` and `where: (like col pat)` run the same code — one + * pattern resolve per distinct symbol, the row passes spread over the worker + * pool. `selection` is the executor's rowsel, or NULL for every row. + * Borrows `input` and `pat_v`; returns an owned BOOL vector. */ +ray_t* ray_like_vec(ray_t* input, ray_t* pat_v, ray_t* selection) { int8_t in_type = input->type; bool in_parted = RAY_IS_PARTED(in_type); int8_t base_type = in_parted ? (int8_t)RAY_PARTED_BASETYPE(in_type) : in_type; - /* Shapes this executor doesn't own — scalar subjects, list-of-atom - * columns (the legacy STRL splayed-load shape), unsupported types — - * delegate to the direct builtin BEFORE reading input->len or - * allocating: an atom's SSO bytes alias ->len, so the result alloc - * below would request a garbage capacity, and the old fallthrough - * memset made unsupported predicates silently match nothing. */ - bool vec_shape = in_parted ? (base_type == RAY_STR || RAY_IS_SYM(base_type)) - : (in_type == RAY_STR || RAY_IS_SYM(in_type)); - if (!vec_shape) { - ray_t* r = ray_like_fn(input, pat_v); - ray_release(input); ray_release(pat_v); - return r; - } - /* Get pattern string */ const char* pat_str = ray_str_ptr(pat_v); size_t pat_len = ray_str_len(pat_v); @@ -605,20 +391,19 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { * for the very common `*literal*` shape. */ ray_glob_compiled_t pc = ray_glob_compile(pat_str, pat_len); bool use_simple = pc.shape != RAY_GLOB_SHAPE_NONE; + uint8_t empty_match = (use_simple ? ray_glob_match_compiled(&pc, "", 0) + : ray_glob_match("", 0, pat_str, pat_len)) ? 1 : 0; int64_t len = in_parted ? parted_row_count(input) : input->len; ray_t* result = ray_vec_new(RAY_BOOL, len); - if (!result || RAY_IS_ERR(result)) { - ray_release(input); ray_release(pat_v); - return result; - } + if (!result || RAY_IS_ERR(result)) return result; /* input/pat_v are borrowed */ result->len = len; uint8_t* dst = (uint8_t*)ray_data(result); if (in_parted && base_type == RAY_STR) { exec_like_parted_str(input, dst, &pc, use_simple, pat_str, pat_len); } else if (in_parted && RAY_IS_SYM(base_type)) { - exec_like_parted_sym(input, dst, &pc, use_simple, pat_str, pat_len, len); + exec_like_parted_sym(input, dst, &pc, use_simple, pat_str, pat_len, empty_match, len); } else if (in_type == RAY_STR) { /* Parallel substring/glob match over RAY_STR. Wide text scans * over URL/title-like columns are memory-bandwidth bound; the @@ -637,33 +422,19 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { .pat_len = pat_len, }; ray_pool_t* str_pool = ray_pool_get(); - if (str_pool && len >= LIKE_PAR_MIN_ROWS_STR && ray_pool_total_workers(str_pool) >= 2) { + if (ray_pool_par_dispatch_ok(str_pool, len, LIKE_PAR_MIN_ROWS_STR)) { ray_pool_dispatch(str_pool, str_like_par_fn, &lctx, len); } else { str_like_par_fn(&lctx, 0, 0, len); } } else if (RAY_IS_SYM(in_type)) { - /* Dictionary-cached fast path. - * - * Three-phase pipeline: - * (1) seen-mark — single sequential row scan that flips a - * byte in `seen[]` for every referenced sym_id. Cheap; - * just sets a byte per row. - * (2) parallel pattern resolve — partition the dict_n range - * across pool workers; for each sid where seen[sid]==1, - * run the matcher and store the answer in lut[sid]. - * (3) parallel row projection — every row reads lut[sid_i]. - * - * Splitting the resolve from the row scan lets phase (2) drive - * the pattern matcher (memmem on long URL strings) across the - * worker pool. ray_sym_count is the GLOBAL dictionary so for - * a low-card column like BrowserCountry phase (1) keeps the - * resolve work bounded to that column's actual sym_ids. */ + /* Dictionary-cached path: the pattern runs once per distinct symbol + * the rows name, in the same parallel pass that writes the rows + * (like_rows_fn). Cell ids are positions in the COLUMN's domain. + * Runtime domain: borrow the global string snapshot (lock-free per + * sid). FILE domain: LUT sized by the domain's count, strings from + * the pinned mapping. */ const void* base = ray_data(input); - /* Cell ids are positions in the COLUMN's domain (sym-domain - * Phase 2). Runtime: borrow the global snapshot. FILE: LUT - * sized by the domain's count, resolved via ray_sym_domain_str - * (fused_group precedent). Pre-flip: always runtime. */ struct ray_sym_domain_s* dom = ray_sym_vec_domain(input); ray_t** sym_strings = NULL; uint32_t dict_n = 0; @@ -675,93 +446,41 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { dict_n = (dn > 0 && dn <= (int64_t)UINT32_MAX) ? (uint32_t)dn : 0; } ray_t* lut_hdr = NULL; - ray_t* seen_hdr = NULL; - uint8_t* lut = NULL; - uint8_t* seen = NULL; - if (dict_n > 0) { - lut = (uint8_t*)scratch_alloc (&lut_hdr, (size_t)dict_n); - seen = (uint8_t*)scratch_calloc(&seen_hdr, (size_t)dict_n); - } - if (lut && seen) { - int sym_w = (int)(input->attrs & RAY_SYM_W_MASK); - - ray_pool_t* pool = ray_pool_get(); - /* Pass 1: mark used sym_ids. Parallelised because for - * high-cardinality text columns the seen- - * mark scan was a 5 ms-class serial pass. Multiple workers - * may write 1 to the same byte concurrently — the value is - * idempotent so the race is benign. */ - like_seen_ctx_t sctx = { - .base = base, - .seen = seen, - .dict_n = (uint64_t)dict_n, - .sym_w = sym_w, - .sel_flg = NULL, - .sel_offs = NULL, - .sel_idx = NULL, - .sel_n_segs = 0, - .total_rows = len, - }; - if (g->selection) { - ray_rowsel_t* sm = ray_rowsel_meta(g->selection); - sctx.sel_flg = ray_rowsel_flags(g->selection); - sctx.sel_offs = ray_rowsel_offsets(g->selection); - sctx.sel_idx = ray_rowsel_idx(g->selection); - sctx.sel_n_segs = sm->n_segs; - } - if (pool && len >= LIKE_PAR_MIN_ROWS_SYM && ray_pool_total_workers(pool) >= 2) { - ray_pool_dispatch(pool, like_seen_fn, &sctx, len); - } else { - like_seen_fn(&sctx, 0, 0, len); - } - - /* Pass 2: parallel pattern resolve over the dict range. */ - like_resolve_ctx_t rctx = { - .sym_strings = sym_strings, .dom = dom, .seen = seen, .lut = lut, + uint8_t* lut = dict_n > 0 ? (uint8_t*)scratch_calloc(&lut_hdr, (size_t)dict_n) : NULL; + if (lut) { + like_rows_ctx_t rctx = { + .base = base, .dst = dst, .lut = lut, .dict_n = (uint64_t)dict_n, + .sym_w = (int)(input->attrs & RAY_SYM_W_MASK), + .sym_strings = sym_strings, .dom = dom, .pc = &pc, .use_simple = use_simple, .pat_str = pat_str, .pat_len = pat_len, + .empty_match = empty_match, }; + if (selection) { + ray_rowsel_t* sm = ray_rowsel_meta(selection); + rctx.sel_flg = ray_rowsel_flags(selection); + rctx.sel_offs = ray_rowsel_offsets(selection); + rctx.sel_idx = ray_rowsel_idx(selection); + rctx.sel_n_segs = sm->n_segs; + } 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); + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, len, LIKE_PAR_MIN_ROWS_SYM)) { + ray_pool_dispatch(pool, like_rows_fn, &rctx, len); } else { - like_resolve_fn(&rctx, 0, 0, (int64_t)dict_n); + like_rows_fn(&rctx, 0, 0, len); } 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 - * serial on a W64 SYM column). Width-specialised in the - * worker fn so the inner load is a typed pointer dereference. */ - like_proj_ctx_t pctx = { - .base = base, - .dst = dst, - .lut = lut, - .dict_n = (uint64_t)dict_n, - .sym_w = sym_w, - .sel_flg = sctx.sel_flg, - .sel_offs = sctx.sel_offs, - .sel_idx = sctx.sel_idx, - .sel_n_segs = sctx.sel_n_segs, - }; - if (pool && len >= LIKE_PAR_MIN_ROWS_SYM && ray_pool_total_workers(pool) >= 2) { - ray_pool_dispatch(pool, like_proj_fn, &pctx, len); - } else { - like_proj_fn(&pctx, 0, 0, len); - } - scratch_free(lut_hdr); - scratch_free(seen_hdr); } else { /* OOM building the LUT: fall back to per-row scan. */ if (lut_hdr) scratch_free(lut_hdr); - if (seen_hdr) scratch_free(seen_hdr); for (int64_t i = 0; i < len; i++) { int64_t sym_id = ray_read_sym(base, i, in_type, input->attrs); ray_t* s = dom ? ray_sym_domain_str(dom, sym_id) : (sym_strings && (uint64_t)sym_id < (uint64_t)dict_n) ? sym_strings[sym_id] : NULL; - if (!s) { dst[i] = 0; continue; } + if (!s) { dst[i] = empty_match; continue; } const char* sp = ray_str_ptr(s); size_t sl = ray_str_len(s); dst[i] = (use_simple @@ -771,6 +490,34 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { } } + return result; +} + +ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { + ray_t* input = exec_like_input(g, op_child(g, op, 0)); + ray_t* pat_v = exec_node(g, op_child(g, op, 1)); + if (!input || RAY_IS_ERR(input)) { if (pat_v && !RAY_IS_ERR(pat_v)) ray_release(pat_v); return input; } + if (!pat_v || RAY_IS_ERR(pat_v)) { ray_release(input); return pat_v; } + + int8_t in_type = input->type; + bool in_parted = RAY_IS_PARTED(in_type); + int8_t base_type = in_parted ? (int8_t)RAY_PARTED_BASETYPE(in_type) : in_type; + + /* Shapes this executor doesn't own — scalar subjects, list-of-atom + * columns (the legacy STRL splayed-load shape), unsupported types — + * delegate to the direct builtin BEFORE reading input->len or + * allocating: an atom's SSO bytes alias ->len, so the result alloc + * below would request a garbage capacity, and the old fallthrough + * memset made unsupported predicates silently match nothing. */ + bool vec_shape = in_parted ? (base_type == RAY_STR || RAY_IS_SYM(base_type)) + : (in_type == RAY_STR || RAY_IS_SYM(in_type)); + if (!vec_shape) { + ray_t* r = ray_like_fn(input, pat_v); + ray_release(input); ray_release(pat_v); + return r; + } + + ray_t* result = ray_like_vec(input, pat_v, g->selection); ray_release(input); ray_release(pat_v); return result; } diff --git a/src/ops/strop.c b/src/ops/strop.c index 224b978cc..3aba16454 100644 --- a/src/ops/strop.c +++ b/src/ops/strop.c @@ -938,158 +938,15 @@ ray_t* ray_like_fn(ray_t* x, ray_t* pattern) { return make_bool(m ? 1 : 0); } - /* Vector: map over elements */ - if (ray_is_vec(x) && (x->type == RAY_SYM || x->type == RAY_STR)) { - int64_t n = ray_len(x); - ray_t* result = ray_vec_new(RAY_BOOL, n); - if (RAY_IS_ERR(result)) return result; - result->len = n; - uint8_t* out = (uint8_t*)ray_data(result); - - if (x->type == RAY_SYM) { - /* SYM column is dictionary-encoded with adaptive widths - * (W8/W16/W32/W64). Two bugs to avoid: - * (a) Reading the column as int64_t* is wrong for any - * width != W64 — must use ray_read_sym. - * (b) ray_sym_str returns a borrowed pointer; releasing - * it would decrement the global sym table entry. - * - * Fast path: a SYM column with N rows references at most - * D = ray_sym_count() distinct sym_ids. Build a - * sym_id → bool LUT with a "seen" bitmap so each sym_id - * runs the glob matcher at most once. For LIKE on URL - * (1.7M unique values, 5M rows) this turns an O(n_rows) - * pattern-scan into O(n_distinct + n_rows) — the second - * pass is a single byte load + table lookup per row. */ - const void* base = ray_data(x); - int8_t in_type = x->type; - uint8_t in_attrs = x->attrs; - - /* The global sym table can be much larger than the set of - * IDs this column references (e.g. BrowserCountry with 54 - * uniques in a process that's also loaded URL with 1.7M - * uniques). Lazy-resolve via the seen bitmap so we only - * match against sym_ids actually touched. ray_sym_strings_borrow - * snapshots the strings array under one lock so each lookup - * is a plain pointer load. */ - /* Cell ids are positions in the COLUMN's domain (sym-domain - * Phase 2). Runtime: borrow the global snapshot (below). - * FILE: size the LUT by the domain's count and resolve via - * ray_sym_domain_str (fused_group precedent). Pre-flip - * this is always the runtime branch. */ - struct ray_sym_domain_s* dom = ray_sym_vec_domain(x); - ray_t** sym_strings = NULL; - uint32_t dict_n = 0; - if (dom == ray_sym_runtime_domain()) { - dom = NULL; - ray_sym_strings_borrow(&sym_strings, &dict_n); - } else { - int64_t dn = ray_sym_domain_count(dom); - dict_n = (dn > 0 && dn <= (int64_t)UINT32_MAX) ? (uint32_t)dn : 0; - } - ray_t* lut_hdr = NULL; - ray_t* seen_hdr = NULL; - uint8_t* lut = NULL; - uint8_t* seen = NULL; - if (dict_n > 0) { - lut = (uint8_t*)scratch_alloc (&lut_hdr, (size_t)dict_n); - seen = (uint8_t*)scratch_calloc(&seen_hdr, (size_t)dict_n); - } - if (lut && seen) { - /* Out-of-range sym IDs ("unknown" or "missing") match - * the pattern as if the string were empty — same - * semantics as the OOM fallback at line 332 below and - * the atom case at line 217 above (sym_str==NULL → ""). - * Compute the empty-string match once so the row pass - * can short-circuit out-of-range sids without taking - * the matcher per row. */ - uint8_t empty_match = (use_simple - ? ray_glob_match_compiled(&pc, "", 0) - : ray_glob_match("", 0, pat, pat_len)) - ? 1 : 0; - - /* First pass: discover the unique sym_ids referenced and - * resolve each pattern match exactly once. Second pass: - * width-specialised LUT projection so the per-row loop - * is a tight gather. */ - int sym_w = (int)(in_attrs & RAY_SYM_W_MASK); - #define DICT_PASS(LOAD) \ - for (int64_t i = 0; i < n; i++) { \ - int64_t sid = (LOAD); \ - if ((uint64_t)sid >= (uint64_t)dict_n) continue; \ - if (!seen[sid]) { \ - ray_t* s = sym_strings ? sym_strings[sid] \ - : ray_sym_domain_str(dom, sid); \ - const char* sp = s ? ray_str_ptr(s) : ""; \ - size_t sl = s ? ray_str_len(s) : 0; \ - lut[sid] = (use_simple \ - ? ray_glob_match_compiled(&pc, sp, sl)\ - : ray_glob_match(sp, sl, pat, pat_len)) \ - ? 1 : 0; \ - seen[sid] = 1; \ - } \ - } - #define ROW_PASS(LOAD) \ - for (int64_t i = 0; i < n; i++) { \ - int64_t sid = (LOAD); \ - out[i] = ((uint64_t)sid < (uint64_t)dict_n) \ - ? lut[sid] \ - : empty_match; \ - } - switch (sym_w) { - case RAY_SYM_W8: { - const uint8_t* d = (const uint8_t*)base; - DICT_PASS(d[i]) ROW_PASS(d[i]) break; - } - case RAY_SYM_W16: { - const uint16_t* d = (const uint16_t*)base; - DICT_PASS(d[i]) ROW_PASS(d[i]) break; - } - case RAY_SYM_W32: { - const uint32_t* d = (const uint32_t*)base; - DICT_PASS(d[i]) ROW_PASS(d[i]) break; - } - case RAY_SYM_W64: - default: { - const int64_t* d = (const int64_t*)base; - DICT_PASS(d[i]) ROW_PASS(d[i]) break; - } - } - #undef DICT_PASS - #undef ROW_PASS - scratch_free(lut_hdr); - scratch_free(seen_hdr); - } else { - /* OOM building the LUT: fall back to per-row scan. Still - * uses ray_read_sym for adaptive-width correctness. */ - if (lut_hdr) scratch_free(lut_hdr); - if (seen_hdr) scratch_free(seen_hdr); - for (int64_t i = 0; i < n; i++) { - int64_t sid = ray_read_sym(base, i, in_type, in_attrs); - ray_t* s = dom ? ray_sym_domain_str(dom, sid) - : (sym_strings && (uint64_t)sid < (uint64_t)dict_n) - ? sym_strings[sid] : NULL; - const char* sp = s ? ray_str_ptr(s) : ""; - size_t sl = s ? ray_str_len(s) : 0; - out[i] = (use_simple - ? ray_glob_match_compiled(&pc, sp, sl) - : ray_glob_match(sp, sl, pat, pat_len)) ? 1 : 0; - } - } - } else { - /* RAY_STR vector */ - for (int64_t i = 0; i < n; i++) { - size_t slen; - const char* s = ray_str_vec_get(x, i, &slen); - bool m = false; - if (s) { - m = use_simple ? ray_glob_match_compiled(&pc, s, slen) - : ray_glob_match(s, slen, pat, pat_len); - } - out[i] = m ? 1 : 0; - } - } - return result; + /* Whole STR / SYM column, flat or parted: the kernel the executor + * runs for `where: (like col pat)` — one pattern resolve per distinct + * symbol, row passes over the worker pool (ops/string.c). */ + if (ray_is_vec(x) && (x->type == RAY_SYM || x->type == RAY_STR)) + return ray_like_vec(x, pattern, NULL); + if (RAY_IS_PARTED(x->type)) { + int8_t base = (int8_t)RAY_PARTED_BASETYPE(x->type); + if (base == RAY_STR || RAY_IS_SYM(base)) + return ray_like_vec(x, pattern, NULL); } /* List of string/symbol atoms — the shape splayed string columns diff --git a/test/rfl/strop/like_vector.rfl b/test/rfl/strop/like_vector.rfl new file mode 100644 index 000000000..cb4ddae44 --- /dev/null +++ b/test/rfl/strop/like_vector.rfl @@ -0,0 +1,48 @@ +;; `like` over a whole column, called directly, runs the same kernel as +;; `select … where: (like …)`: one pattern match per distinct symbol, the row +;; pass over the worker pool. Sizes past the parallel thresholds (SYM +;; 100000 rows, STR 200000) so the pooled path runs; every answer must equal +;; the select form and the same match over the plain strings. +(set N 240000) +(set i (til N)) +;; low cardinality (8-bit dictionary width) and high cardinality (wider ids) +(set lo (as 'SYMBOL (map (fn [k] (format "site%.example.com" (% k 40))) i))) +(set hi (as 'SYMBOL (map (fn [k] (format "http://h%.example.com/p/%/%" (% k 700) (% (* 31 k) 977) k)) i))) +(set losv (as 'STR lo)) +(set hisv (as 'STR hi)) +(set T (table [lo hi losv hisv] (list lo hi losv hisv))) +(count T) -- 240000 +;; SYM, 8-bit ids: prefix / contains / exact / class / any / none +(all (== (like lo "site1*") (like losv "site1*"))) -- true +(== (sum (as 'I64 (like lo "site1*"))) (count (select {from: T where: (like lo "site1*")}))) -- true +(all (== (like lo "*7.example*") (like losv "*7.example*"))) -- true +(== (sum (as 'I64 (like lo "*7.example*"))) (count (select {from: T where: (like lo "*7.example*")}))) -- true +(all (== (like lo "site12.example.com") (like losv "site12.example.com"))) -- true +(sum (as 'I64 (like lo "site12.example.com"))) -- 6000 +(all (== (like lo "site[12]?.example.com") (like losv "site[12]?.example.com"))) -- true +(sum (as 'I64 (like lo "*"))) -- 240000 +(sum (as 'I64 (like lo "nothing*"))) -- 0 +;; SYM, wide ids +(all (== (like hi "http://h1*") (like hisv "http://h1*"))) -- true +(== (sum (as 'I64 (like hi "http://h1*"))) (count (select {from: T where: (like hi "http://h1*")}))) -- true +(all (== (like hi "*/p/5/*") (like hisv "*/p/5/*"))) -- true +(== (sum (as 'I64 (like hi "*/p/5/*"))) (count (select {from: T where: (like hi "*/p/5/*")}))) -- true +(all (== (like hi "*/p/5/[0-9]") (like hisv "*/p/5/[0-9]"))) -- true +(all (== (like hi "http://h12.example.com/p/492/*") (like hisv "http://h12.example.com/p/492/*"))) -- true +;; STR column past its own parallel threshold +(== (sum (as 'I64 (like hisv "*/p/5/*"))) (count (select {from: T where: (like hisv "*/p/5/*")}))) -- true +(== (sum (as 'I64 (like losv "site1*"))) (count (select {from: T where: (like losv "site1*")}))) -- true +;; the direct form and the select form agree with `==` on an exact pattern +(sum (as 'I64 (like hi "http://h3.example.com/p/93/3"))) -- 1 +;; a parted table: the select form runs the kernel per segment, the direct +;; form gets the column materialised flat — both must agree +(.sys.exec "rm -rf /tmp/rfl_like_vec_p") -- 0 +(set P1 (table [s] (list (as 'SYMBOL (map (fn [k] (format "a%" (% k 9))) (til 120000)))))) +(set P2 (table [s] (list (as 'SYMBOL (map (fn [k] (format "b%" (% k 9))) (til 120000)))))) +(.db.splayed.set "/tmp/rfl_like_vec_p/1/t/" P1) +(.db.splayed.set "/tmp/rfl_like_vec_p/2/t/" P2) +(set PT (.db.parted.get "/tmp/rfl_like_vec_p/" 't)) +(== (sum (as 'I64 (like (at PT 's) "a*"))) (count (select {from: PT where: (like s "a*")}))) -- true +(sum (as 'I64 (like (at PT 's) "a*"))) -- 120000 +(sum (as 'I64 (like (at PT 's) "?3"))) -- 26666 +(sum (as 'I64 (like (at PT 's) "*"))) -- 240000 From f35846a99e9e563de24c14a7ce7fd0030969c555 Mon Sep 17 00:00:00 2001 From: Evgen Belozerov Date: Fri, 25 Sep 2026 19:20:38 +0200 Subject: [PATCH 28/29] fix(system): report arity errors for extra arguments (#616) --- docs/docs/language/functions.md | 2 +- docs/docs/namespaces/sys.md | 10 +++++----- docs/docs/reference/all-functions.md | 2 +- src/lang/syscmd.c | 2 ++ src/ops/system.c | 3 ++- test/rfl/system/syscmd_coverage.rfl | 12 +++++++----- test/rfl/system/system_branch_cov2.rfl | 1 + 7 files changed, 19 insertions(+), 13 deletions(-) diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index 943e1b78a..7580b8e64 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -516,7 +516,7 @@ spills exactly as it did before. | `.time.timer.del` | unary, restricted | Cancel a scheduled timer by id. Returns null. | `(.time.timer.del 0)` | | `.sys.args` | nullary | Application arguments as a typed dict (`user` subdict for post-`--` args) | `(.sys.args)` | | `env` | unary | List all global environment bindings | `(env 0)` | -| `.sys.build` | variadic | Build metadata: `version` + `build-date` | `(.sys.build)` | +| `.sys.build` | nullary | Build metadata: `version` + `build-date` | `(.sys.build)` | | `.sys.mem` | variadic | Memory allocator statistics (alloc/peak/slab) | `(.sys.mem)` | | `.sys.info` | variadic | System information (cores, page size, memory) | `(.sys.info)` | diff --git a/docs/docs/namespaces/sys.md b/docs/docs/namespaces/sys.md index f6eefbffb..f1c8a1e87 100644 --- a/docs/docs/namespaces/sys.md +++ b/docs/docs/namespaces/sys.md @@ -10,18 +10,18 @@ Process-level introspection (build, memory, host info) and command-style operati | Function | Arity | Flags | Description | |---|---|---|---| | [`.sys.args`](#sys-args) | variadic | — | Command-line arguments as a typed dict. | -| [`.sys.build`](#sys-build) | variadic | — | Version + build date as a dict. | +| [`.sys.build`](#sys-build) | nullary | — | Version + build date as a dict. | | [`.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.env`](#sys-env) | variadic (0–1) | — | Count or list of globally bound names. | | [`.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. | +| [`.sys.timeit`](#sys-timeit) | variadic (0–1) | — | Toggle / set the per-expression profiler. | ## `.sys.args` { #sys-args } @@ -244,7 +244,7 @@ GC, not a tracing object collector. Returns `0`. ## `.sys.env` { #sys-env } -Signature: `(.sys.env)`. From a script / IPC context returns the **count** of globally bound names (i64). In a REPL context the same dispatcher prints one line per binding (name + type label) and returns null — the variadic registration accommodates both forms. +Signature: `(.sys.env [compat-arg])`. From a script / IPC context returns the **count** of globally bound names (i64). In a REPL context the same dispatcher prints one line per binding (name + type label) and returns null. At most one optional compatibility argument is accepted; additional arguments return an `arity` error. ```lisp (.sys.env) @@ -330,7 +330,7 @@ Errors: `type` (port not an int / not parseable from string), `domain` (port out ## `.sys.timeit` { #sys-timeit } -Signature: `(.sys.timeit [flag])`. Toggles the per-expression profiler. Calling with no argument flips the current state; passing `0` disables, anything non-zero enables. Returns the new state as `i64` (0/1). +Signature: `(.sys.timeit [flag])`. Toggles the per-expression profiler. Calling with no argument flips the current state; passing `0` disables, anything non-zero enables. Returns the new state as `i64` (0/1). More than one argument returns an `arity` error. ```lisp (.sys.timeit 1) ;; enable profiling diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index eba0d980b..2c3e552ec 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -655,7 +655,7 @@ System interaction, metaprogramming, diagnostics, and runtime inspection. | `.time.now` | variadic | — | Monotonic time in milliseconds | `(.time.now)` | | `.time.timer.set` | variadic | restricted | Schedule callback every `ms`, `num` times (0 = forever); returns id | `(.time.timer.set 1000 0 (fn [t] (println t)))` | | `.time.timer.del` | unary | restricted | Cancel a scheduled timer by id; returns null | `(.time.timer.del 0)` | -| `.sys.build` | variadic | — | Build metadata dict with `version` + `build-date` | `(.sys.build)` | +| `.sys.build` | nullary | — | Build metadata dict with `version` + `build-date` | `(.sys.build)` | | `.sys.mem` | variadic | — | Memory allocator statistics (alloc / peak / slab hits) | `(.sys.mem)` | | `.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)` | diff --git a/src/lang/syscmd.c b/src/lang/syscmd.c index 9fd7b44c6..62f613c97 100644 --- a/src/lang/syscmd.c +++ b/src/lang/syscmd.c @@ -424,9 +424,11 @@ ray_t* ray_sys_listen_fn(ray_t* x) { return invoke_by_name("listen", x); } * matches `.sys.gc`'s convention and avoids the arity error users * would otherwise hit calling `(.sys.env)` with no args. */ ray_t* ray_sys_timeit_fn(ray_t** args, int64_t n) { + if (n > 1) return ray_error("arity", ".sys.timeit accepts at most one argument"); return invoke_by_name("timeit", n > 0 ? args[0] : RAY_NULL_OBJ); } ray_t* ray_sys_env_fn(ray_t** args, int64_t n) { + if (n > 1) return ray_error("arity", ".sys.env accepts at most one argument"); (void)args; return invoke_by_name("env", n > 0 ? args[0] : RAY_NULL_OBJ); } diff --git a/src/ops/system.c b/src/ops/system.c index 6d5a55cce..6c0a2627f 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -1229,7 +1229,8 @@ ray_t* ray_env_fn(ray_t* x) { /* (.sys.build) -- return dict with internal build information */ ray_t* ray_internals_fn(ray_t** args, int64_t n) { - (void)args; (void)n; + (void)args; + if (n != 0) return ray_error("arity", ".sys.build takes no arguments"); ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 2); if (RAY_IS_ERR(keys)) return keys; ray_t* vals = ray_list_new(2); diff --git a/test/rfl/system/syscmd_coverage.rfl b/test/rfl/system/syscmd_coverage.rfl index a69bf0af6..656cda9f4 100644 --- a/test/rfl/system/syscmd_coverage.rfl +++ b/test/rfl/system/syscmd_coverage.rfl @@ -113,17 +113,19 @@ (.sys.timeit) -- 1 (.sys.timeit) -- 0 -;; ────────────── ray_sys_timeit_fn: variadic with extra args ignored ────── -;; The variadic adapter (line 353) only forwards the first arg. +;; ────────────── ray_sys_timeit_fn: optional arg + arity guard ────────── +;; The variadic adapter accepts zero or one arg, and rejects extras before +;; changing profiler state. (.sys.timeit 1) -- 1 (.sys.timeit 0) -- 0 +(.sys.timeit 1 0) !- arity -;; ────────────── h_env: count > 0 + variadic with arg branch ────────────── -;; ray_sys_env_fn takes optional arg via variadic adapter (line 356); -;; arg is ignored by h_env (line 164). Both call shapes work. +;; ────────────── h_env: count > 0 + optional compatibility arg ────────── +;; ray_sys_env_fn accepts zero or one arg and rejects extras before h_env runs. (> (.sys.env) 0) -- true (> (.sys.env 1) 0) -- true (> (.sys.env "x") 0) -- true +(.sys.env 1 2) !- arity ;; ────────────── h_listen: domain / type / io branches ────────────── ;; The test runtime (test/main.c rfl_setup) registers a poll instance — diff --git a/test/rfl/system/system_branch_cov2.rfl b/test/rfl/system/system_branch_cov2.rfl index 73a2d595c..eaf7ebdde 100644 --- a/test/rfl/system/system_branch_cov2.rfl +++ b/test/rfl/system/system_branch_cov2.rfl @@ -101,6 +101,7 @@ (type (.sys.build)) -- 'DICT (count (.sys.build)) -- 2 (type (at (.sys.build) 'version)) -- 'str +(.sys.build 1) !- arity ;; ══════════════════════════════════════════════════════════════════════ ;; ray_memstat_fn (.sys.mem) (lines 703-728) From fb426dcd45c06f72513d40205b544932e56bd3e2 Mon Sep 17 00:00:00 2001 From: Anton Kundenko Date: Fri, 25 Sep 2026 20:46:17 +0200 Subject: [PATCH 29/29] fix(in): admit the typed kernel for text columns, which it never reached (#607) --- src/ops/collection.c | 17 +++++++++++++++-- test/rfl/collection/in.rfl | 39 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/ops/collection.c b/src/ops/collection.c index b9ac009d8..6b20c4b24 100644 --- a/src/ops/collection.c +++ b/src/ops/collection.c @@ -1374,8 +1374,21 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { * the WHERE kernel uses null-matches-nothing semantics — the * two must not be conflated. NULL result = unsupported shape * (STR etc.): fall through to the hashset probe below. */ - if (!ray_vec_may_have_nulls(val) && - !ray_vec_may_have_nulls(vec)) { + /* Admission check, so it uses the EXACT ray_vec_has_nulls rather + * than the conservative row-kernel gate. ray_vec_may_have_nulls + * returns true unconditionally for SYM and STR — their null is a + * payload value, not an attribute bit — so gating this on it made + * the branch unreachable for every text column, including the SYM + * verdict-LUT the kernel carries specifically for them. Every + * `in` over a symbol column fell through to the generic per-row + * hashset probe: ~4.8 ms against ~40 us for the equivalent `==` + * on a 351k-row column (#593). vec.h says as much where it + * defines the two — "paths requiring null-free data use has_nulls + * below". The exact check costs one pass and is not on a per-row + * path; a null-bearing operand still falls through, because the + * kernel's null-matches-nothing semantics differ from this path's + * null-equals-null. */ + if (!ray_vec_has_nulls(val) && !ray_vec_has_nulls(vec)) { ray_t* fast = ray_in_vec_exec(val, vec, false); if (fast) return fast; } diff --git a/test/rfl/collection/in.rfl b/test/rfl/collection/in.rfl index fbead052c..026417e41 100644 --- a/test/rfl/collection/in.rfl +++ b/test/rfl/collection/in.rfl @@ -84,3 +84,42 @@ (in [1h 2h 3h] [3h 2h 1h]) -- [true true true] ;; Test with empty arrays (in (list) [1h 2h]) -- (list) + +;; ========== TEXT (SYM/STR) NULL SEMANTICS (#593) ========== +;; `in` admits the typed verdict-LUT kernel only when BOTH sides are exactly +;; null-free, because that kernel uses null-matches-nothing semantics while +;; this path is null-equals-null. The gate used to ask +;; ray_vec_may_have_nulls, which is unconditionally true for SYM and STR +;; (their null is a payload value, not an attribute bit) — so the kernel was +;; unreachable for text columns and every symbol `in` fell through to the +;; generic per-row hashset probe. These pin the semantics on both sides of +;; that gate so the admission check cannot drift back. + +;; null in the COLUMN, null needle — null equals null +(in (as 'SYM ["a" "" "b"]) (as 'SYM [""])) -- [false true false] +(in ["a" "" "b"] [""]) -- [false true false] + +;; null in the column, non-null needle — the null matches nothing else +(in (as 'SYM ["a" "" "b"]) (as 'SYM ["a"])) -- [true false false] + +;; null only in the NEEDLES: the column is null-free but the gate must still +;; reject, since a null needle needs null-equals-null against nothing +(in (as 'SYM ["a" "b"]) (as 'SYM ["" "a"])) -- [true false] + +;; nulls on both sides +(in (as 'SYM ["a" ""]) (as 'SYM ["" "z"])) -- [false true] + +;; null-free text: this is the shape that now reaches the kernel +(in (as 'SYM ["a" "b" "c"]) (as 'SYM ["b" "c"])) -- [false true true] +(in ["a" "b" "c"] ["b" "c"]) -- [false true true] + +;; empty needle set over a null-free symbol column +(in (as 'SYM ["a" "b"]) (as 'SYM [])) -- [false false] + +;; a single needle is the degenerate case the issue reported: same answer as +;; the equality it should cost the same as +(in (as 'SYM ["a" "b" "a"]) (as 'SYM ["a"])) -- [true false true] +(== (as 'SYM ["a" "b" "a"]) 'a) -- [true false true] + +;; duplicate needles must not double-count or change the verdict +(in (as 'SYM ["a" "b"]) (as 'SYM ["a" "a" "a"])) -- [true false]