diff --git a/RELEASE.md b/RELEASE.md index 76421ebe8..248133049 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -29,6 +29,26 @@ truth for the version** — no version literal is ever hand-edited in source. - packages `rayforce-X.Y.Z--.tar.gz` + a `.sha256` checksum, - publishes a GitHub Release with a feature-oriented changelog and the artifacts. +5. **Merge `master` back into `dev`** right after the release PR merges: + + ```sh + git fetch origin + git switch dev && git pull --ff-only + git merge --no-ff -s ours origin/master \ + -m "chore: merge master back into dev after the vX.Y.Z release (#N)" + git diff origin/dev --stat # must print nothing + git push origin dev + ``` + + Merging the release PR leaves a squash or merge commit on `master` that `dev` + doesn't contain. `master` requires branches to be up to date before merging, + so without this step the next release PR is blocked as "out of date with the + base". After a squash, it also shows conflicts that aren't real. Copying the + release commit onto `dev` doesn't help: only a merge makes `master`'s commit + an ancestor of `dev`. `-s ours` is correct because `dev` already contains + everything the release shipped, so the empty `git diff` proves the merge + changed no files. If `master` ever carries a hotfix that isn't on `dev`, + drop `-s ours` and do a normal merge instead. That's the whole ritual. **Never edit the version in source to make a release** — the tag is authoritative. diff --git a/docs/docs/guides/memory.md b/docs/docs/guides/memory.md index a0050195e..ba1780ea8 100644 --- a/docs/docs/guides/memory.md +++ b/docs/docs/guides/memory.md @@ -385,7 +385,7 @@ This tells you the join needed about 1 GB of temporary memory beyond what was al | Tool | What It Does | When to Use | |---|---|---| | `(.sys.mem 0)` | Returns heap allocation statistics | Monitor memory usage, detect leaks | -| `(.sys.gc 0)` | Flushes caches, releases pages | Between heavy queries, before benchmarks | +| `(.sys.gc)` | Flushes caches, releases pages | Between heavy queries, before benchmarks | | `(.sys.info 0)` | Shows system and runtime info | Check total RAM, CPU count, OS details | | `(timeit expr)` | Measures execution time of one expression | Benchmark a specific operation | | `:timeit` | Toggles profiling for all REPL expressions | Interactive performance exploration | diff --git a/src/ops/agg_engine.c b/src/ops/agg_engine.c index 9f19eb1ab..81ffe6651 100644 --- a/src/ops/agg_engine.c +++ b/src/ops/agg_engine.c @@ -4645,15 +4645,34 @@ static int64_t agg_index_winner(void* raw, const int64_t* rows, int64_t count) { #undef INDEX_FIRST_VALID } int64_t best = -1; + /* A FILE domain's entries are compared off the mapped vocabulary: no + * atom per row — the lazily built atoms of a wide vocabulary cost far + * more than the compare and stay for the domain's lifetime. Positions + * past the file prefix, and the runtime domain, go through the atoms. */ + struct ray_sym_domain_s* dom = ray_sym_vec_domain(c->src); + ray_sym_domain_raw_t vocab; + bool vocab_ok = ray_sym_domain_raw_pin(dom, &vocab); for (int64_t j = 0; j < count; j++) { if ((j & 65535) == 0 && ray_interrupted()) return -1; int64_t r = rows[c->kind == OP_LAST ? count - 1 - j : j]; if (ray_vec_is_null(c->src, r)) continue; if (best < 0) best = r; if (c->kind == OP_FIRST || c->kind == OP_LAST) break; - ray_t* x = ray_group_sym_read(&c->symbols, ray_sym_vec_domain(c->src), ray_read_sym(data, r, c->src->type, c->src->attrs)); - ray_t* y = ray_group_sym_read(&c->symbols, ray_sym_vec_domain(c->src), ray_read_sym(data, best, c->src->type, c->src->attrs)); - int cmp = ray_str_cmp(x, y); + int64_t ir = ray_read_sym(data, r, c->src->type, c->src->attrs); + int64_t ib = ray_read_sym(data, best, c->src->type, c->src->attrs); + int cmp; + if (vocab_ok && ir >= 0 && ib >= 0 && ir < vocab.count && ib < vocab.count) { + size_t lr, lb; + const char* pr = ray_sym_domain_raw_str(&vocab, ir, &lr); + const char* pb = ray_sym_domain_raw_str(&vocab, ib, &lb); + size_t m = lr < lb ? lr : lb; + cmp = m ? memcmp(pr, pb, m) : 0; + if (cmp == 0) cmp = (lr > lb) - (lr < lb); + } else { + ray_t* x = ray_group_sym_read(&c->symbols, dom, ir); + ray_t* y = ray_group_sym_read(&c->symbols, dom, ib); + cmp = ray_str_cmp(x, y); + } if (c->kind == OP_MIN ? cmp < 0 : cmp > 0) best = r; } return best; diff --git a/src/ops/exec.c b/src/ops/exec.c index de07dbbe4..fe5dd93b0 100644 --- a/src/ops/exec.c +++ b/src/ops/exec.c @@ -1839,9 +1839,117 @@ static ray_t* exec_elementwise_tree(ray_graph_t* g, ray_op_t* root) { return result; } +/* Nodes whose result may be shared between consumers: pure, vector-valued + * operators. Structural ops (scan, filter, group, sort, join …) either + * carry side state (g->selection) or return their input, and stay out. */ +static inline bool op_memoizable(uint16_t o) { + switch (o) { + case OP_IF: case OP_LIKE: case OP_ILIKE: case OP_UPPER: case OP_LOWER: + case OP_STRLEN: case OP_SUBSTR: case OP_REPLACE: case OP_TRIM: + case OP_CONCAT: case OP_STR_FIND: case OP_EXTRACT: case OP_DATE_TRUNC: + case OP_IN: case OP_NOT_IN: + return true; + default: + return op_is_elementwise(o); + } +} + +/* Count each node's consumers over the in_id edges (plus one for the + * root's return) and arm the memo when some memoizable node has more than + * one. The memo keeps its own ref on every stored value until + * exec_memo_end: a consumer that receives an input with rc == 1 may reuse + * the buffer in place, and a fused window or a sibling still holding a raw + * pointer into that buffer would then read the overwritten values — so no + * shared value is ever handed out as the sole reference. Shared + * intermediates therefore live to the end of the execution; before this a + * shared node was recomputed per consumer instead. Values belong to the + * table the memo was armed over (memo_table): while g->table is swapped + * for a sub-table the memo is inert. Returns whether it armed; not + * re-entrant on purpose — a nested execution of the same graph leaves the + * outer memo alone and must not tear it down. */ +static bool exec_memo_begin(ray_graph_t* g, ray_op_t* root) { + if (!g || g->memo_uses || g->node_count == 0) return false; + uint32_t nc = g->node_count; + ray_t* hdr = NULL; + char* mem = (char*)scratch_calloc(&hdr, (size_t)nc * (sizeof(ray_t*) + sizeof(uint32_t))); + if (!mem) return false; + ray_t** vals = (ray_t**)mem; + uint32_t* uses = (uint32_t*)(mem + (size_t)nc * sizeof(ray_t*)); + for (uint32_t i = 0; i < nc; i++) { + ray_op_t* n = &g->nodes[i]; + if (n->flags & OP_FLAG_DEAD) continue; + for (uint8_t k = 0; k < n->arity && k < 2; k++) + if (n->in_id[k] != RAY_OP_NONE && n->in_id[k] < nc) uses[n->in_id[k]]++; + /* Operands kept in the ext node: the third input of if / substr / + * replace, the trailing arguments of concat. */ + if (n->opcode == OP_IF || n->opcode == OP_SUBSTR || n->opcode == OP_REPLACE) { + ray_op_ext_t* e = find_ext(g, n->id); + if (e && e->third_in < nc) uses[e->third_in]++; + } else if (n->opcode == OP_CONCAT) { + ray_op_ext_t* e = find_ext(g, n->id); + if (e) { + int n_args = (int)e->sym; + const uint32_t* trail = (const uint32_t*)((const char*)(e + 1)); + for (int a = 2; a < n_args; a++) + if (trail[a - 2] < nc) uses[trail[a - 2]]++; + } + } + } + if (root && root->id < nc) uses[root->id]++; + bool any = false; + for (uint32_t i = 0; i < nc && !any; i++) + any = uses[i] > 1 && op_memoizable(g->nodes[i].opcode); + if (!any) { scratch_free(hdr); return false; } + g->memo_vals = vals; g->memo_uses = uses; g->memo_n = nc; g->memo_hdr = hdr; + g->memo_table = g->table; + return true; +} + +static void exec_memo_end(ray_graph_t* g) { + if (!g || !g->memo_uses) return; + for (uint32_t i = 0; i < g->memo_n; i++) + if (g->memo_vals[i]) ray_release(g->memo_vals[i]); + scratch_free(g->memo_hdr); + g->memo_vals = NULL; g->memo_uses = NULL; g->memo_n = 0; g->memo_hdr = NULL; + g->memo_table = NULL; +} + +/* A sub-evaluation over another table (an `if` branch over its compacted + * rows) gets a memo of its own: the outer memo is set aside — its values + * belong to the outer table — and a fresh one is armed over the current + * g->table with the sub-root's census. Pop tears the inner memo down and + * puts the outer one back. */ +void ray_exec_memo_push(ray_graph_t* g, ray_op_t* root, ray_exec_memo_save_t* save) { + save->vals = g->memo_vals; save->uses = g->memo_uses; save->n = g->memo_n; + save->hdr = g->memo_hdr; save->table = g->memo_table; + g->memo_vals = NULL; g->memo_uses = NULL; g->memo_n = 0; g->memo_hdr = NULL; + g->memo_table = NULL; + (void)exec_memo_begin(g, root); +} + +void ray_exec_memo_pop(ray_graph_t* g, const ray_exec_memo_save_t* save) { + exec_memo_end(g); + g->memo_vals = save->vals; g->memo_uses = save->uses; g->memo_n = save->n; + g->memo_hdr = save->hdr; g->memo_table = save->table; +} + ray_t* exec_node(ray_graph_t* g, ray_op_t* op) { if (!op) return ray_error("nyi", NULL); + /* Shared node already computed: hand out a ref (the memo's own ref goes + * at exec_memo_end). */ + bool memo_on = g->memo_uses && g->table == g->memo_table && + op->id < g->memo_n && op_memoizable(op->opcode); + if (memo_on && g->memo_vals[op->id]) { + ray_t* v = g->memo_vals[op->id]; + ray_retain(v); + /* The memo keeps its own ref until exec_memo_end: a consumer that + * reaches its input with rc == 1 may reuse the buffer in place, and + * another consumer may still hold a raw pointer into it. */ + return v; + } + bool memo_shared = memo_on && g->memo_uses[op->id] > 1; + /* Per-op cancellation checkpoint. Long fused pipelines iterate * exec_node many times; this catches Ctrl-C between operators * without adding cost to the per-row hot path. */ @@ -1879,6 +1987,15 @@ ray_t* exec_node(ray_graph_t* g, ray_op_t* op) { ray_t* _prof_result = exec_node_inner(g, op); tl_exec_depth--; + /* First consumer of a shared node: keep a ref for the others (a lazy + * value is not kept — materialising it is the consumer's business). */ + if (memo_shared && _prof_result && !RAY_IS_ERR(_prof_result) && + !ray_is_lazy(_prof_result) && g->memo_uses && g->table == g->memo_table && + !g->memo_vals[op->id]) { + ray_retain(_prof_result); + g->memo_vals[op->id] = _prof_result; + } + if (profiling) { ray_prof_span_t* ep = ray_profile_span_end(oname); if (ep) { @@ -3926,7 +4043,11 @@ static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root) { if (seg_count == 0 || !dag_can_stream(g, root)) { /* Non-parted table or DAG contains ops that need specialized merge: * use existing flat-materialization path. */ + /* Only the call that armed the memo tears it down: a nested + * execution of the same graph leaves the outer memo alone. */ + bool memo_armed = exec_memo_begin(g, root); ray_t* result = exec_node(g, root); + if (memo_armed) exec_memo_end(g); if (g->selection && result && !RAY_IS_ERR(result) && result->type == RAY_TABLE) { /* Projection-aware compaction: a select publishes the keys-only diff --git a/src/ops/fused_pred.c b/src/ops/fused_pred.c index 391d741a9..94d30219d 100644 --- a/src/ops/fused_pred.c +++ b/src/ops/fused_pred.c @@ -104,8 +104,8 @@ static int fp_atom_col_compatible(int8_t atom_type, int8_t col_type) { } /* Numeric, temporal, STR and GUID comparisons have an explicit typed leg - * with null-as-minimum ordering. SYM equality uses domain codes. LIKE/IN keep - * their stricter null-free admission because they use different evaluators. */ + * with null-as-minimum ordering. SYM equality uses domain codes. IN keeps + * its stricter null-free admission because it uses a different evaluator. */ static int fp_col_supported_op(const ray_t* col, int eq_or_ne) { if (!col) return 0; if (col->type >= RAY_BOOL && col->type <= RAY_TIMESTAMP) return 1; @@ -114,8 +114,8 @@ static int fp_col_supported_op(const ray_t* col, int eq_or_ne) { return !ray_vec_has_nulls(col); } -/* Strict form — no nullable column at all. Used by the shapes whose - * evaluator arm is not an equality compare (LIKE, IN). */ +/* Strict form — no nullable column at all. Used by the shape whose + * evaluator arm is not an equality compare (IN). */ static int fp_col_supported(const ray_t* col) { return col && !ray_vec_has_nulls(col); } @@ -208,7 +208,10 @@ static int fp_check_like(ray_t* expr, ray_t* tbl) { if (!fp_expr_const_str(elems[2])) return 0; if (tbl) { ray_t* col = ray_table_get_col(tbl, lhs->i64); - if (!col || !fp_col_supported(col)) return 0; + /* A null text cell is the empty string on every like path (the + * kernel and this evaluator both match the pattern against ""), + * so a nullable column is admitted. */ + if (!col) return 0; if (col->type != RAY_STR && col->type != RAY_SYM) return 0; } return 1; @@ -445,10 +448,13 @@ void fp_eval_cmp(const fp_cmp_t* p, int64_t start, int64_t end, for (int64_t r = 0; r < n; r++) { uint64_t sid = (uint64_t)read_by_esz(base, start + r, esz_l); if (sid >= lut_n || !lut) { - bits[r] = 0; + bits[r] = p->like_empty_match; continue; } - uint8_t state = lut[sid]; + /* The LUT is shared by the workers: relaxed atomics on its + * bytes (every writer stores the same answer for a cell, + * so a repeated resolve is the only cost of a race). */ + uint8_t state = __atomic_load_n(&lut[sid], __ATOMIC_RELAXED); if (!state) { const char* sp = NULL; size_t sl = 0; @@ -466,7 +472,7 @@ void fp_eval_cmp(const fp_cmp_t* p, int64_t start, int64_t end, : (uint8_t)ray_glob_match(sp, sl, p->pat_str, p->pat_len); } state = (uint8_t)(match ? 2 : 1); - lut[sid] = state; + __atomic_store_n(&lut[sid], state, __ATOMIC_RELAXED); } bits[r] = (uint8_t)(state == 2); } @@ -608,8 +614,8 @@ static inline uint8_t fp_eval_cmp_one(const fp_cmp_t* p, int64_t row) { if (p->col_type == RAY_SYM) { uint64_t sid = (uint64_t)read_by_esz(p->col_base, row, p->col_esz); if (sid >= p->like_lut_count || !p->like_lut) - return 0; - uint8_t state = p->like_lut[sid]; + return p->like_empty_match; + uint8_t state = __atomic_load_n(&p->like_lut[sid], __ATOMIC_RELAXED); if (!state) { /* NULL sym_strings ⇒ FILE-domain column (see fp_eval_cmp) */ const char* sp = NULL; @@ -629,7 +635,7 @@ static inline uint8_t fp_eval_cmp_one(const fp_cmp_t* p, int64_t row) { : (uint8_t)ray_glob_match(sp, sl, p->pat_str, p->pat_len); } state = (uint8_t)(match ? 2 : 1); - p->like_lut[sid] = state; + __atomic_store_n(&p->like_lut[sid], state, __ATOMIC_RELAXED); } return (uint8_t)(state == 2); } @@ -797,8 +803,10 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, return 0; } if (out->op == FP_LIKE) { + /* A nullable text column is admitted: a null cell is the empty + * string on every like path, matched against the pattern once + * here (like_empty_match). */ if (col->type != RAY_STR && col->type != RAY_SYM) return -1; - if (!fp_col_supported(col)) return -1; ray_t* cv_like = rext->literal; if (!cv_like || cv_like->type != -RAY_STR) return -1; out->col_type = col->type; @@ -810,6 +818,9 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, out->pat_str = ray_str_ptr(cv_like); out->pat_len = ray_str_len(cv_like); out->pat_compiled = ray_glob_compile(out->pat_str, out->pat_len); + out->like_empty_match = (out->pat_compiled.shape != RAY_GLOB_SHAPE_NONE) + ? (uint8_t)ray_glob_match_compiled(&out->pat_compiled, "", 0) + : (uint8_t)ray_glob_match("", 0, out->pat_str, out->pat_len); if (col->type == RAY_SYM) { /* Cell ids are positions in the COLUMN's domain. Runtime * domain: borrow the global string snapshot (lock-free per diff --git a/src/ops/fused_pred.h b/src/ops/fused_pred.h index d26ee6b24..be2fea7fc 100644 --- a/src/ops/fused_pred.h +++ b/src/ops/fused_pred.h @@ -82,6 +82,9 @@ typedef struct { * read straight from the mapping (see ray_sym_domain_raw_pin). */ ray_sym_domain_raw_t like_raw; uint8_t like_raw_ok; + /* pattern vs "": the answer for a null text cell and for a cell id the + * LUT does not cover (the same rule as the bare like kernel). */ + uint8_t like_empty_match; struct ray_sym_domain_s* like_dom; } fp_cmp_t; diff --git a/src/ops/fused_topk.c b/src/ops/fused_topk.c index ddf2ddfc3..6d44e49da 100644 --- a/src/ops/fused_topk.c +++ b/src/ops/fused_topk.c @@ -379,16 +379,20 @@ ray_t* ray_fused_topk_select(ray_t* tbl, ctx.k = k; ctx.tbl = tbl; - /* Compile the predicate via a temp graph just for the WHERE clause. */ + /* Compile the predicate via a temp graph just for the WHERE clause. No + * where: is a predicate with no children — every row passes — and the + * heap does the whole sort-and-take in one pass. */ ray_graph_t* g = ray_graph_new(tbl); if (!g) { fpk_unpin_keys(ctx.keys, n_sort_keys); return NULL; } - ray_op_t* pred_dag = compile_expr_dag(g, where_expr); - if (!pred_dag) { ray_graph_free(g); fpk_unpin_keys(ctx.keys, n_sort_keys); return NULL; } - if (fp_compile_pred(g, pred_dag, tbl, &ctx.pred) != 0) { - fp_pred_cleanup(&ctx.pred); - ray_graph_free(g); - fpk_unpin_keys(ctx.keys, n_sort_keys); - return NULL; + if (where_expr) { + ray_op_t* pred_dag = compile_expr_dag(g, where_expr); + if (!pred_dag) { ray_graph_free(g); fpk_unpin_keys(ctx.keys, n_sort_keys); return NULL; } + if (fp_compile_pred(g, pred_dag, tbl, &ctx.pred) != 0) { + fp_pred_cleanup(&ctx.pred); + ray_graph_free(g); + fpk_unpin_keys(ctx.keys, n_sort_keys); + return NULL; + } } if (sym_needed) { diff --git a/src/ops/group.c b/src/ops/group.c index 8ebc04187..0e5448e50 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -162,13 +162,24 @@ static void reduce_acc_init(reduce_acc_t* acc) { static inline bool sym_lex_lt(struct ray_sym_domain_s* dom, int64_t a, int64_t b) { if (a == b) return false; - ray_t* sa = ray_sym_domain_str(dom, a); - ray_t* sb = ray_sym_domain_str(dom, b); - if (!sa || !sb) return a < b; - const char* pa = ray_str_ptr(sa); - const char* pb = ray_str_ptr(sb); - size_t la = ray_str_len(sa); - size_t lb = ray_str_len(sb); + const char* pa; const char* pb; + size_t la, lb; + /* A FILE domain's entries are read off the mapped vocabulary: no atom + * is materialised per compare (the lazily built atoms cost more than + * the compare itself on a wide vocabulary). Positions past the file + * prefix, and the runtime domain, resolve through the atoms as before. */ + ray_sym_domain_raw_t raw; + if (ray_sym_domain_raw_pin(dom, &raw) && a >= 0 && b >= 0 && + a < raw.count && b < raw.count) { + pa = ray_sym_domain_raw_str(&raw, a, &la); + pb = ray_sym_domain_raw_str(&raw, b, &lb); + } else { + ray_t* sa = ray_sym_domain_str(dom, a); + ray_t* sb = ray_sym_domain_str(dom, b); + if (!sa || !sb) return a < b; + pa = ray_str_ptr(sa); pb = ray_str_ptr(sb); + la = ray_str_len(sa); lb = ray_str_len(sb); + } size_t m = la < lb ? la : lb; int c = memcmp(pa, pb, m); if (c != 0) return c < 0; @@ -7848,6 +7859,7 @@ typedef struct { ray_t* rowsel; ray_t** sym_strings; /* borrowed sym snapshot for strlen-on-SYM aggs */ uint32_t sym_count; + int64_t da_n_scan; /* rows to scan (ranged tasks split it) */ } da_ctx_t; typedef struct { @@ -8890,6 +8902,18 @@ static void da_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t en #undef DA_PF_DIST } +/* One task per accumulator (ray_pool_dispatch_n): task i scans the i-th + * of n_accums equal row ranges into accums[i], whichever worker runs it. */ +static void da_accum_task_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + (void)worker_id; (void)end; + da_ctx_t* c = (da_ctx_t*)ctx; + int64_t k = c->n_accums, n = c->da_n_scan; + int64_t base = n / k, rem = n % k; + int64_t lo = start * base + (start < rem ? start : rem); + int64_t hi = lo + base + (start < rem ? 1 : 0); + da_accum_fn(ctx, (uint32_t)start, lo, hi); +} + /* Parallel DA merge: merge per-worker accumulators into accums[0] by * dispatching disjoint slot ranges across pool workers. */ typedef struct { @@ -12641,8 +12665,15 @@ da_path:; uint64_t max_workers = cells_per_worker ? (uint64_t)n_scan / cells_per_worker : 1; if (max_workers < 1) max_workers = 1; - if ((uint64_t)da_n_workers > max_workers) - da_n_workers = 1; + /* More workers than the budget allows: keep the budget's worth + * of accumulators and give each one a contiguous row range (one + * task per accumulator, whichever worker runs it) instead of + * collapsing to a serial scan of every row. */ + bool da_ranged = false; + if ((uint64_t)da_n_workers > max_workers) { + da_n_workers = (uint32_t)max_workers; + da_ranged = da_n_workers > 1; + } ray_t* accums_hdr; da_accum_t* accums = (da_accum_t*)scratch_calloc(&accums_hdr, @@ -12768,9 +12799,12 @@ da_path:; .n_slots = n_slots, .match_idx = match_idx, .rowsel = rowsel, + .da_n_scan = n_scan, }; - if (da_n_workers > 1) + if (da_ranged) + ray_pool_dispatch_n(da_pool, da_accum_task_fn, &da_ctx, da_n_workers); + else if (da_n_workers > 1) ray_pool_dispatch(da_pool, da_accum_fn, &da_ctx, n_scan); else da_accum_fn(&da_ctx, 0, 0, n_scan); diff --git a/src/ops/internal.h b/src/ops/internal.h index a1e1eeba8..63d19d339 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -1603,6 +1603,19 @@ ray_t* exec_k_shortest(ray_graph_t* g, ray_op_t* op, /* ── pivot_exec.c ── */ ray_t* exec_if(ray_graph_t* g, ray_op_t* op); + +/* Shared-node memo around a sub-evaluation over a swapped g->table + * (exec.c): push sets the outer memo aside and arms one for the current + * table and sub-root; pop tears it down and restores the outer one. */ +typedef struct { + ray_t** vals; + uint32_t* uses; + uint32_t n; + ray_t* hdr; + ray_t* table; +} ray_exec_memo_save_t; +void ray_exec_memo_push(ray_graph_t* g, ray_op_t* root, ray_exec_memo_save_t* save); +void ray_exec_memo_pop(ray_graph_t* g, const ray_exec_memo_save_t* save); ray_t* exec_pivot(ray_graph_t* g, ray_op_t* op, ray_t* tbl); /* ── embedding_exec.c ── */ diff --git a/src/ops/ops.h b/src/ops/ops.h index 656b4fd57..d24ce6ae5 100644 --- a/src/ops/ops.h +++ b/src/ops/ops.h @@ -572,6 +572,23 @@ typedef struct ray_graph { * 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; + + /* Result memo for shared nodes (exec.c, exec_node): a node with more + * than one consumer in the graph is executed once and its result is + * handed to every consumer as a retained ref; the memo's own ref is + * released at exec_memo_end. Set up around the flat exec_node(root) call in + * ray_execute_inner, NULL otherwise. Without it a `let`-bound string + * expression used three times ran three times. */ + ray_t** memo_vals; + uint32_t* memo_uses; + uint32_t memo_n; + ray_t* memo_hdr; + /* The table the memo was armed over. A node evaluated while g->table + * is swapped for another (an `if` branch over its compacted rows, a + * filter's right-hand side over a sub-table, a window partition) has a + * value of that table's length, so the memo neither serves nor stores + * while g->table differs. */ + ray_t* memo_table; } ray_graph_t; /* ===== Morsel Iterator ===== */ diff --git a/src/ops/pivot.c b/src/ops/pivot.c index 0be4a5579..e43b1f6e2 100644 --- a/src/ops/pivot.c +++ b/src/ops/pivot.c @@ -252,7 +252,12 @@ static ray_t* if_eval_branch(ray_graph_t* g, ray_op_t* branch, g->table = sub; g->selection = NULL; + /* The branch's shared nodes get a memo over the branch's rows; the + * outer memo (values of the full table) is set aside meanwhile. */ + ray_exec_memo_save_t memo_save; + ray_exec_memo_push(g, branch, &memo_save); ray_t* value = exec_node(g, branch); + ray_exec_memo_pop(g, &memo_save); if (g->selection) { ray_release(g->selection); g->selection = NULL; @@ -501,6 +506,144 @@ static ray_t* if_scatter_str(ray_t* result, ray_t* value, int64_t* ids, return result; } +/* Descriptor scatter for the STR arm of the selected path. A side is a + * STR vector with one row per id (or as many rows as the table, indexed by + * the id), or a broadcast scalar. The result takes the side's 16-byte + * descriptor at ids[j] instead of appending its bytes row by row: pooled + * strings keep pointing into their pool, two different pools are laid end + * to end (the second side's offsets shift), a pooled scalar's bytes go in + * once. Rows not in either id list stay the null descriptor the caller + * zeroed. Returns NULL, the result untouched, for a side this cannot take + * (a SYM branch, a length that is neither) — the caller then falls back to + * the per-row scatter, which also reports the length error. */ +typedef struct { + ray_t* v; + int64_t* ids; + int64_t n; + bool scalar; + bool full; /* vector of nrows: row ids[j] */ + const ray_str_t* desc; + ray_t* pool; + const char* sp; /* scalar bytes */ + size_t sl; +} if_str_side_t; + +static bool if_str_side_init(ray_t* v, int64_t* ids, int64_t n, int64_t nrows, + if_str_side_t* s) { + memset(s, 0, sizeof(*s)); + s->ids = ids; s->n = n; + if (!v || n <= 0) return true; + s->v = v; + if (v->type == -RAY_STR) { + s->scalar = true; s->sp = ray_str_ptr(v); s->sl = ray_str_len(v); + return true; + } + if (v->type != RAY_STR) return false; + if (v->len == 1) { + s->scalar = true; + s->sp = ray_str_vec_get(v, 0, &s->sl); + if (!s->sp) { s->sp = ""; s->sl = 0; } + return true; + } + if (v->len == n) s->full = false; + else if (v->len == nrows) s->full = true; + else return false; + const char* bytes = NULL; + str_resolve(v, &s->desc, &bytes); + s->pool = str_vec_pool_obj(v); + if (s->pool && RAY_IS_ERR(s->pool)) return false; + return true; +} + +typedef struct { + const int64_t* ids; + const ray_str_t* src; + bool scalar; + bool full; + ray_str_t sd; /* the scalar's descriptor */ + uint32_t shift; + ray_str_t* dst; +} if_str_scatter_ctx_t; + +static void if_str_scatter_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + const if_str_scatter_ctx_t* c = (const if_str_scatter_ctx_t*)vctx; + if (c->scalar) { + for (int64_t j = start; j < end; j++) c->dst[c->ids[j]] = c->sd; + return; + } + for (int64_t j = start; j < end; j++) { + ray_str_t d = c->full ? c->src[c->ids[j]] : c->src[j]; + if (c->shift && !ray_str_is_inline(&d)) d.pool_off += c->shift; + c->dst[c->ids[j]] = d; + } +} + +static void if_str_scatter_side(const if_str_side_t* s, uint32_t shift, uint32_t scalar_off, + ray_str_t* dst) { + if (!s->v) return; + if_str_scatter_ctx_t c = { + .ids = s->ids, .src = s->desc, .scalar = s->scalar, .full = s->full, + .shift = shift, .dst = dst, + }; + if (s->scalar) { + memset(&c.sd, 0, sizeof(c.sd)); + c.sd.len = (uint32_t)s->sl; + if (s->sl <= RAY_STR_INLINE_MAX) { + if (s->sl) memcpy(c.sd.data, s->sp, s->sl); + } else { + memcpy(c.sd.prefix, s->sp, 4); + c.sd.pool_off = scalar_off; + } + } + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, s->n, RAY_PARALLEL_THRESHOLD)) + ray_pool_dispatch(pool, if_str_scatter_fn, &c, s->n); + else + if_str_scatter_fn(&c, 0, 0, s->n); +} + +static ray_t* if_scatter_str_desc(ray_t* result, + ray_t* then_v, int64_t* t_ids, int64_t t_n, + ray_t* else_v, int64_t* e_ids, int64_t e_n, + int64_t nrows) { + if_str_side_t t, e; + if (!if_str_side_init(then_v, t_ids, t_n, nrows, &t)) return NULL; + if (!if_str_side_init(else_v, e_ids, e_n, nrows, &e)) return NULL; + + ray_t* pt = (t.v && !t.scalar) ? t.pool : NULL; + ray_t* pe = (e.v && !e.scalar) ? e.pool : NULL; + bool t_big = t.v && t.scalar && t.sl > RAY_STR_INLINE_MAX; + bool e_big = e.v && e.scalar && e.sl > RAY_STR_INLINE_MAX; + uint32_t e_shift = 0, ts_off = 0, es_off = 0; + if (!t_big && !e_big && (pt == pe || !pt || !pe)) { + ray_t* shared = pt ? pt : pe; + if (shared) { ray_retain(shared); result->str_pool = shared; } + } else { + int64_t tl = pt ? pt->len : 0; + int64_t el = (pe && pe != pt) ? pe->len : 0; + if (tl < 0 || el < 0) return NULL; + uint64_t total = (uint64_t)tl + (uint64_t)el + + (t_big ? (uint64_t)t.sl : 0) + (e_big ? (uint64_t)e.sl : 0); + if (total > UINT32_MAX) return NULL; + ray_t* np = ray_alloc(total > 0 ? (size_t)total : 1); + if (!np || RAY_IS_ERR(np)) return NULL; + np->type = RAY_U8; + np->len = (int64_t)total; + char* dst = (char*)ray_data(np); + uint32_t off = 0; + if (tl) { memcpy(dst, ray_data(pt), (size_t)tl); off += (uint32_t)tl; } + if (pe && pe != pt && el) { memcpy(dst + off, ray_data(pe), (size_t)el); e_shift = off; off += (uint32_t)el; } + if (t_big) { memcpy(dst + off, t.sp, t.sl); ts_off = off; off += (uint32_t)t.sl; } + if (e_big) { memcpy(dst + off, e.sp, e.sl); es_off = off; off += (uint32_t)e.sl; } + result->str_pool = np; + } + ray_str_t* dst = (ray_str_t*)ray_data(result); + if_str_scatter_side(&t, 0, ts_off, dst); + if_str_scatter_side(&e, e_shift, es_off, dst); + return result; +} + /* Runtime-id translation for one SYM branch of an `if`. * * A branch that scans a FILE-domain column used to go through the @@ -772,9 +915,15 @@ static ray_t* exec_if_selected(ray_graph_t* g, ray_op_t* op, ray_t* cond_v) { bool ok = true; if (out_type == RAY_STR) { - result = if_scatter_str(result, then_v, true_ids, true_count, nrows); - if (result && !RAY_IS_ERR(result)) - result = if_scatter_str(result, else_v, false_ids, false_count, nrows); + ray_t* fast = if_scatter_str_desc(result, then_v, true_ids, true_count, + else_v, false_ids, false_count, nrows); + if (fast) { + result = fast; + } else { + result = if_scatter_str(result, then_v, true_ids, true_count, nrows); + if (result && !RAY_IS_ERR(result)) + result = if_scatter_str(result, else_v, false_ids, false_count, nrows); + } } else if (out_type == RAY_SYM) { ok = if_scatter_sym(result, then_v, true_ids, true_count, nrows) && if_scatter_sym(result, else_v, false_ids, false_count, nrows); @@ -893,6 +1042,32 @@ static void if_fill_par_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) if_fill_range((const if_fill_ctx_t*)ctx, start, end); } +/* Descriptor fill for the STR arm of exec_if_eager: dst[r] is the chosen + * side's descriptor; a pooled else-descriptor moves by e_shift when the two + * pools were laid end to end. Rows are independent; workers write disjoint + * ranges. */ +typedef struct { + const uint8_t* cond; + const ray_str_t* t; + const ray_str_t* e; + ray_str_t* dst; + uint32_t e_shift; +} if_str_desc_ctx_t; + +static void if_str_desc_fn(void* vctx, uint32_t worker_id, int64_t start, int64_t end) { + (void)worker_id; + const if_str_desc_ctx_t* c = (const if_str_desc_ctx_t*)vctx; + for (int64_t r = start; r < end; r++) { + if (c->cond[r]) { + c->dst[r] = c->t[r]; + } else { + ray_str_t d = c->e[r]; + if (c->e_shift && !ray_str_is_inline(&d)) d.pool_off += c->e_shift; + c->dst[r] = d; + } + } +} + static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op) { /* cond = inputs[0], then = inputs[1], else_id stored in ext->third_in */ ray_t* cond_v = exec_node(g, op_child(g, op, 0)); @@ -959,27 +1134,64 @@ static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op) { uint8_t* cond_p = (uint8_t*)ray_data(cond_v); if (out_type == RAY_STR) { + /* Two STR vectors: the result is descriptors only. Each row takes + * its side's 16-byte descriptor; pooled strings keep pointing into + * their pool. One shared pool (or one side inline-only) is reused + * as is; two different pools are laid end to end in a new pool and + * the else side's offsets shift by the then pool's length. Nulls + * are empty descriptors and travel unchanged. No per-row append, + * no rehash; the fill runs on the worker pool. */ if (!then_scalar && !else_scalar && then_v->type == RAY_STR && else_v->type == RAY_STR && - len <= then_v->len && len <= else_v->len && - !ray_vec_may_have_nulls(then_v) && - !ray_vec_may_have_nulls(else_v)) { + len <= then_v->len && len <= else_v->len) { ray_t* then_pool = str_vec_pool_obj(then_v); ray_t* else_pool = str_vec_pool_obj(else_v); + const ray_str_t* t_desc = NULL; + const ray_str_t* e_desc = NULL; + const char* t_bytes = NULL; + const char* e_bytes = NULL; + str_resolve(then_v, &t_desc, &t_bytes); + str_resolve(else_v, &e_desc, &e_bytes); + bool ok = true; + uint32_t e_shift = 0; if (then_pool == else_pool || !then_pool || !else_pool) { ray_t* out_pool = then_pool ? then_pool : else_pool; if (out_pool && !RAY_IS_ERR(out_pool)) { ray_retain(out_pool); result->str_pool = out_pool; } - const ray_str_t* t_desc = NULL; - const ray_str_t* e_desc = NULL; - const char* unused_pool = NULL; - str_resolve(then_v, &t_desc, &unused_pool); - str_resolve(else_v, &e_desc, &unused_pool); - ray_str_t* dst = (ray_str_t*)ray_data(result); - for (int64_t i = 0; i < len; i++) - dst[i] = cond_p[i] ? t_desc[i] : e_desc[i]; + } else if (RAY_IS_ERR(then_pool) || RAY_IS_ERR(else_pool)) { + ok = false; + } else { + int64_t tl = then_pool->len, el = else_pool->len; + if (tl < 0 || el < 0 || (uint64_t)tl + (uint64_t)el > UINT32_MAX) { + ok = false; + } else { + ray_t* np = ray_alloc((size_t)(tl + el) > 0 ? (size_t)(tl + el) : 1); + if (!np || RAY_IS_ERR(np)) { + ok = false; + } else { + np->type = RAY_U8; + np->len = tl + el; + if (tl) memcpy(ray_data(np), t_bytes, (size_t)tl); + if (el) memcpy((char*)ray_data(np) + tl, e_bytes, (size_t)el); + result->str_pool = np; + e_shift = (uint32_t)tl; + } + } + } + if (ok) { + if_str_desc_ctx_t dctx = { + .cond = cond_p, .t = t_desc, .e = e_desc, + .dst = (ray_str_t*)ray_data(result), .e_shift = e_shift, + }; + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, len, RAY_PARALLEL_THRESHOLD)) + ray_pool_dispatch(pool, if_str_desc_fn, &dctx, len); + else + if_str_desc_fn(&dctx, 0, 0, len); + if (ray_vec_may_have_nulls(then_v) || ray_vec_may_have_nulls(else_v)) + result->attrs |= RAY_ATTR_HAS_NULLS; ray_release(cond_v); ray_release(then_v); ray_release(else_v); return result; } diff --git a/src/ops/query.c b/src/ops/query.c index f5bc3071e..a17e15810 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -3069,6 +3069,225 @@ static int64_t derived_key_chunk_rows(void) { #endif return DERIVED_KEY_CHUNK; } + +/* ---- chunk STR build: the entries at positions dv[lo, lo+n) as one STR + * vector over one pool. Lengths and byte pointers are read on the workers + * (the raw snapshot needs no lock); a position past the file prefix — a + * runtime-appended entry — is resolved through the domain on the calling + * thread. A serial prefix sum places the pooled rows, then the workers + * write the descriptors and copy the pooled bytes into disjoint ranges. */ +typedef struct { + const void* dv; + uint8_t dattrs; + int64_t lo; + const ray_sym_domain_raw_t* raw; + const char** ptr; + uint32_t* len; + uint32_t* off; + ray_str_t* dst; + char* pool; + atomic_int late; +} dk_chunk_ctx_t; + +static void dk_chunk_scan_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + dk_chunk_ctx_t* c = (dk_chunk_ctx_t*)vctx; + int late = 0; + for (int64_t i = start; i < end; i++) { + int64_t pos = ray_read_sym(c->dv, c->lo + i, RAY_SYM, c->dattrs); + if (pos >= 0 && pos < c->raw->count) { + size_t sl = 0; + c->ptr[i] = ray_sym_domain_raw_str(c->raw, pos, &sl); + c->len[i] = (uint32_t)sl; + } else { + c->ptr[i] = NULL; + c->len[i] = UINT32_MAX; + late++; + } + } + if (late) atomic_fetch_add_explicit(&c->late, late, memory_order_relaxed); +} + +static void dk_chunk_fill_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + const dk_chunk_ctx_t* c = (const dk_chunk_ctx_t*)vctx; + for (int64_t i = start; i < end; i++) { + ray_str_t* d = &c->dst[i]; + uint32_t l = c->len[i]; + memset(d, 0, sizeof(*d)); + d->len = l; + if (l == 0) continue; + if (l <= RAY_STR_INLINE_MAX) { + memcpy(d->data, c->ptr[i], l); + } else { + memcpy(c->pool + c->off[i], c->ptr[i], l); + memcpy(d->prefix, c->ptr[i], 4); + d->pool_off = c->off[i]; + } + } +} + +static ray_t* derived_key_chunk_strs(const void* dv, uint8_t dattrs, int64_t lo, int64_t n, + const ray_sym_domain_raw_t* raw, + struct ray_sym_domain_s* dom) { + ray_t* aux_hdr = NULL; + size_t ptr_sz = (size_t)n * sizeof(const char*); + size_t u32_sz = (size_t)n * sizeof(uint32_t); + char* mem = (char*)scratch_alloc(&aux_hdr, ptr_sz + 2 * u32_sz); + if (!mem) return NULL; + dk_chunk_ctx_t c; + memset(&c, 0, sizeof(c)); + c.dv = dv; c.dattrs = dattrs; c.lo = lo; c.raw = raw; + c.ptr = (const char**)mem; + c.len = (uint32_t*)(mem + ptr_sz); + c.off = (uint32_t*)(mem + ptr_sz + u32_sz); + atomic_store_explicit(&c.late, 0, memory_order_relaxed); + + ray_pool_t* pool = ray_pool_get(); + bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); + if (par) ray_pool_dispatch(pool, dk_chunk_scan_fn, &c, n); + else dk_chunk_scan_fn(&c, 0, 0, n); + if (atomic_load_explicit(&c.late, memory_order_relaxed)) { + for (int64_t i = 0; i < n; i++) { + if (c.len[i] != UINT32_MAX) continue; + int64_t pos = ray_read_sym(dv, lo + i, RAY_SYM, dattrs); + ray_t* a = ray_sym_domain_str(dom, pos); + size_t sl = a ? ray_str_len(a) : 0; + if (sl > UINT32_MAX) { scratch_free(aux_hdr); return NULL; } + c.ptr[i] = a ? ray_str_ptr(a) : ""; + c.len[i] = (uint32_t)sl; + } + } + uint64_t total = 0; + for (int64_t i = 0; i < n; i++) { + if (c.len[i] <= RAY_STR_INLINE_MAX) continue; + c.off[i] = (uint32_t)total; + total += c.len[i]; + if (total > UINT32_MAX) { scratch_free(aux_hdr); return NULL; } + } + ray_t* sv = ray_vec_new(RAY_STR, n); + if (!sv || RAY_IS_ERR(sv)) { if (sv) ray_error_free(sv); scratch_free(aux_hdr); return NULL; } + sv->len = n; + if (total > 0) { + ray_t* sp = ray_alloc((size_t)total); + if (!sp || RAY_IS_ERR(sp)) { ray_release(sv); scratch_free(aux_hdr); return NULL; } + sp->type = RAY_U8; + sp->len = (int64_t)total; + sv->str_pool = sp; + c.pool = (char*)ray_data(sp); + } + c.dst = (ray_str_t*)ray_data(sv); + if (par) ray_pool_dispatch(pool, dk_chunk_fill_fn, &c, n); + else dk_chunk_fill_fn(&c, 0, 0, n); + scratch_free(aux_hdr); + return sv; +} + +/* ---- chunk result interning: each distinct string of the chunk's key + * vector is interned once, all of them under one lock, and its id spread + * over the rows that hold it. The hashes are the intern table's own + * (ray_hash_bytes), computed on the workers; the dedupe is an + * open-addressing table over the distinct ordinals, on scratch. */ +typedef struct { + const ray_str_t* desc; + const char* pool; + uint32_t* hash; +} dk_hash_ctx_t; + +static void dk_hash_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + const dk_hash_ctx_t* c = (const dk_hash_ctx_t*)vctx; + for (int64_t i = start; i < end; i++) { + const ray_str_t* d = &c->desc[i]; + c->hash[i] = (uint32_t)ray_hash_bytes(ray_str_t_ptr(d, c->pool), d->len); + } +} + +static bool derived_key_intern_chunk(ray_t* kc, int64_t n, int64_t* out) { + const ray_str_t* desc = NULL; + const char* pool = NULL; + str_resolve(kc, &desc, &pool); + int64_t slots = 1024; + while (slots < 2 * n) slots <<= 1; + ray_t* hdr = NULL; + size_t hash_sz = (size_t)n * sizeof(uint32_t); + size_t rep_sz = (size_t)n * sizeof(int32_t); + size_t tab_sz = (size_t)slots * sizeof(int32_t); + size_t dstr_sz = (size_t)n * sizeof(const char*); + size_t dlen_sz = (size_t)n * sizeof(size_t); + size_t dhsh_sz = (size_t)n * sizeof(uint32_t); + size_t did_sz = (size_t)n * sizeof(int64_t); + /* One carve; the 8-byte arrays go first so every field stays aligned. */ + char* mem = (char*)scratch_alloc(&hdr, hash_sz + rep_sz + tab_sz + dstr_sz + dlen_sz + dhsh_sz + did_sz); + if (!mem) return false; + const char** dstr = (const char**)mem; mem += dstr_sz; + size_t* dlen = (size_t*)mem; mem += dlen_sz; + int64_t* did = (int64_t*)mem; mem += did_sz; + uint32_t* hash = (uint32_t*)mem; mem += hash_sz; + int32_t* rep = (int32_t*)mem; mem += rep_sz; + int32_t* tab = (int32_t*)mem; mem += tab_sz; + uint32_t* dhsh = (uint32_t*)mem; + memset(tab, 0xff, tab_sz); + + dk_hash_ctx_t hc = { .desc = desc, .pool = pool, .hash = hash }; + ray_pool_t* rp = ray_pool_get(); + if (ray_pool_par_dispatch_ok(rp, n, RAY_PARALLEL_THRESHOLD)) + ray_pool_dispatch(rp, dk_hash_fn, &hc, n); + else + dk_hash_fn(&hc, 0, 0, n); + + uint64_t mask = (uint64_t)slots - 1; + int64_t nd = 0; + for (int64_t i = 0; i < n; i++) { + uint32_t h = hash[i]; + const ray_str_t* d = &desc[i]; + const char* sp = ray_str_t_ptr(d, pool); + uint64_t s = ((uint64_t)h * 0x9E3779B97F4A7C15ull >> 32) & mask; + for (;;) { + int32_t r = tab[s]; + if (r < 0) { + tab[s] = (int32_t)nd; + rep[i] = (int32_t)nd; + dstr[nd] = sp; dlen[nd] = d->len; dhsh[nd] = h; + nd++; + break; + } + if (dhsh[r] == h && dlen[r] == d->len && + (d->len == 0 || memcmp(dstr[r], sp, d->len) == 0)) { + rep[i] = r; + break; + } + s = (s + 1) & mask; + } + } + if (ray_sym_intern_batch(dhsh, dstr, dlen, nd, did) < 0) { scratch_free(hdr); return false; } + for (int64_t i = 0; i < n; i++) out[i] = did[rep[i]]; + scratch_free(hdr); + return true; +} + +/* ---- the spread pass of derived_key_over_sym_domain: each row takes the + * key of its symbol's slot (workers, disjoint ranges). */ +typedef struct { + const void* cd; + uint8_t attrs; + int64_t dn; + const int32_t* pos; + const int64_t* key; /* spread: key per slot; NULL = write the slot */ + int64_t* out; +} dk_rows_ctx_t; + +static void dk_spread_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + const dk_rows_ctx_t* c = (const dk_rows_ctx_t*)vctx; + if (c->key) { + for (int64_t r = start; r < end; r++) + c->out[r] = c->key[c->pos[ray_read_sym(c->cd, r, RAY_SYM, c->attrs)]]; + } else { + for (int64_t r = start; r < end; r++) + c->out[r] = c->pos[ray_read_sym(c->cd, r, RAY_SYM, c->attrs)]; + } +} static ray_t* derived_key_str_chunks(ray_t* by_expr, int64_t col_sym, ray_t* dom_vec, struct ray_sym_domain_s* dom, int64_t du) { if (!dom || dom == ray_sym_runtime_domain() || du <= 0) return NULL; @@ -3102,21 +3321,8 @@ static ray_t* derived_key_str_chunks(ray_t* by_expr, int64_t col_sym, ray_t* dom const int64_t chunk = derived_key_chunk_rows(); for (int64_t lo = 0; lo < du; lo += chunk) { int64_t n = du - lo < chunk ? du - lo : chunk; - ray_t* sv = ray_vec_new(RAY_STR, n); - if (!sv || RAY_IS_ERR(sv)) { if (sv) ray_error_free(sv); goto fail; } - for (int64_t i = 0; i < n; i++) { - int64_t pos = ray_read_sym(dv, lo + i, dom_vec->type, dom_vec->attrs); - const char* sp = NULL; - size_t sl = 0; - if (pos >= 0 && pos < raw.count) { - sp = ray_sym_domain_raw_str(&raw, pos, &sl); - } else { - ray_t* a = ray_sym_domain_str(dom, pos); - if (a) { sp = ray_str_ptr(a); sl = ray_str_len(a); } - } - sv = ray_str_vec_append(sv, sp ? sp : "", sp ? sl : 0); - if (!sv || RAY_IS_ERR(sv)) { if (sv) ray_error_free(sv); goto fail; } - } + ray_t* sv = derived_key_chunk_strs(dv, dom_vec->attrs, lo, n, &raw, dom); + if (!sv) goto fail; ray_t* mini = ray_table_new(0); if (mini && !RAY_IS_ERR(mini)) mini = ray_table_add_col(mini, col_sym, sv); ray_release(sv); @@ -3134,13 +3340,7 @@ static ray_t* derived_key_str_chunks(ray_t* by_expr, int64_t col_sym, ray_t* dom if (!kc || RAY_IS_ERR(kc)) { if (kc) ray_error_free(kc); goto fail; } if (!ray_is_vec(kc) || kc->len != n) { ray_release(kc); goto fail; } if (kc->type == RAY_STR) { - for (int64_t i = 0; i < n; i++) { - size_t sl = 0; - const char* sp = ray_str_vec_get(kc, i, &sl); - int64_t id = ray_sym_intern(sp ? sp : "", sp ? sl : 0); - if (id < 0) { ray_release(kc); goto fail; } - kd[lo + i] = id; - } + if (!derived_key_intern_chunk(kc, n, kd + lo)) { ray_release(kc); goto fail; } } else if (RAY_IS_SYM(kc->type)) { /* The STR evaluation still produced symbols (e.g. a literal * symbol branch): take them cell by cell as runtime ids. */ @@ -3215,6 +3415,9 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl) { ray_sym_vec_adopt_domain(dom_vec, C); int64_t du = 0, du_max = nrows / 2; if (du_max > INT32_MAX) du_max = INT32_MAX; /* slots are int32 */ + /* Slots in first-seen row order: the interned key ids follow the slot + * order, and with them the order the groups come out in — the same + * order the row-wise evaluation gives. */ bool ok = true; for (int64_t r = 0; r < nrows; r++) { int64_t id = ray_read_sym(cd, r, C->type, C->attrs); @@ -3228,6 +3431,11 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl) { } if (!ok || du == 0) { ray_release(dom_vec); scratch_free(pos_hdr); return NULL; } dom_vec->len = du; + dk_rows_ctx_t rc; + memset(&rc, 0, sizeof(rc)); + rc.cd = cd; rc.attrs = C->attrs; rc.dn = dn; + ray_pool_t* rpool = ray_pool_get(); + bool rows_par = ray_pool_par_dispatch_ok(rpool, nrows, RAY_PARALLEL_THRESHOLD); /* Evaluate the expression over the du distinct symbols through the * same DAG compiler the row-wise key would take, against a one-column @@ -3254,20 +3462,37 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl) { if (!ray_is_vec(key_dom) || key_dom->len != du) { ray_release(key_dom); scratch_free(pos_hdr); return NULL; } } - /* Pass 2: spread by slot. */ - ray_t* ids = ray_vec_new(RAY_I64, nrows); - if (!ids || RAY_IS_ERR(ids)) { if (ids) ray_error_free(ids); ray_release(key_dom); scratch_free(pos_hdr); return NULL; } - ids->len = nrows; - int64_t* idp = (int64_t*)ray_data(ids); - for (int64_t r = 0; r < nrows; r++) - idp[r] = pos[ray_read_sym(cd, r, C->type, C->attrs)]; - scratch_free(pos_hdr); - ray_t* spread = ray_at_fn(key_dom, ids); - ray_release(ids); - ray_release(key_dom); - if (spread && !RAY_IS_ERR(spread) && ray_is_lazy(spread)) spread = ray_lazy_materialize(spread); - if (!spread || RAY_IS_ERR(spread)) { if (spread) ray_error_free(spread); return NULL; } - if (!ray_is_vec(spread) || spread->len != nrows) { ray_release(spread); return NULL; } + /* Pass 2: spread by slot — each row takes the key of its symbol's slot, + * written straight into the result (no index vector, no gather). */ + if (!ray_is_vec(key_dom) || key_dom->len != du) { ray_release(key_dom); scratch_free(pos_hdr); return NULL; } + ray_t* spread = NULL; + if (key_dom->type == RAY_SYM && (key_dom->attrs & RAY_SYM_W_MASK) == RAY_SYM_W64) { + spread = ray_sym_vec_new(RAY_SYM_W64, nrows); + if (!spread || RAY_IS_ERR(spread)) { if (spread) ray_error_free(spread); ray_release(key_dom); scratch_free(pos_hdr); return NULL; } + spread->len = nrows; + ray_sym_vec_adopt_domain(spread, key_dom); + rc.pos = pos; rc.key = (const int64_t*)ray_data(key_dom); rc.out = (int64_t*)ray_data(spread); + if (rows_par) ray_pool_dispatch(rpool, dk_spread_fn, &rc, nrows); + else dk_spread_fn(&rc, 0, 0, nrows); + scratch_free(pos_hdr); + ray_release(key_dom); + } else { + /* Any other key vector (the one-shot SYM evaluation's width, or a + * non-SYM result): index by slot and gather. */ + ray_t* ids = ray_vec_new(RAY_I64, nrows); + if (!ids || RAY_IS_ERR(ids)) { if (ids) ray_error_free(ids); ray_release(key_dom); scratch_free(pos_hdr); return NULL; } + ids->len = nrows; + rc.pos = pos; rc.key = NULL; rc.out = (int64_t*)ray_data(ids); + if (rows_par) ray_pool_dispatch(rpool, dk_spread_fn, &rc, nrows); + else dk_spread_fn(&rc, 0, 0, nrows); + scratch_free(pos_hdr); + spread = ray_at_fn(key_dom, ids); + ray_release(ids); + ray_release(key_dom); + if (spread && !RAY_IS_ERR(spread) && ray_is_lazy(spread)) spread = ray_lazy_materialize(spread); + if (!spread || RAY_IS_ERR(spread)) { if (spread) ray_error_free(spread); return NULL; } + if (!ray_is_vec(spread) || spread->len != nrows) { ray_release(spread); return NULL; } + } agg_route_note_key_domain(); return spread; } @@ -7135,8 +7360,8 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * intermediate filtered table materialised. Closes a large * latency gap on ORDER BY + LIMIT shapes that were previously * dominated by the filtered-table materialisation step. */ - if (where_expr && take_expr && has_sort && !by_expr && !nearest_expr) { - if (ray_fused_topk_supported(where_expr, tbl)) { + if (take_expr && has_sort && !by_expr && !nearest_expr) { + if (!where_expr || ray_fused_topk_supported(where_expr, tbl)) { /* Walk the dict and check: exactly one asc/desc clause naming * a single scalar column, take is an atom K, and every * output column is a -RAY_SYM source-column reference (no diff --git a/src/ops/string.c b/src/ops/string.c index 501e89431..52a792f68 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -987,171 +987,148 @@ static bool substr_scalar_arg(ray_t* v, int64_t* out) { } } -static ray_t* substr_str_scalar_view(ray_t* input, int64_t start, int64_t length) { - if (!input || input->type != RAY_STR) - return NULL; - - int64_t nrows = input->len; - ray_t* result = ray_vec_new(RAY_STR, nrows); - if (!result || RAY_IS_ERR(result)) return result ? result : ray_error("oom", NULL); - result->len = nrows; +/* True when a whole-column (scalar) start/length argument is null. Such an + * argument applies to every row, so the entire result is null — and a null + * integer scalar is INT64_MIN, which must never reach the `scalar - 1` + * subtraction in the row loop (signed-overflow UB). Only scalars are tested + * here; the per-row vector case is handled inline via ray_vec_is_null. */ +static bool substr_scalar_is_null(ray_t* v) { + if (!v) return false; + if (ray_is_atom(v)) return RAY_ATOM_IS_NULL(v); + if (ray_is_vec(v) && v->len == 1 && ray_vec_may_have_nulls(v)) + return ray_vec_is_null(v, 0); + return false; +} - const ray_str_t* src = NULL; - const char* pool = NULL; - str_resolve(input, &src, &pool); - ray_t* owner = (input->attrs & RAY_ATTR_SLICE) ? input->slice_parent : input; - ray_t* pool_obj = owner ? owner->str_pool : NULL; - if (pool_obj && !RAY_IS_ERR(pool_obj)) { - ray_retain(pool_obj); - result->str_pool = pool_obj; +/* Per-row start / length argument of substr: an atom, a 1-element vector + * (scalar), or a vector with one value per row (I64 / I32 / F64). `ok` is + * false for a null. */ +typedef struct { + int64_t scalar; + const int64_t* i64; + const int32_t* i32; + const double* f64; + ray_t* v; /* the vector, for null checks; NULL for scalars */ + bool all_null; +} substr_arg_t; + +static bool substr_arg_init(ray_t* v, int64_t nrows, substr_arg_t* a) { + memset(a, 0, sizeof(*a)); + int64_t sc; + if (substr_scalar_arg(v, &sc)) { a->scalar = sc; return true; } + if (substr_scalar_is_null(v)) { a->all_null = true; return true; } + if (!ray_is_vec(v) || v->len != nrows) return false; + a->v = v; + switch (v->type) { + case RAY_I64: a->i64 = (const int64_t*)ray_data(v); return true; + case RAY_I32: a->i32 = (const int32_t*)ray_data(v); return true; + case RAY_F64: a->f64 = (const double*)ray_data(v); return true; + default: return false; } +} - ray_str_t* dst = (ray_str_t*)ray_data(result); - for (int64_t i = 0; i < nrows; i++) { - const ray_str_t* s = &src[i]; - ray_str_t* d = &dst[i]; - memset(d, 0, sizeof(*d)); +static inline bool substr_arg_at(const substr_arg_t* a, int64_t r, int64_t* out) { + if (a->all_null) return false; + if (!a->v) { *out = a->scalar; return true; } + if (a->i64) { int64_t x = a->i64[r]; if (x == NULL_I64) return false; *out = x; return true; } + if (a->i32) { int32_t x = a->i32[r]; if (x == NULL_I32) return false; *out = (int64_t)x; return true; } + double d = a->f64[r]; + if (d != d) return false; + *out = (int64_t)d; + return true; +} - int64_t st = start - 1; +/* Substring of a STR column as descriptors over the column's own pool: + * an inline result copies its bytes, a longer one points into the parent + * pool at the shifted offset. No bytes are copied and no pool is built, + * so the pass is descriptor-bound and runs on the worker pool. A null + * start or length gives a null (empty) row; the empty result of a start + * past the end is an empty row. Returns NULL for shapes it does not take + * (the caller keeps the general loop). */ +typedef struct { + const ray_str_t* src; + const char* pool; + ray_str_t* dst; + substr_arg_t start; + substr_arg_t len; + _Atomic(uint32_t) any_null; + _Atomic(uint32_t) range_err; +} substr_view_ctx_t; + +static void substr_view_fn(void* vctx, uint32_t worker_id, int64_t lo, int64_t hi) { + (void)worker_id; + substr_view_ctx_t* c = (substr_view_ctx_t*)vctx; + bool null_seen = false, range_seen = false; + for (int64_t i = lo; i < hi; i++) { + ray_str_t* d = &c->dst[i]; + memset(d, 0, sizeof(*d)); + int64_t st, ln; + if (!substr_arg_at(&c->start, i, &st) || !substr_arg_at(&c->len, i, &ln)) { + null_seen = true; + continue; + } + const ray_str_t* s = &c->src[i]; int64_t sl = (int64_t)s->len; + st -= 1; /* 1-based → 0-based */ if (st < 0) st = 0; if (st >= sl) continue; - - int64_t ln = length; if (ln < 0 || ln > sl - st) ln = sl - st; if (ln <= 0) continue; - + const char* sp = ray_str_t_ptr(s, c->pool) + st; d->len = (uint32_t)ln; - if (!ray_str_is_inline(s) && !pool) { - ray_release(result); - return NULL; - } - const char* sp = ray_str_t_ptr(s, pool) + st; if (ln <= RAY_STR_INLINE_MAX) { memcpy(d->data, sp, (size_t)ln); - } else if (!ray_str_is_inline(s) && pool_obj) { - if ((uint64_t)s->pool_off + (uint64_t)st > UINT32_MAX) { - ray_release(result); - return ray_error("range", "substr: pool offset exceeds %lld bytes", (long long)UINT32_MAX); - } + } else { + /* a pooled result needs a pooled source (an inline source is at + * most 12 bytes, so a longer result never comes from one) */ + if ((uint64_t)s->pool_off + (uint64_t)st > UINT32_MAX) { range_seen = true; d->len = 0; continue; } memcpy(d->prefix, sp, 4); d->pool_off = s->pool_off + (uint32_t)st; - ray_str_t_cache_hash(d, pool); - } else { - ray_release(result); - return NULL; + /* hash32 stays 0: a consumer that needs it computes it once + * (ray_str_t_hash32); hashing every substring here paid a pass + * over the bytes that most consumers never used. */ } } - - return result; -} - -static bool substr_len_at(ray_t* len_v, int64_t row, int64_t* out) { - if (!len_v || !out) return false; - if (ray_vec_may_have_nulls(len_v)) { - if (ray_vec_is_null(len_v, row)) return false; - } - switch (len_v->type) { - case RAY_I64: { - int64_t v = ((const int64_t*)ray_data(len_v))[row]; - if (v == NULL_I64) return false; - *out = v; - return true; - } - case RAY_I32: { - int32_t v = ((const int32_t*)ray_data(len_v))[row]; - if (v == NULL_I32) return false; - *out = (int64_t)v; - return true; - } - default: - return false; - } + if (null_seen) atomic_store_explicit(&c->any_null, 1, memory_order_relaxed); + if (range_seen) atomic_store_explicit(&c->range_err, 1, memory_order_relaxed); } -static ray_t* substr_str_scalar_start_len_view(ray_t* input, - int64_t start, - ray_t* len_v) { - if (!input || input->type != RAY_STR || !len_v) - return NULL; - if (len_v->type != RAY_I64 && len_v->type != RAY_I32) - return NULL; +static ray_t* substr_str_view(ray_t* input, ray_t* start_v, ray_t* len_v) { + if (!input || input->type != RAY_STR) return NULL; int64_t nrows = input->len; - if (len_v->len != nrows) - return NULL; + substr_view_ctx_t ctx; + memset(&ctx, 0, sizeof(ctx)); + if (!substr_arg_init(start_v, nrows, &ctx.start)) return NULL; + if (!substr_arg_init(len_v, nrows, &ctx.len)) return NULL; ray_t* result = ray_vec_new(RAY_STR, nrows); if (!result || RAY_IS_ERR(result)) return result ? result : ray_error("oom", NULL); result->len = nrows; - - const ray_str_t* src = NULL; - const char* pool = NULL; - str_resolve(input, &src, &pool); + str_resolve(input, &ctx.src, &ctx.pool); ray_t* owner = (input->attrs & RAY_ATTR_SLICE) ? input->slice_parent : input; ray_t* pool_obj = owner ? owner->str_pool : NULL; if (pool_obj && !RAY_IS_ERR(pool_obj)) { ray_retain(pool_obj); result->str_pool = pool_obj; } + ctx.dst = (ray_str_t*)ray_data(result); + atomic_store_explicit(&ctx.any_null, 0, memory_order_relaxed); + atomic_store_explicit(&ctx.range_err, 0, memory_order_relaxed); - ray_str_t* dst = (ray_str_t*)ray_data(result); - int64_t st0 = start - 1; - if (st0 < 0) st0 = 0; - for (int64_t i = 0; i < nrows; i++) { - ray_str_t* d = &dst[i]; - memset(d, 0, sizeof(*d)); - - int64_t ln = 0; - if (!substr_len_at(len_v, i, &ln)) { - ray_vec_set_null(result, i, true); - continue; - } - - const ray_str_t* s = &src[i]; - int64_t sl = (int64_t)s->len; - if (st0 >= sl) continue; - - if (ln < 0 || ln > sl - st0) ln = sl - st0; - if (ln <= 0) continue; - - d->len = (uint32_t)ln; - if (!ray_str_is_inline(s) && !pool) { - ray_release(result); - return NULL; - } - const char* sp = ray_str_t_ptr(s, pool) + st0; - if (ln <= RAY_STR_INLINE_MAX) { - memcpy(d->data, sp, (size_t)ln); - } else if (!ray_str_is_inline(s) && pool_obj) { - if ((uint64_t)s->pool_off + (uint64_t)st0 > UINT32_MAX) { - ray_release(result); - return ray_error("range", "substr: pool offset exceeds %lld bytes", (long long)UINT32_MAX); - } - memcpy(d->prefix, sp, 4); - d->pool_off = s->pool_off + (uint32_t)st0; - ray_str_t_cache_hash(d, pool); - } else { - ray_release(result); - return NULL; - } + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, nrows, RAY_PARALLEL_THRESHOLD)) + ray_pool_dispatch(pool, substr_view_fn, &ctx, nrows); + else + substr_view_fn(&ctx, 0, 0, nrows); + if (atomic_load_explicit(&ctx.range_err, memory_order_relaxed)) { + ray_release(result); + return ray_error("range", "substr: pool offset exceeds %lld bytes", (long long)UINT32_MAX); } - + if (atomic_load_explicit(&ctx.any_null, memory_order_relaxed)) + result->attrs |= RAY_ATTR_HAS_NULLS; return result; } -/* True when a whole-column (scalar) start/length argument is null. Such an - * argument applies to every row, so the entire result is null — and a null - * integer scalar is INT64_MIN, which must never reach the `scalar - 1` - * subtraction in the row loop (signed-overflow UB). Only scalars are tested - * here; the per-row vector case is handled inline via ray_vec_is_null. */ -static bool substr_scalar_is_null(ray_t* v) { - if (!v) return false; - if (ray_is_atom(v)) return RAY_ATOM_IS_NULL(v); - if (ray_is_vec(v) && v->len == 1 && ray_vec_may_have_nulls(v)) - return ray_vec_is_null(v, 0); - return false; -} - ray_t* exec_substr(ray_graph_t* g, ray_op_t* op) { ray_t* input = exec_node(g, op_child(g, op, 0)); ray_t* start_v = exec_node(g, op_child(g, op, 1)); @@ -1167,26 +1144,14 @@ ray_t* exec_substr(ray_graph_t* g, ray_op_t* op) { bool is_str = (input->type == RAY_STR); if (is_str) { - int64_t s_const = 0, l_const = 0; - if (substr_scalar_arg(start_v, &s_const) && - substr_scalar_arg(len_v, &l_const)) { - ray_t* view = substr_str_scalar_view(input, s_const, l_const); - if (view) { - ray_release(input); - ray_release(start_v); - ray_release(len_v); - return view; - } - } - if (substr_scalar_arg(start_v, &s_const) && - !ray_is_atom(len_v) && len_v->len == nrows) { - ray_t* view = substr_str_scalar_start_len_view(input, s_const, len_v); - if (view) { - ray_release(input); - ray_release(start_v); - ray_release(len_v); - return view; - } + /* Descriptors over the column's own pool, for every scalar / per-row + * combination of start and length that reads as an integer. */ + ray_t* view = substr_str_view(input, start_v, len_v); + if (view) { + ray_release(input); + ray_release(start_v); + ray_release(len_v); + return view; } } diff --git a/src/ops/system.c b/src/ops/system.c index 6c0a2627f..96ef785c3 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -873,7 +873,8 @@ ray_t* ray_mem_ts_fn(ray_t** args, int64_t n) { * pages/pools. Rayforce values are reference-counted, so this is allocator * GC rather than a tracing collector. Variadic to allow `(.sys.gc)`. */ ray_t* ray_gc_fn(ray_t** args, int64_t n) { - (void)args; (void)n; + (void)args; + if (n != 0) return ray_error("arity", ".sys.gc takes no arguments"); ray_heap_gc(); /* Same statement-boundary rule as the REPL: an explicit maintenance * call is also a chance to notice the process has gone quiet. */ diff --git a/test/rfl/fused/topk_like_nullable_nowhere.rfl b/test/rfl/fused/topk_like_nullable_nowhere.rfl new file mode 100644 index 000000000..ef9c53fa0 --- /dev/null +++ b/test/rfl/fused/topk_like_nullable_nowhere.rfl @@ -0,0 +1,37 @@ +;; The fused filter + top-k takes a `like` over a text column that holds +;; empty strings (a null text cell is the empty string on every like path), +;; and a sort + take with no where: at all — both used to fall back to a full +;; filter / sort of the table. Results are checked against the unfused +;; spelling. +(set N 120000) +(set i (til N)) +(set url (as 'SYMBOL (map (fn [k] (if (== 0 (% k 97)) (format "http://google.com/q/%" k) (if (== 0 (% k 41)) "" (format "http://site%.example.com/p/%" (% k 500) k)))) i))) +(set us (as 'STR url)) +(set ts (% (* i 7919) 100003)) +(set T (table [url us ts k] (list url us ts (% i 17)))) +(count (select {from: T where: (nil? url)})) -- 2896 +;; like on the nullable SYM column: fused select equals the direct like +(count (select {from: T where: (like url "*google*")})) -- 1238 +(== (count (select {from: T where: (like url "*google*")})) (sum (as 'I64 (like url "*google*")))) -- true +(== (count (select {from: T where: (like us "*google*")})) (sum (as 'I64 (like us "*google*")))) -- true +;; top-k over the like: same rows as sorting the filtered table +(set A (select {from: T where: (like url "*google*") asc: ts take: 10})) +(set B (select {from: (select {from: T where: (like url "*google*")}) asc: ts take: 10})) +(all (== (at A 'ts) (at B 'ts))) -- true +(all (== (at A 'url) (at B 'url))) -- true +(count (cols A)) -- 4 +;; the sort key need not be in the projection +(all (== (at (select {from: T u: url where: (like url "*google*") asc: ts take: 10}) 'u) (at B 'url))) -- true +(all (== (at (select {from: T u: us where: (like us "*google*") desc: ts take: 10}) 'u) (at (select {from: (select {from: T where: (like url "*google*")}) desc: ts take: 10}) 'us))) -- true +;; a pattern the empty string matches admits the null rows on both paths +(== (count (select {from: T where: (like url "*") asc: ts take: 200000})) (sum (as 'I64 (like url "*")))) -- true +(== (count (select {from: T where: (like url "*") asc: ts take: 200000})) 120000) -- true +;; and with a projection list +(all (== (at (select {from: T u: url t: ts where: (like us "*google*") asc: ts take: 10}) 't) (at B 'ts))) -- true +;; no where: at all — the whole table's top-k, ascending and descending +(all (== (at (select {from: T asc: ts take: 10}) 'ts) (at (select {from: (select {from: T asc: ts}) take: 10}) 'ts))) -- true +(all (== (at (select {from: T desc: ts take: 10}) 'ts) (at (select {from: (select {from: T desc: ts}) take: 10}) 'ts))) -- true +(first (at (select {from: T asc: ts take: 1}) 'ts)) -- 0 +(count (select {from: T desc: ts take: 25})) -- 25 +;; empty strings sort first as null text +(first (at (select {from: T asc: us take: 1}) 'us)) -- "" diff --git a/test/rfl/query/shared_node_memo.rfl b/test/rfl/query/shared_node_memo.rfl new file mode 100644 index 000000000..239a5f7ef --- /dev/null +++ b/test/rfl/query/shared_node_memo.rfl @@ -0,0 +1,32 @@ +;; A DAG node with several consumers is executed once and its value shared +;; (exec_node memo). The answers must equal the per-consumer evaluation the +;; engine used to do, including when one consumer's kernel would have been +;; free to reuse the input buffer in place (rc == 1) while a sibling still +;; read it. +(set N 70000) +(set i (til N)) +(set S (as 'STR (map (fn [k] (if (== 0 (% k 11)) "" (if (== 0 (% k 3)) (format "http://www.host%.example.org/path/%/page?id=%" (% k 500) k (* k 13)) (if (== 0 (% k 7)) (format "ab%" (% k 10)) (format "https://host%.example.org/p/%" (% k 500) k))))) i))) +(set T (table [S] (list S))) +;; a let-bound string search used twice and three times equals its explicit form +(all (== (at (select {from: T x: (let p (str-find S "://") (+ p p))}) 'x) (at (select {from: T x: (+ (str-find S "://") (str-find S "://"))}) 'x))) -- true +(all (== (at (select {from: T x: (let p (str-find S "://") (+ p (+ p p)))}) 'x) (at (select {from: T x: (* 3 (str-find S "://"))}) 'x))) -- true +;; the shared node feeds both an arithmetic consumer and a comparison; the +;; comparison must see the original values +(set R (select {from: T s: S x1: (let p (str-find S "://") (as 'I64 (within p [4 5]))) x3: (let p (str-find S "://") (let s (substr S (+ p 4) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (as 'I64 (not (nil? sl))))))) x4: (let p (str-find S "://") (let s (substr S (+ p 4) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (as 'I64 (and (within p [4 5]) (not (nil? sl)))))))) pp: (let p (str-find S "://") (let s (substr S (+ p 4) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (+ p (* 0 sl)))))) p0: (str-find S "://")})) +(count (select {from: R where: (!= x4 (* x1 x3))})) -- 0 +(count (select {from: R where: (!= pp p0)})) -- 0 +(sum (at R 'x4)) -- 57576 +;; the whole derived host expression equals its unshared spelling +(set host (fn [] (select {from: T k: (let p (str-find S "://") (let s (substr S (+ p 4) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (if (and (within p [4 5]) (== (substr S 1 4) "http") (not (nil? sl))) (substr r 1 sl) S)))))}))) +(count (distinct (at (host) 'k))) -- 511 +(sum (as 'I64 (strlen (at (host) 'k)))) -- 1099454 +;; a shared node used both outside an `if` and inside its branches: the +;; branch runs over its own rows only, so the value computed there must not +;; be handed to the consumer that runs over the whole table (and vice versa) +(set c (< (% i 7) 3)) +(set U (table [S c] (list S c))) +(all (== (at (select {from: U r: (let x (upper S) (if c (concat x "?") (concat x "!")))}) 'r) (at (select {from: U r: (if c (concat (upper S) "?") (concat (upper S) "!"))}) 'r))) -- true +(all (== (at (select {from: U r: (let x (strlen S) (if c x (+ x 1000)))}) 'r) (at (select {from: U r: (if c (strlen S) (+ (strlen S) 1000))}) 'r))) -- true +(all (== (at (select {from: U r: (let x (strlen S) (+ x (if c x (+ x 1000))))}) 'r) (at (select {from: U r: (+ (strlen S) (if c (strlen S) (+ (strlen S) 1000)))}) 'r))) -- true +(all (== (at (select {from: U r: (let x (substr S 8 5) (if c x (concat x "-")))}) 'r) (at (select {from: U r: (if c (substr S 8 5) (concat (substr S 8 5) "-"))}) 'r))) -- true +(sum (at (select {from: U r: (let x (strlen S) (+ x (if c x (+ x 1000))))}) 'r)) -- 41272796 diff --git a/test/rfl/strop/substr_if_str_views.rfl b/test/rfl/strop/substr_if_str_views.rfl new file mode 100644 index 000000000..13774ac48 --- /dev/null +++ b/test/rfl/strop/substr_if_str_views.rfl @@ -0,0 +1,33 @@ +;; substr over a STR column with per-row start / length is a descriptor view +;; over the column's pool, and `if` over two STR columns is a descriptor pick +;; whatever pools the sides come from. Every answer is checked against the +;; per-row evaluation of the same expression. +(set N 120000) +(set i (til N)) +(set S (as 'STR (map (fn [k] (if (== 0 (% k 11)) "" (if (== 0 (% k 3)) (format "http://www.host%.example.org/path/%/page?id=%" (% k 500) k (* k 13)) (if (== 0 (% k 7)) (format "ab%" (% k 10)) (format "https://host%.example.org/p/%" (% k 500) k))))) i))) +(set st (% (* i 7) 19)) +(set ln (- (% (* i 5) 23) 3)) +(set stn (as 'I64 (map (fn [j] (if (== 0 (% j 13)) 0N (% (* j 7) 19))) i))) +(set kk (% i 17)) +(set T (table [S st ln stn k] (list S st ln stn kk))) +(set oracle (fn [f] (as 'STR (map f i)))) +;; vector start, whole tail +(all (== (at (select {from: T x: (substr S st -1)}) 'x) (oracle (fn [j] (substr (at S j) (at st j) -1))))) -- true +;; vector start and vector length (negative lengths, past-the-end starts) +(all (== (at (select {from: T x: (substr S st ln)}) 'x) (oracle (fn [j] (substr (at S j) (at st j) (at ln j)))))) -- true +;; a float start vector reads as its integer image +(all (== (at (select {from: T x: (substr S (as 'F64 st) -1)}) 'x) (oracle (fn [j] (substr (at S j) (at st j) -1))))) -- true +;; null starts give empty (null) rows +(all (== (at (select {from: T x: (substr S stn 4)}) 'x) (oracle (fn [j] (if (nil? (at stn j)) "" (substr (at S j) (at stn j) 4)))))) -- true +;; scalar start and length, the old view shape +(all (== (at (select {from: T x: (substr S 5 7)}) 'x) (oracle (fn [j] (substr (at S j) 5 7))))) -- true +;; a substring of a substring stays a view; the pool is shared, not copied +(all (== (at (select {from: T x: (substr (substr S 9 -1) 2 5)}) 'x) (oracle (fn [j] (substr (substr (at S j) 9 -1) 2 5))))) -- true +;; if over two STR sides from different pools, with empty strings on both +(all (== (at (select {from: T x: (if (== 0 (% k 2)) (substr S 9 -1) S)}) 'x) (oracle (fn [j] (if (== 0 (% (at kk j) 2)) (substr (at S j) 9 -1) (at S j)))))) -- true +;; if over two views of one pool +(all (== (at (select {from: T x: (if (== 0 (% k 3)) (substr S 5 -1) (substr S 2 6))}) 'x) (oracle (fn [j] (if (== 0 (% (at kk j) 3)) (substr (at S j) 5 -1) (substr (at S j) 2 6)))))) -- true +;; the picked side's empty strings are nulls of the result +(count (select {from: (select {from: T x: (if (== 0 (% k 2)) (substr S 9 -1) S)}) where: (nil? x)})) -- 16410 +;; a scalar side keeps the per-row path +(all (== (at (select {from: T x: (if (== 0 (% k 3)) S "zzz")}) 'x) (oracle (fn [j] (if (== 0 (% (at kk j) 3)) (at S j) "zzz"))))) -- true diff --git a/test/rfl/system/reserved_namespace.rfl b/test/rfl/system/reserved_namespace.rfl index fd0d72382..69a451442 100644 --- a/test/rfl/system/reserved_namespace.rfl +++ b/test/rfl/system/reserved_namespace.rfl @@ -5,10 +5,10 @@ ;; `'?` regardless of arity — so we exercise by calling, which is ;; what actually matters here.) ;; .sys.gc returns 0 on success — doubles as a binding-exists probe. -;; Registered as variadic so both (.sys.gc) and (.sys.gc 0) work; -;; other .sys.* info builtins follow the same convention. +;; Registered as variadic so the zero-argument call remains valid while +;; the implementation can reject unexpected arguments explicitly. (.sys.gc) -- 0 -(.sys.gc 0) -- 0 +(.sys.gc 0) !- arity (count (.sys.info)) -- 5 (count (.sys.mem)) -- 16 (count (.sys.build)) -- 2 @@ -116,7 +116,7 @@ internals !- name (del .sys.gc) !- reserve (del .os.getenv) !- reserve ;; Built-in still resolves after the blocked shadow attempts. -(.sys.gc 0) -- 0 +(.sys.gc) -- 0 (nil? .os.getenv) -- false ;; User-level dotted writes under a non-`.` root still work. (set myns.x 1) diff --git a/test/rfl/system/system_branch_cov.rfl b/test/rfl/system/system_branch_cov.rfl index bb67d9ed6..d07fe3aed 100644 --- a/test/rfl/system/system_branch_cov.rfl +++ b/test/rfl/system/system_branch_cov.rfl @@ -180,8 +180,8 @@ ;; ray_gc_fn (line 539) ;; ══════════════════════════════════════════════════════════════════════ (.sys.gc) -- 0 -(.sys.gc 0) -- 0 -(.sys.gc "x") -- 0 +(.sys.gc 0) !- arity +(.sys.gc "x") !- arity ;; ────────────── teardown ────────────── (.sys.exec "rm -rf /tmp/rfl_sys_bc_*")