diff --git a/.github/workflows/rayforce-audit-comment.yml b/.github/workflows/rayforce-audit-comment.yml index 2e29786cf..16964c8ef 100644 --- a/.github/workflows/rayforce-audit-comment.yml +++ b/.github/workflows/rayforce-audit-comment.yml @@ -33,6 +33,13 @@ jobs: body="audit-output/rayforce-audit-comment.md" report="audit-output/rayforce-audit.md" + case "$RUN_CONCLUSION" in + cancelled|skipped) + echo "::notice title=Rayforce audit comment skipped::Audit workflow run ${RUN_ID} ended with conclusion '${RUN_CONCLUSION}', so no PR comment is needed." + exit 0 + ;; + esac + pr_number=$(python3 - <<'PY' import json, os with open(os.environ['GITHUB_EVENT_PATH'], 'r', encoding='utf-8') as f: @@ -96,8 +103,10 @@ jobs: Workflow run: ${RUN_URL} EOF_PASS - gh api -X PATCH "repos/${REPO}/issues/comments/${existing}" \ - -f body="$(cat "$body")" >/dev/null + if ! gh api -X PATCH "repos/${REPO}/issues/comments/${existing}" \ + -f body="$(cat "$body")" >/dev/null; then + echo "::notice title=Rayforce audit comment write failed::Could not update the existing PR comment. The required check and artifact remain authoritative." + fi fi exit 0 fi @@ -124,9 +133,13 @@ jobs: | tail -n 1) if [ -n "$comment_id" ]; then - gh api -X PATCH "repos/${REPO}/issues/comments/${comment_id}" \ - -f body="$(cat "$body")" >/dev/null + if ! gh api -X PATCH "repos/${REPO}/issues/comments/${comment_id}" \ + -f body="$(cat "$body")" >/dev/null; then + echo "::notice title=Rayforce audit comment write failed::Could not update the existing PR comment. The required check and artifact remain authoritative." + fi else - gh api -X POST "repos/${REPO}/issues/${pr_number}/comments" \ - -f body="$(cat "$body")" >/dev/null + if ! gh api -X POST "repos/${REPO}/issues/${pr_number}/comments" \ + -f body="$(cat "$body")" >/dev/null; then + echo "::notice title=Rayforce audit comment write failed::Could not create the PR comment. The required check and artifact remain authoritative." + fi fi diff --git a/src/ops/arith.c b/src/ops/arith.c index 6c1e7c17d..d22c8aba7 100644 --- a/src/ops/arith.c +++ b/src/ops/arith.c @@ -145,6 +145,14 @@ ray_t* ray_sub_fn(ray_t* a, ray_t* b) { if ((a && RAY_IS_PARTED(a->type)) || (b && RAY_IS_PARTED(b->type))) return atomic_map_binary_op(ray_sub_fn, OP_SUB, a, b); + /* Match add: temporal offsets must be integer typed. Without this, + * DATE/TIME/TIMESTAMP - F64 reads the float payload through as_i64() and + * either truncates semantics or uses raw union bits. */ + if (((a->type == -RAY_F64 || a->type == -RAY_F32) && is_temporal(b)) || + (is_temporal(a) && (b->type == -RAY_F64 || b->type == -RAY_F32))) + return ray_error("type", "subtract: temporal arithmetic requires integer offsets, got %s and %s", + ray_type_name(a->type), ray_type_name(b->type)); + /* Temporal - int null propagation (both operands) */ if (is_temporal(a) && is_numeric(b)) { if (RAY_ATOM_IS_NULL(a) || RAY_ATOM_IS_NULL(b)) @@ -219,6 +227,11 @@ ray_t* ray_mul_fn(ray_t* a, ray_t* b) { if ((a && RAY_IS_PARTED(a->type)) || (b && RAY_IS_PARTED(b->type))) return atomic_map_binary_op(ray_mul_fn, OP_MUL, a, b); + if (((a->type == -RAY_F64 || a->type == -RAY_F32) && b->type == -RAY_TIME) || + (a->type == -RAY_TIME && (b->type == -RAY_F64 || b->type == -RAY_F32))) + return ray_error("type", "multiply: temporal arithmetic requires integer factors, got %s and %s", + ray_type_name(a->type), ray_type_name(b->type)); + /* int * TIME → TIME, TIME * int → TIME */ if (is_numeric(a) && b->type == -RAY_TIME) { if (RAY_ATOM_IS_NULL(a) || RAY_ATOM_IS_NULL(b)) return ray_typed_null(-RAY_TIME); diff --git a/src/ops/collection.c b/src/ops/collection.c index 056f7dec7..cfc0ada95 100644 --- a/src/ops/collection.c +++ b/src/ops/collection.c @@ -1078,6 +1078,11 @@ static ray_t* parted_to_flat_vec(ray_t* x) { for (int64_t s = 0; s < x->len; s++) if (segs[s]) total += segs[s]->len; + /* RAY_LIST: share (retain) elements — ray_vec_new rejects type 0 and + * the per-cell copy below has no notion of nested elements. */ + if (base == RAY_LIST) + return parted_flatten_list(segs, x->len, total); + ray_t* out = ray_vec_new(base, base == RAY_STR ? 0 : total); if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); if (base != RAY_STR) out->len = total; diff --git a/src/ops/exec.c b/src/ops/exec.c index 15274d4e4..cb15929e5 100644 --- a/src/ops/exec.c +++ b/src/ops/exec.c @@ -1836,11 +1836,16 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { /* RAY_STR: deep-copy to handle multi-pool segments */ if (base == RAY_STR) return parted_flatten_str(sps, col->len, total); + /* RAY_LIST: share (retain) elements — byte-copy would + * alias them without a refcount (issue #355). */ + if (base == RAY_LIST) + return parted_flatten_list(sps, col->len, total); uint8_t sba = (base == RAY_SYM) ? parted_sym_max_attrs(sps, col->len) : 0; ray_t* flat = typed_vec_new(base, sba, total); - if (!flat || RAY_IS_ERR(flat)) return ray_error("oom", NULL); + if (!flat || RAY_IS_ERR(flat)) + return flat ? flat : ray_error("oom", NULL); flat->len = total; ray_t** segs = sps; int64_t off = 0; @@ -2891,6 +2896,8 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_t* head_vec; if (base == RAY_STR) { head_vec = parted_head_str(sp, col->len, n); + } else if (base == RAY_LIST) { + head_vec = parted_head_list(sp, col->len, n); } else { uint8_t ba = (base == RAY_SYM) ? parted_sym_max_attrs(sp, col->len) : 0; @@ -3022,6 +3029,8 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_t* tail_vec; if (base == RAY_STR) { tail_vec = parted_tail_str(tsp, col->len, n); + } else if (base == RAY_LIST) { + tail_vec = parted_tail_list(tsp, col->len, n); } else { uint8_t tba = (base == RAY_SYM) ? parted_sym_max_attrs(tsp, col->len) : 0; @@ -3691,9 +3700,11 @@ static ray_t* flatten_parted_col(ray_t* col) { int64_t total = ray_parted_nrows(col); if (base == RAY_STR) return parted_flatten_str(segs, col->len, total); + if (base == RAY_LIST) + return parted_flatten_list(segs, col->len, total); uint8_t sba = (base == RAY_SYM) ? parted_sym_max_attrs(segs, col->len) : 0; ray_t* flat = typed_vec_new(base, sba, total); - if (!flat || RAY_IS_ERR(flat)) return ray_error("oom", NULL); + if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); flat->len = total; int64_t off = 0; uint8_t seg_nulls = 0; diff --git a/src/ops/filter.c b/src/ops/filter.c index f5c78165c..ce7153101 100644 --- a/src/ops/filter.c +++ b/src/ops/filter.c @@ -70,6 +70,35 @@ static void parted_gather_col(ray_t* parted_col, const int64_t* match_idx, /* Filter a single vector by boolean predicate. */ static ray_t* exec_filter_vec(ray_t* input, ray_t* pred, int64_t pass_count) { + /* RAY_LIST: cells are ray_t* — gather them with a retain. The + * byte-copy loop below would alias elements without a refcount (and + * col_vec_new rejects RAY_LIST, type 0, outright). */ + if (input->type == RAY_LIST) { + if (input->len != pred->len) + return ray_error("length", "filter: predicate length must match input, got %lld and %lld", + (long long)input->len, (long long)pred->len); + ray_t* result = ray_list_new(pass_count); + if (!result || RAY_IS_ERR(result)) return result; + ray_t** dst = (ray_t**)ray_data(result); + ray_morsel_t mi, mf; + ray_morsel_init(&mi, input); + ray_morsel_init(&mf, pred); + int64_t out_idx = 0; + while (ray_morsel_next(&mi) && ray_morsel_next(&mf)) { + uint8_t* bits = (uint8_t*)mf.morsel_ptr; + ray_t** src = (ray_t**)mi.morsel_ptr; + for (int64_t i = 0; i < mi.morsel_len; i++) { + if (!bits[i]) continue; + if (out_idx >= pass_count) break; + ray_t* e = src[i]; + if (e) ray_retain(e); + dst[out_idx++] = e; + } + } + result->len = out_idx; + return result; + } + uint8_t esz = col_esz(input); ray_t* result = col_vec_new(input, pass_count); if (!result || RAY_IS_ERR(result)) return result; @@ -114,6 +143,11 @@ static ray_t* exec_filter_parted_vec(ray_t* parted_col, ray_t* pred, int64_t n_segs = parted_col->len; uint8_t* pred_data = (uint8_t*)ray_data(pred); + /* RAY_LIST: share (retain) elements — the byte-copy path below would + * alias them without a refcount and double-free on release. */ + if (base == RAY_LIST) + return parted_filter_list(segs, n_segs, pred_data, pass_count); + /* RAY_STR: deep-copy to handle multi-pool segments */ if (base == RAY_STR) { ray_t* result = ray_vec_new(RAY_STR, pass_count); @@ -392,12 +426,47 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { } } if (RAY_IS_PARTED(col->type)) has_parted_cols = true; - ray_t* nc = typed_vec_new(out_type, out_attrs, pass_count); + /* RAY_LIST == 0; typed_vec_new rejects type <= 0, which would leave + * new_cols[c] NULL and silently DROP the LIST column. Allocate it + * as a proper list; elements are gathered (with a retain) in the + * dedicated LIST pass below. */ + ray_t* nc = (out_type == RAY_LIST) + ? ray_list_new(pass_count) + : typed_vec_new(out_type, out_attrs, pass_count); if (!nc || RAY_IS_ERR(nc)) { new_cols[c] = NULL; continue; } nc->len = pass_count; new_cols[c] = nc; } + /* LIST columns (flat or parted-LIST): gather element pointers with a + * retain. The byte-copy gather branches below copy raw 8-byte ray_t* + * cells without retaining — that would alias source elements and + * double-free on release (issue #355) — so LIST columns are filled + * here and skipped there. */ + for (int64_t c = 0; c < ncols; c++) { + if (!new_cols[c]) continue; + ray_t* col = ray_table_get_col_idx(input, c); + if (!col) continue; + if (col->type == RAY_LIST) { + ray_t** d = (ray_t**)ray_data(new_cols[c]); + ray_t** s = (ray_t**)ray_data(col); + for (int64_t i = 0; i < pass_count; i++) { + ray_t* e = s[match_idx[i]]; + if (e) ray_retain(e); + d[i] = e; + } + } else if (parted_base_is_list(col)) { + ray_release(new_cols[c]); + new_cols[c] = parted_gather_list_rows((ray_t**)ray_data(col), + col->len, match_idx, + pass_count); + if (new_cols[c] && RAY_IS_ERR(new_cols[c])) { + ray_error_free(new_cols[c]); + new_cols[c] = NULL; + } + } + } + if (has_parted_cols) { /* Parted-aware gather: use parted_gather_col for parted columns, * sequential flat gather for non-parted columns */ @@ -405,6 +474,8 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { ray_t* col = ray_table_get_col_idx(input, c); if (!col || !new_cols[c]) continue; if (col->type == RAY_MAPCOMMON) continue; /* already materialized */ + if (col->type == RAY_LIST || parted_base_is_list(col)) + continue; /* gathered above with retain */ if (RAY_IS_PARTED(col->type)) { int8_t pbase = (int8_t)RAY_PARTED_BASETYPE(col->type); if (pbase == RAY_STR) { @@ -430,6 +501,7 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { if (!new_cols[c]) continue; ray_t* col = ray_table_get_col_idx(input, c); if (col && col->type == RAY_MAPCOMMON) continue; /* already materialized */ + if (col && col->type == RAY_LIST) continue; /* gathered above with retain */ int64_t ci = mgctx.ncols; mgctx.srcs[ci] = (char*)ray_data(col); mgctx.dsts[ci] = (char*)ray_data(new_cols[c]); @@ -447,6 +519,7 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { for (int64_t c = 0; c < ncols; c++) { ray_t* col = ray_table_get_col_idx(input, c); if (!col || !new_cols[c]) continue; + if (col->type == RAY_LIST) continue; /* gathered above with retain */ uint8_t esz = col_esz(col); char* src = (char*)ray_data(col); char* dst = (char*)ray_data(new_cols[c]); @@ -465,6 +538,8 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { if (!new_cols[c]) continue; ray_t* col = ray_table_get_col_idx(input, c); if (!col) continue; + if (col->type == RAY_LIST || parted_base_is_list(col)) + continue; /* elements gathered+retained; no str-pool to touch */ if (RAY_IS_PARTED(col->type)) { int8_t pb = (int8_t)RAY_PARTED_BASETYPE(col->type); if (pb != RAY_STR) { @@ -554,6 +629,35 @@ ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit) { out_attrs = parted_sym_max_attrs(sp, col->len); } else out_attrs = col->attrs; } + /* LIST (flat or parted-LIST): gather element pointers with a + * retain — the byte-copy gather below would alias them without a + * refcount and double-free on release (issue #355). typed_vec_new + * also rejects RAY_LIST (type 0), which would silently drop the + * column. */ + if (out_type == RAY_LIST) { + ray_t* lcol; + if (RAY_IS_PARTED(col->type)) { + lcol = parted_gather_list_rows((ray_t**)ray_data(col), + col->len, match_idx, found); + } else { + lcol = ray_list_new(found); + if (lcol && !RAY_IS_ERR(lcol)) { + lcol->len = found; + ray_t** d = (ray_t**)ray_data(lcol); + ray_t** s = (ray_t**)ray_data(col); + for (int64_t j = 0; j < found; j++) { + ray_t* e = s[match_idx[j]]; + if (e) ray_retain(e); + d[j] = e; + } + } + } + if (!lcol) continue; + if (RAY_IS_ERR(lcol)) { ray_error_free(lcol); continue; } + tbl = ray_table_add_col(tbl, name_id, lcol); + ray_release(lcol); + continue; + } uint8_t esz = ray_sym_elem_size(out_type, out_attrs); ray_t* new_col = typed_vec_new(out_type, out_attrs, found); if (!new_col || RAY_IS_ERR(new_col)) continue; @@ -852,14 +956,29 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, new_cols[c] = nc; } - /* LIST columns: gather element pointers with a retain. The byte-copy - * gather paths below copy raw esz bytes (8-byte ray_t* pointers) without - * retaining — that would alias source elements and double-free on - * release — so LIST columns are filled here and skipped there. */ + /* LIST columns (flat or parted-LIST): gather element pointers with a + * retain. The byte-copy gather paths below copy raw esz bytes (8-byte + * ray_t* pointers) without retaining — that would alias source elements + * and double-free on release — so LIST columns are filled here and + * skipped there. A parted LIST column's type is RAY_PARTED_BASE + + * RAY_LIST, not RAY_LIST, so it must be matched explicitly (issue + * #355). */ for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; ray_t* col = ray_table_get_col_idx(tbl, c); - if (!col || col->type != RAY_LIST) continue; + if (!col) continue; + if (parted_base_is_list(col)) { + ray_release(new_cols[c]); + new_cols[c] = parted_gather_list_rows((ray_t**)ray_data(col), + col->len, match_idx, + pass_count); + if (new_cols[c] && RAY_IS_ERR(new_cols[c])) { + ray_error_free(new_cols[c]); + new_cols[c] = NULL; + } + continue; + } + if (col->type != RAY_LIST) continue; ray_t** d = (ray_t**)ray_data(new_cols[c]); ray_t** s = (ray_t**)ray_data(col); for (int64_t i = 0; i < pass_count; i++) { @@ -873,7 +992,8 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, for (int64_t c = 0; c < ncols; c++) { ray_t* col = ray_table_get_col_idx(tbl, c); if (!col || !new_cols[c]) continue; - if (col->type == RAY_LIST) continue; /* gathered above with retain */ + if (col->type == RAY_LIST || parted_base_is_list(col)) + continue; /* gathered above with retain */ if (RAY_IS_PARTED(col->type)) { int8_t pbase = (int8_t)RAY_PARTED_BASETYPE(col->type); if (pbase == RAY_STR) { @@ -933,7 +1053,7 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; ray_t* scol = ray_table_get_col_idx(tbl, c); - if (scol && scol->type == RAY_LIST) { + if (scol && (scol->type == RAY_LIST || parted_base_is_list(scol))) { /* LIST elements already gathered+retained; no str-pool / null * bitmap to propagate. */ } else if (scol && RAY_IS_PARTED(scol->type)) { diff --git a/src/ops/group.c b/src/ops/group.c index 71ac9a8fa..f482e08f1 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -7268,6 +7268,8 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, if (base_type == RAY_STR) { flat = parted_flatten_str(segs, col->len, total_rows); + } else if (base_type == RAY_LIST) { + flat = parted_flatten_list(segs, col->len, total_rows); } else { uint8_t base_attrs = (base_type == RAY_SYM) ? parted_sym_max_attrs(segs, col->len) : 0; @@ -7275,7 +7277,7 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, if (!flat || RAY_IS_ERR(flat)) { ray_release(flat_tbl); scratch_free(needed_hdr); - return ray_error("oom", NULL); + return flat ? flat : ray_error("oom", NULL); } /* segment cells are copied id-preserving — all partitions * resolve over the root symfile's domain (PARTED @@ -7300,7 +7302,7 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, if (!flat || RAY_IS_ERR(flat)) { ray_release(flat_tbl); scratch_free(needed_hdr); - return ray_error("oom", NULL); + return flat ? flat : ray_error("oom", NULL); } flat_tbl = ray_table_add_col(flat_tbl, name_id, flat); diff --git a/src/ops/internal.h b/src/ops/internal.h index 509a55db9..800faf4f4 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -448,6 +448,139 @@ static inline ray_t* parted_flatten_str(ray_t** segs, int64_t n_segs, int64_t to return out; } +/* ── LIST analogues of the parted STR helpers ──────────────────────────── + * A LIST cell is a ray_t* — every copy below SHARES elements via + * ray_retain, never byte-copies: a raw memcpy of the 8-byte pointers + * would alias the segments' elements without a refcount and double-free + * on release (issue #355). NULL segments contribute zero rows, matching + * parted_gather_col's row numbering. */ + +/* Flatten all rows from parted RAY_LIST segments. */ +static inline ray_t* parted_flatten_list(ray_t** segs, int64_t n_segs, + int64_t total) { + ray_t* out = ray_list_new(total); + if (!out || RAY_IS_ERR(out)) return out; + ray_t** dst = (ray_t**)ray_data(out); + int64_t pos = 0; + for (int64_t s = 0; s < n_segs; s++) { + if (!segs[s]) continue; + ray_t** src = (ray_t**)ray_data(segs[s]); + for (int64_t i = 0; i < segs[s]->len && pos < total; i++) { + ray_t* e = src[i]; + if (e) ray_retain(e); + dst[pos++] = e; + } + } + out->len = pos; + return out; +} + +/* First n rows from parted RAY_LIST segments. */ +static inline ray_t* parted_head_list(ray_t** segs, int64_t n_segs, int64_t n) { + ray_t* out = ray_list_new(n); + if (!out || RAY_IS_ERR(out)) return out; + ray_t** dst = (ray_t**)ray_data(out); + int64_t pos = 0; + for (int64_t s = 0; s < n_segs && pos < n; s++) { + if (!segs[s]) continue; + ray_t** src = (ray_t**)ray_data(segs[s]); + for (int64_t i = 0; i < segs[s]->len && pos < n; i++) { + ray_t* e = src[i]; + if (e) ray_retain(e); + dst[pos++] = e; + } + } + out->len = pos; + return out; +} + +/* Last n rows from parted RAY_LIST segments. */ +static inline ray_t* parted_tail_list(ray_t** segs, int64_t n_segs, int64_t n) { + int64_t total = 0; + for (int64_t s = 0; s < n_segs; s++) + if (segs[s]) total += segs[s]->len; + int64_t skip = total - n; + if (skip < 0) skip = 0; + + ray_t* out = ray_list_new(total - skip); + if (!out || RAY_IS_ERR(out)) return out; + ray_t** dst = (ray_t**)ray_data(out); + int64_t pos = 0, seen = 0; + for (int64_t s = 0; s < n_segs; s++) { + if (!segs[s]) continue; + ray_t** src = (ray_t**)ray_data(segs[s]); + for (int64_t i = 0; i < segs[s]->len; i++, seen++) { + if (seen < skip) continue; + ray_t* e = src[i]; + if (e) ray_retain(e); + dst[pos++] = e; + } + } + out->len = pos; + return out; +} + +/* Gather rows (global row indices, sorted ascending) from parted RAY_LIST + * segments — LIST counterpart of parted_gather_str_rows. */ +static inline ray_t* parted_gather_list_rows(ray_t** segs, int64_t n_segs, + const int64_t* idx, + int64_t count) { + ray_t* out = ray_list_new(count); + if (!out || RAY_IS_ERR(out)) return out; + ray_t** dst = (ray_t**)ray_data(out); + int64_t seg = 0; + int64_t seg_start = 0; + int64_t seg_end = (n_segs > 0 && segs[0]) ? segs[0]->len : 0; + for (int64_t j = 0; j < count; j++) { + int64_t r = idx[j]; + while (seg < n_segs - 1 && r >= seg_end) { + seg_start = seg_end; + seg++; + seg_end += segs[seg] ? segs[seg]->len : 0; + } + ray_t* e = NULL; + if (segs[seg] && r >= seg_start && r - seg_start < segs[seg]->len) + e = ((ray_t**)ray_data(segs[seg]))[r - seg_start]; + if (e) ray_retain(e); + dst[j] = e; + } + out->len = count; + return out; +} + +/* Filter parted RAY_LIST segments by a boolean predicate over the column's + * global rows. */ +static inline ray_t* parted_filter_list(ray_t** segs, int64_t n_segs, + const uint8_t* pred, + int64_t pass_count) { + ray_t* out = ray_list_new(pass_count); + if (!out || RAY_IS_ERR(out)) return out; + ray_t** dst = (ray_t**)ray_data(out); + int64_t off = 0, pos = 0; + for (int64_t s = 0; s < n_segs; s++) { + if (!segs[s]) continue; + ray_t** src = (ray_t**)ray_data(segs[s]); + for (int64_t i = 0; i < segs[s]->len; i++) { + if (!pred[off + i]) continue; + if (pos >= pass_count) break; + ray_t* e = src[i]; + if (e) ray_retain(e); + dst[pos++] = e; + } + off += segs[s]->len; + } + out->len = pos; + return out; +} + +/* True for a parted column whose segments are RAY_LIST vectors — such a + * column must go through the retaining LIST helpers above, never the + * byte-copy gather kernels. */ +static inline bool parted_base_is_list(const ray_t* col) { + return RAY_IS_PARTED(col->type) && + (int8_t)RAY_PARTED_BASETYPE(col->type) == RAY_LIST; +} + /* Same but from explicit type + attrs (for parted base type, etc.) */ static inline ray_t* typed_vec_new(int8_t type, uint8_t attrs, int64_t cap) { if (type == RAY_SYM) diff --git a/src/ops/query.c b/src/ops/query.c index 139161524..f236bebd8 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -308,6 +308,19 @@ static bool dag_pow_type_admitted(int8_t t) { return dag_numeric_type_admitted(t); } +static bool dag_type_is_temporal(int8_t t) { + if (t <= 0) return false; + if (RAY_IS_PARTED(t)) t = (int8_t)RAY_PARTED_BASETYPE(t); + return t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP; +} + +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)) + return false; + return len == 1 && (name[0] == '+' || name[0] == '-' || name[0] == '*'); +} + static bool dag_unary_numeric_name(const char* name, size_t len) { if (len == 3) return memcmp(name, "sin", 3) == 0 || @@ -1567,6 +1580,10 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { ray_op_t* right = compile_expr_dag(g, elems[2]); if (!right) return NULL; left = &g->nodes[left_id]; + if (dag_temporal_arith_needs_eval(fname, fname_len, + left->out_type, + 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))) @@ -1836,6 +1853,8 @@ static int expr_contains_agg(ray_t* expr) { } static int is_group_dag_agg_expr(ray_t* expr); /* defined below */ +static bool simplify_agg_idiom(ray_t* val_expr, ray_t* tbl, + uint16_t* out_op, ray_t** out_arg); /* ── Arith-of-aggs decomposition ────────────────────────────────────────── * A select-by output like (/ (sum a) (as 'F64 (sum b))) is not itself a @@ -2027,6 +2046,71 @@ static int is_group_dag_agg_expr(ray_t* expr) { return !expr_contains_call_named(elems[1], "distinct", 8); } +static bool expr_literal_is_temporal(ray_t* expr) { + if (!expr) return false; + int8_t t = expr->type < 0 ? (int8_t)-expr->type : expr->type; + return dag_type_is_temporal(t); +} + +static bool expr_dag_result_is_temporal(ray_t* expr, ray_t* tbl) { + if (expr_literal_is_temporal(expr)) return true; + + ray_graph_t* pg = ray_graph_new(tbl); + if (!pg) return false; + + ray_op_t* op = compile_expr_dag(pg, expr); + bool temporal = op && dag_type_is_temporal(op->out_type); + ray_graph_free(pg); + return temporal; +} + +static bool expr_contains_temporal_arith(ray_t* expr, ray_t* tbl) { + if (!expr || expr->type != RAY_LIST) return false; + + ray_t** elems = (ray_t**)ray_data(expr); + int64_t n = ray_len(expr); + if (n >= 3 && elems[0] && elems[0]->type == -RAY_SYM) { + ray_t* name = ray_sym_str(elems[0]->i64); + size_t len = name ? ray_str_len(name) : 0; + const char* s = name ? ray_str_ptr(name) : NULL; + if (len == 1 && (s[0] == '+' || s[0] == '-' || s[0] == '*')) { + if (expr_dag_result_is_temporal(elems[1], tbl) || + expr_dag_result_is_temporal(elems[2], tbl)) + return true; + } + } + + for (int64_t i = 0; i < n; i++) + if (expr_contains_temporal_arith(elems[i], tbl)) + return true; + return false; +} + +static int is_group_dag_agg_expr_dag_safe(ray_t* expr, ray_t* tbl) { + if (!is_group_dag_agg_expr(expr)) return 0; + + ray_t** elems = (ray_t**)ray_data(expr); + uint16_t op = resolve_agg_opcode(elems[0]->i64); + ray_t* agg_arg = elems[1]; + { + uint16_t new_op; + ray_t* new_arg; + if (simplify_agg_idiom(expr, tbl, &new_op, &new_arg)) { + op = new_op; + agg_arg = new_arg; + } + } + + if (expr_contains_temporal_arith(agg_arg, tbl)) + return 0; + if (agg_is_binary_agg(op)) { + if (ray_len(expr) < 3) return 1; + if (expr_contains_temporal_arith(elems[2], tbl)) + return 0; + } + return 1; +} + static int is_single_group_key_projection(ray_t* by_expr, ray_t* val_expr) { int64_t key_id = -1; if (by_expr && by_expr->type == -RAY_SYM && !(by_expr->attrs & ATTR_QUOTED)) { @@ -3380,6 +3464,7 @@ static ray_t* query_materialize_parted_col(ray_t* col) { ray_t** segs = (ray_t**)ray_data(col); int64_t total = ray_parted_nrows(col); if (base == RAY_STR) return parted_flatten_str(segs, col->len, total); + if (base == RAY_LIST) return parted_flatten_list(segs, col->len, total); uint8_t attrs = (base == RAY_SYM) ? parted_sym_max_attrs(segs, col->len) : 0; ray_t* flat = typed_vec_new(base, attrs, total); @@ -4304,6 +4389,95 @@ static ray_t* atom_broadcast_vec(ray_t* a, int64_t n) { return v; } +static ray_t* scalar_result_col(ray_t* value) { + if (!value || RAY_IS_ERR(value)) return value ? value : ray_error("domain", "select: scalar aggregate produced no result"); + + if (ray_is_atom(value)) { + ray_t* col = atom_broadcast_vec(value, 1); + if (col) return col; + + ray_t* boxed = ray_alloc(sizeof(ray_t*)); + if (!boxed) return ray_error("oom", NULL); + boxed->type = RAY_LIST; + boxed->len = 1; + ((ray_t**)ray_data(boxed))[0] = value; + ray_retain(value); + return boxed; + } + + if (ray_len(value) != 1) + return ray_error("length", "select: scalar aggregate produced %lld rows", (long long)ray_len(value)); + ray_retain(value); + return value; +} + +static ray_t* eval_scalar_agg_outputs(ray_t** dict_elems, int64_t dict_n, + ray_t* tbl, + int64_t from_id, int64_t where_id, + int64_t by_id, int64_t take_id, + int64_t asc_id, int64_t desc_id, + int64_t nearest_id) { + ray_t* result = ray_table_new(0); + if (!result || RAY_IS_ERR(result)) + return result ? result : ray_error("oom", NULL); + + int64_t nrows = ray_table_nrows(tbl); + 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; + + ray_t* val_expr = dict_elems[i + 1]; + if (!is_agg_expr(val_expr)) { + ray_release(result); + return ray_error("domain", "select: scalar aggregate fallback saw non-aggregate output"); + } + + ray_t** agg_elems = (ray_t**)ray_data(val_expr); + if (ray_len(val_expr) != 2) { + ray_release(result); + return ray_error("domain", "select: scalar aggregate fallback only supports unary aggregates"); + } + + ray_t* fn_obj = ray_env_get(agg_elems[0]->i64); + if (!fn_obj || fn_obj->type != RAY_UNARY) { + ray_release(result); + return ray_error("type", "select: aggregate must be a unary function, got %s", + fn_obj ? ray_type_name(fn_obj->type) : "null"); + } + + ray_t* src = eval_expr_per_row(agg_elems[1], tbl, nrows); + if (!src || RAY_IS_ERR(src)) { + ray_release(result); + return src ? src : ray_error("domain", "select: failed to evaluate aggregation source"); + } + + ray_unary_fn uf = (ray_unary_fn)(uintptr_t)fn_obj->i64; + ray_t* agg_value = uf(src); + ray_release(src); + if (agg_value && !RAY_IS_ERR(agg_value) && ray_is_lazy(agg_value)) + agg_value = ray_lazy_materialize(agg_value); + if (!agg_value || RAY_IS_ERR(agg_value)) { + ray_release(result); + return agg_value ? agg_value : ray_error("domain", "select: scalar aggregate evaluation failed"); + } + + ray_t* col = scalar_result_col(agg_value); + ray_release(agg_value); + if (!col || RAY_IS_ERR(col)) { + ray_release(result); + return col ? col : ray_error("domain", "select: failed to materialize scalar aggregate"); + } + result = ray_table_add_col(result, kid, col); + ray_release(col); + if (!result || RAY_IS_ERR(result)) + return result ? result : ray_error("oom", NULL); + } + + return result; +} + /* (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); @@ -6191,7 +6365,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { (size_t)n_out_max * (3 * sizeof(int64_t) + 2 * sizeof(ray_t*)) + (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*) + sizeof(int64_t) + sizeof(uint16_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)); if (!nonagg_names) { scratch_free(dep_src_hdr); @@ -6208,7 +6382,8 @@ ray_t* ray_select(ray_t** args, int64_t n) { ray_op_t** agg_ins = key_ops + nk_max; ray_op_t** agg_ins2 = agg_ins + aggs_max; int64_t* agg_k = (int64_t*)(agg_ins2 + aggs_max); - dep_key_names = agg_k + aggs_max; /* [n_dep_keys] */ + 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); /* Copy the bridged dependent-key names/biases into this block, then release @@ -8218,7 +8393,7 @@ 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 (is_group_dag_agg_expr(expr)) { + if (is_group_dag_agg_expr_dag_safe(expr, tbl)) { /* dag-aggs claim output slots in order. Not a flat * forcer. */ n_grp_agg_outputs++; @@ -8460,7 +8635,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { if (kid == from_id || kid == where_id || kid == by_id || kid == take_id || kid == asc_id || kid == desc_id) continue; ray_t* val_expr = dict_elems[i + 1]; - if (is_group_dag_agg_expr(val_expr)) { + if (is_group_dag_agg_expr_dag_safe(val_expr, tbl)) { ray_t** agg_elems = (ray_t**)ray_data(val_expr); uint16_t op = resolve_agg_opcode(agg_elems[0]->i64); ray_t* agg_arg = agg_elems[1]; @@ -8479,6 +8654,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { /* 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_names[n_aggs] = kid; /* Canonical aggregand type-admission (matches the scalar * builtins): reject non-numeric / absolute-temporal inputs so a * by-group sum/avg/var never silently folds symbol ids etc. */ @@ -9285,6 +9461,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { uint16_t* s_agg_ops = (uint16_t*)(s_agg_ins2 + s_max); int64_t s_n_aggs = 0; int s_has_binary = 0; + int s_use_eval_fallback = 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 || @@ -9296,13 +9473,8 @@ ray_t* ray_select(ray_t** args, int64_t n) { s_agg_ins[s_n_aggs] = compile_expr_dag(g, agg_elems[1]); s_agg_ins2[s_n_aggs] = NULL; if (!s_agg_ins[s_n_aggs]) { - if (g->selection) { - ray_release(g->selection); - g->selection = NULL; - } - ray_graph_free(g); ray_release(tbl); - scratch_free(sagg_hdr); - scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select: failed to compile aggregation argument"); + s_use_eval_fallback = 1; + break; } /* Canonical aggregand type-admission (same table as the scalar * builtins): reject non-numeric (SYM/STR/GUID) and, for sum, @@ -9325,10 +9497,8 @@ ray_t* ray_select(ray_t** args, int64_t n) { } s_agg_ins2[s_n_aggs] = compile_expr_dag(g, agg_elems[2]); if (!s_agg_ins2[s_n_aggs]) { - if (g->selection) { ray_release(g->selection); g->selection = NULL; } - ray_graph_free(g); ray_release(tbl); - scratch_free(sagg_hdr); - scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select: failed to compile binary aggregation second argument"); + s_use_eval_fallback = 1; + break; } if (s_agg_ins2[s_n_aggs]->out_type > 0 && !agg_type_admitted(op, s_agg_ins2[s_n_aggs]->out_type)) { @@ -9342,6 +9512,29 @@ ray_t* ray_select(ray_t** args, int64_t n) { } s_n_aggs++; } + if (s_use_eval_fallback) { + ray_t* eval_tbl = tbl; + int release_eval_tbl = 0; + if (g->selection) { + eval_tbl = sel_compact(g, tbl, g->selection, NULL, 0); + if (!eval_tbl || RAY_IS_ERR(eval_tbl)) { + if (g->selection) { ray_release(g->selection); g->selection = NULL; } + ray_graph_free(g); ray_release(tbl); + scratch_free(sagg_hdr); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return eval_tbl ? eval_tbl : ray_error("oom", NULL); + } + release_eval_tbl = 1; + } + ray_t* result = eval_scalar_agg_outputs(dict_elems, dict_n, eval_tbl, + from_id, where_id, by_id, + take_id, asc_id, desc_id, + nearest_id); + if (release_eval_tbl) ray_release(eval_tbl); + if (g->selection) { ray_release(g->selection); g->selection = NULL; } + ray_graph_free(g); ray_release(tbl); + scratch_free(sagg_hdr); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; + } if (s_has_binary) root = ray_group_build(g, NULL, 0, s_agg_ops, s_agg_ins, s_agg_ins2, NULL, s_n_aggs); @@ -9722,23 +9915,9 @@ ray_t* ray_select(ray_t** args, int64_t n) { ray_table_set_col_name(result, k, aliases[k]); } /* Rename only the agg columns (positions after keys). - * Non-agg LIST columns were named at scatter time. */ - ray_t* aun_hdr = NULL; - int64_t* agg_user_names = (int64_t*)scratch_alloc(&aun_hdr, - (size_t)n_out_max * sizeof(int64_t)); - int64_t n_agg_user = 0; - if (agg_user_names) { - 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) continue; - if (!is_group_dag_agg_expr(dict_elems[i + 1])) continue; - if (n_agg_user < n_out_max) agg_user_names[n_agg_user++] = kid; - } - for (int64_t j = 0; j < n_agg_user && n_key_cols + j < ncols; j++) - ray_table_set_col_name(result, n_key_cols + j, agg_user_names[j]); - } - scratch_free(aun_hdr); + * Non-agg/fallback columns are named at scatter time. */ + for (int64_t j = 0; j < n_aggs_real && n_key_cols + j < ncols; j++) + ray_table_set_col_name(result, n_key_cols + j, agg_names[j]); } else { /* Projection-only: columns are in dict order. Rename each * output column directly — a projection may have any number diff --git a/test/rfl/arith/mul.rfl b/test/rfl/arith/mul.rfl index 976e0c439..057bf2137 100644 --- a/test/rfl/arith/mul.rfl +++ b/test/rfl/arith/mul.rfl @@ -110,6 +110,12 @@ (type (* 3 (as 'TIME 1000))) -- 'time (* (as 'TIME 1000) 3) -- 00:00:03.000 (type (* (as 'TIME 1000) 3)) -- 'time +;; TIME scaling only admits integer factors; float factors used to read raw +;; F64 union bits as i64 and trip signed-overflow UBSan. +(* (as 'TIME 1000) 1.5) !- type +(* 1.5 (as 'TIME 1000)) !- type +(* (as 'TIME [1000 2000]) 1.5) !- type +(* (as 'TIME 1000) 0Nf) !- type ;; null-int * TIME → null TIME (line 174 path) (nil? (* 0Ni (as 'TIME 1000))) -- true diff --git a/test/rfl/arith/sub.rfl b/test/rfl/arith/sub.rfl index 3fae52fb9..58608b1b5 100644 --- a/test/rfl/arith/sub.rfl +++ b/test/rfl/arith/sub.rfl @@ -115,6 +115,12 @@ (- (as 'DATE 7305) (as 'I32 30)) -- 2019.12.02 ;; DATE - I16 (- (as 'DATE 7305) (as 'I16 5)) -- 2019.12.27 +;; DATE/TIME/TIMESTAMP offsets must be integer typed; float offsets are type errors. +(- (as 'DATE 7305) 1.5) !- type +(- (as 'TIME 5000) 1.5) !- type +(- (as 'TIMESTAMP 5000) 1.5) !- type +(- (as 'DATE [7305 7306]) 1.5) !- type +(- (as 'DATE 7305) 0Nf) !- type ;; DATE - DATE → I32 (days) (- (as 'DATE 7310) (as 'DATE 7305)) -- 5 diff --git a/test/rfl/expr/const_expr.rfl b/test/rfl/expr/const_expr.rfl index 033d4f8a0..1e45c1846 100644 --- a/test/rfl/expr/const_expr.rfl +++ b/test/rfl/expr/const_expr.rfl @@ -99,26 +99,14 @@ (select {s: (sum (+ x 3.5)) from: Tce}) -- (table [s] (list [32.5])) ;; =================================================================== -;; DATE constant in arithmetic → atom_to_numeric called with -RAY_DATE -;; type (line 38: case -RAY_DATE → Branch(39:9) True). -;; 2024.01.01 represents 8766 days; sum(x * 8766) = 15 * 8766 = 131490 -;; =================================================================== -(select {s: (sum (* x 2024.01.01)) from: Tce}) -- (table [s] (list [131490])) - -;; =================================================================== -;; TIME constant in arithmetic → atom_to_numeric with -RAY_TIME -;; (line 39: case -RAY_TIME → Branch(40:9) True). -;; 12:00:00 = 43200000ms; sum(x * 43200000) = 15 * 43200000 = 648000000 -;; =================================================================== -(select {s: (sum (* x 12:00:00)) from: Tce}) -- (table [s] (list [648000000])) - -;; =================================================================== -;; TIMESTAMP constant in arithmetic → atom_to_numeric with -RAY_TIMESTAMP -;; (line 40: case -RAY_TIMESTAMP → Branch(40:9) True). -;; 2000.01.01D00:00:00.000000001 = 1 nanosecond since epoch. -;; sum(x * 1) = 1+2+3+4+5 = 15 -;; =================================================================== -(select {s: (sum (* x 2000.01.01D00:00:00.000000001)) from: Tce}) -- (table [s] (list [15])) +;; Temporal constants in arithmetic must follow builtin temporal rules. +;; The query DAG used to demote them to raw integers; the eval fallback now +;; preserves builtin results for valid pairs and type errors for invalid pairs. +;; =================================================================== +(select {s: (sum (* x 2024.01.01)) from: Tce}) !- type +(type (at (select {s: (sum (* x 12:00:00)) from: Tce}) 's)) -- 'TIME +(as 'I32 (at (at (select {s: (sum (* x 12:00:00)) from: Tce}) 's) 0)) -- 648000000i +(select {s: (sum (* x 2000.01.01D00:00:00.000000001)) from: Tce}) !- type ;; =================================================================== ;; F64 NEG constant → eval_const_numeric_expr NEG/ABS branch (line 83:25) diff --git a/test/rfl/expr/narrow_binary.rfl b/test/rfl/expr/narrow_binary.rfl index 8f66b2dfa..c9280abf5 100644 --- a/test/rfl/expr/narrow_binary.rfl +++ b/test/rfl/expr/narrow_binary.rfl @@ -168,17 +168,15 @@ (set _Tu8 (table [x] (list (as 'U8 [4 5 6])))) (at (select {y: (* x 2.0) from: _Tu8}) 'y) -- [8.0 10.0 12.0] -;; TIMESTAMP column → F64 scratch (line 625-628 I64/TIMESTAMP path) +;; Temporal columns route to eval fallback so builtin temporal rules are preserved. (set _Tts (table [x] (list (as 'TIMESTAMP [1000 2000 3000])))) -(at (select {y: (* x 2.0) from: _Tts}) 'y) -- [2000.0 4000.0 6000.0] +(select {y: (* x 2.0) from: _Tts}) !- type -;; DATE column → F64 scratch (line 633: DATE/TIME path via I32) (set _Td (table [x] (list (as 'DATE [0 1 2])))) -(at (select {y: (* x 2.0) from: _Td}) 'y) -- [0.0 2.0 4.0] +(select {y: (* x 2.0) from: _Td}) !- type -;; TIME column → F64 scratch (set _Tt (table [x] (list (as 'TIME [100 200 300])))) -(at (select {y: (* x 2.0) from: _Tt}) 'y) -- [200.0 400.0 600.0] +(select {y: (* x 2.0) from: _Tt}) !- type ;; BOOL column → F64 scratch (line 637-640 U8/BOOL path) (set _Tb (table [x] (list (as 'BOOL [true false true])))) diff --git a/test/rfl/integration/dag_binary_ops.rfl b/test/rfl/integration/dag_binary_ops.rfl index e4ae2725a..70ebec88e 100644 --- a/test/rfl/integration/dag_binary_ops.rfl +++ b/test/rfl/integration/dag_binary_ops.rfl @@ -71,6 +71,34 @@ (at (select {x: (<= a b) from: Tc}) 'x) -- [true true true false false] (sum (as 'I64 (at (select {x: (<= a b) from: Tc}) 'x))) -- 3 +;; ────────────── temporal arithmetic routes to eval fallback ────────────── +;; The generic DAG treats temporal values as raw integers, which demotes +;; special temporal semantics. Projection fallback must preserve the builtin +;; rules instead: valid pairs keep their temporal/difference types, invalid +;; pairs surface type errors. +(set Ttm (table [d1 d2 t1 t2 p1 p2] (list (as 'DATE [10 20]) (as 'DATE [20 30]) (as 'TIME [1000 2000]) (as 'TIME [2000 3000]) (as 'TIMESTAMP [1000 2000]) (as 'TIMESTAMP [2000 3000])))) +(type (at (select {x: (+ d1 2) from: Ttm}) 'x)) -- 'DATE +(at (select {x: (+ t1 t2) from: Ttm}) 'x) -- [00:00:03.000 00:00:05.000] +(type (at (select {x: (- d2 d1) from: Ttm}) 'x)) -- 'I32 +(at (select {x: (- d2 d1) from: Ttm}) 'x) -- [10 10] +(type (at (select {x: (* t1 2) from: Ttm}) 'x)) -- 'TIME +(select {x: (+ d1 d2) from: Ttm}) !- type +(select {x: (+ p1 p2) from: Ttm}) !- type +(select {x: (- d1 1.5) from: Ttm}) !- type +(select {x: (* t1 1.5) from: Ttm}) !- type + +;; Grouped aggregations use the same temporal fallback instead of failing +;; compile or renaming mixed fallback/DAG outputs incorrectly. +(set Ttmg (table [k d1 d2 t1 v] (list [a a b b] [2024.01.01 2024.01.02 2024.01.03 2024.01.04] [2024.01.11 2024.01.12 2024.01.13 2024.01.14] [00:00:01.000 00:00:02.000 00:00:03.000 00:00:04.000] [1 2 3 4]))) +(set Gspan (select {span: (avg (- d2 d1)) from: Ttmg by: k})) +(at Gspan 'span) -- [10.0 10.0] +(set Gtime (select {total: (sum (* t1 2)) from: Ttmg by: k})) +(type (at Gtime 'total)) -- 'TIME +(as 'I32 (at Gtime 'total)) -- [6000 14000] +(set Gmix (select {span: (avg (- d2 d1)) qty: (sum v) from: Ttmg by: k})) +(at Gmix 'span) -- [10.0 10.0] +(at Gmix 'qty) -- [3 7] + ;; ────────────── compound where: AND / OR with derived comparisons ────────────── (set Tw (table [a b] (list [1 2 3 4 5 6 7 8] [10 20 30 40 50 60 70 80]))) (at (select {from: Tw where: (and (> a 2) (< b 60))}) 'a) -- [3 4 5] diff --git a/test/test_exec.c b/test/test_exec.c index 7133a2a65..199e2e6cb 100644 --- a/test/test_exec.c +++ b/test/test_exec.c @@ -26,6 +26,7 @@ #include #include "mem/heap.h" #include "ops/ops.h" +#include "ops/internal.h" #include "lang/eval.h" #include "table/sym.h" #include "core/profile.h" @@ -17344,6 +17345,146 @@ static test_result_t test_exec_prod_sel_compact(void) { PASS(); } +/* ====================================================================== + * LIST columns through the filter kernels (issue #355 follow-up) + * + * A LIST cell is a ray_t* — the byte-copy gather kernels must never see + * one (aliasing without a retain double-frees on release), and + * typed_vec_new rejects RAY_LIST (type 0), which used to silently DROP + * the column from the result. + * ====================================================================== */ + +/* Build an n-row table [x: i64 0..n-1, brk: LIST cycling [10] / [20 30]]. */ +static ray_t* make_list_col_table(int64_t n) { + ray_t* xs = ray_vec_new(RAY_I64, n); + xs->len = n; + int64_t* xd = (int64_t*)ray_data(xs); + for (int64_t i = 0; i < n; i++) xd[i] = i; + + int64_t a_raw[] = {10}; + int64_t b_raw[] = {20, 30}; + ray_t* a = ray_vec_from_raw(RAY_I64, a_raw, 1); + ray_t* b = ray_vec_from_raw(RAY_I64, b_raw, 2); + ray_t* brk = ray_list_new(n); + for (int64_t i = 0; i < n; i++) + brk = ray_list_append(brk, (i & 1) ? b : a); + ray_release(a); + ray_release(b); + + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("x", 1), xs); + tbl = ray_table_add_col(tbl, ray_sym_intern("brk", 3), brk); + ray_release(xs); + ray_release(brk); + return tbl; +} + +/* All-rows BOOL predicate with the first `pass` elements set. */ +static ray_t* make_prefix_pred(int64_t n, int64_t pass) { + ray_t* pred = ray_vec_new(RAY_BOOL, n); + pred->len = n; + uint8_t* pd = (uint8_t*)ray_data(pred); + for (int64_t i = 0; i < n; i++) pd[i] = i < pass; + return pred; +} + +/* exec_filter parallel gather (> RAY_PARALLEL_THRESHOLD rows) must keep + * the LIST column and retain its elements — it used to silently drop it + * (typed_vec_new rejects type 0 → new_cols[c] = NULL). */ +static test_result_t test_exec_filter_par_list_col(void) { + ray_heap_init(); + (void)ray_sym_init(); + + int64_t n = RAY_PARALLEL_THRESHOLD + 4096; + ray_t* tbl = make_list_col_table(n); + ray_t* pred = make_prefix_pred(n, 10); + + ray_t* out = exec_filter(NULL, NULL, tbl, pred); + TEST_ASSERT_NOT_NULL(out); + TEST_ASSERT_FALSE(RAY_IS_ERR(out)); + TEST_ASSERT_EQ_I(ray_table_ncols(out), 2); + TEST_ASSERT_EQ_I(ray_table_nrows(out), 10); + ray_t* brk = ray_table_get_col(out, ray_sym_intern("brk", 3)); + TEST_ASSERT_NOT_NULL(brk); + TEST_ASSERT_EQ_I(brk->type, RAY_LIST); + TEST_ASSERT_EQ_I(brk->len, 10); + ray_t** be = (ray_t**)ray_data(brk); + TEST_ASSERT_EQ_I(be[0]->len, 1); /* row 0 → [10] */ + TEST_ASSERT_EQ_I(be[1]->len, 2); /* row 1 → [20 30] */ + TEST_ASSERT_EQ_I(((int64_t*)ray_data(be[1]))[1], 30); + + /* Release the result BEFORE the source: an unretained aliasing gather + * would leave the table's elements freed (ASan double-free). */ + ray_release(out); + ray_release(pred); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* exec_filter_head must keep LIST columns too (same silent-drop shape). */ +static test_result_t test_exec_filter_head_list_col(void) { + ray_heap_init(); + (void)ray_sym_init(); + + ray_t* tbl = make_list_col_table(6); + ray_t* pred = make_prefix_pred(6, 6); /* all pass; limit trims */ + + ray_t* out = exec_filter_head(tbl, pred, 3); + TEST_ASSERT_NOT_NULL(out); + TEST_ASSERT_FALSE(RAY_IS_ERR(out)); + TEST_ASSERT_EQ_I(ray_table_ncols(out), 2); + TEST_ASSERT_EQ_I(ray_table_nrows(out), 3); + ray_t* brk = ray_table_get_col(out, ray_sym_intern("brk", 3)); + TEST_ASSERT_NOT_NULL(brk); + TEST_ASSERT_EQ_I(brk->type, RAY_LIST); + TEST_ASSERT_EQ_I(brk->len, 3); + ray_t** be = (ray_t**)ray_data(brk); + TEST_ASSERT_EQ_I(be[1]->len, 2); /* row 1 → [20 30] */ + + ray_release(out); + ray_release(pred); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* Filtering a standalone LIST vector (OP_FILTER over a scanned LIST + * column → exec_filter_vec) must gather elements with a retain — it used + * to reject with "type" via col_vec_new. */ +static test_result_t test_exec_filter_vec_list(void) { + ray_heap_init(); + (void)ray_sym_init(); + + ray_t* tbl = make_list_col_table(6); + + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* brk = ray_scan(g, "brk"); + ray_op_t* x = ray_scan(g, "x"); + ray_op_t* thresh = ray_const_i64(g, 3); + ray_op_t* pred = ray_lt(g, x, thresh); + ray_op_t* filt = ray_filter(g, brk, pred); + + ray_t* result = ray_execute(g, filt); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(result->type, RAY_LIST); + TEST_ASSERT_EQ_I(result->len, 3); + ray_t** re = (ray_t**)ray_data(result); + TEST_ASSERT_EQ_I(re[0]->len, 1); /* [10] */ + TEST_ASSERT_EQ_I(re[1]->len, 2); /* [20 30] */ + TEST_ASSERT_EQ_I(((int64_t*)ray_data(re[1]))[0], 20); + + ray_release(result); + ray_graph_free(g); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + /* ====================================================================== * Suite * ====================================================================== */ @@ -17626,5 +17767,8 @@ const test_entry_t exec_entries[] = { { "exec/var_pop", test_exec_var_pop, NULL, NULL }, { "exec/prod_f64", test_exec_prod_f64, NULL, NULL }, { "exec/prod_sel_compact", test_exec_prod_sel_compact, NULL, NULL }, + { "exec/filter_par_list_col", test_exec_filter_par_list_col, NULL, NULL }, + { "exec/filter_head_list_col", test_exec_filter_head_list_col, NULL, NULL }, + { "exec/filter_vec_list", test_exec_filter_vec_list, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_lang.c b/test/test_lang.c index 5b8856373..3247ae100 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -4231,6 +4231,78 @@ static test_result_t test_eval_insert_parted_physical_types(void) { return result; } +/* ---- Test: nested (LIST) column through a parted view ------------------ */ + +/* Two disk partitions, each with a LIST column whose rows are i64 vectors + * of different lengths (issue #355). */ +static bool lang_parted_list_fixture(const char* root) { + char day1[1024], day2[1024], sym_path[1024]; + int n1 = snprintf(day1, sizeof(day1), "%s/2024.01.01/trades", root); + int n2 = snprintf(day2, sizeof(day2), "%s/2024.01.02/trades", root); + int ns = snprintf(sym_path, sizeof(sym_path), "%s/.sym", root); + if (n1 <= 0 || (size_t)n1 >= sizeof(day1) || + n2 <= 0 || (size_t)n2 >= sizeof(day2) || + ns <= 0 || (size_t)ns >= sizeof(sym_path)) + return false; + + const char* src = + "(table ['acct 'brk] " + " (list ['a 'b] (list [0 250000] [0 250000 5000000])))"; + return lang_parted_insert_save_table(src, day1, sym_path) && + lang_parted_insert_save_table(src, day2, sym_path); +} + +static test_result_t test_eval_parted_list_column_impl(const char* root) { + TEST_ASSERT(lang_parted_list_fixture(root), "create parted LIST fixture"); + + char src[1400]; + int n = snprintf(src, sizeof(src), + "(set pl (.db.parted.get \"%s\" 'trades))", root); + TEST_ASSERT(n > 0 && (size_t)n < sizeof(src), "format parted get"); + ray_t* setup = ray_eval_str(src); + TEST_ASSERT_NOT_NULL(setup); + TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); + ray_release(setup); + + /* Flatten via `at`: all four rows, in partition order. */ + ASSERT_EQ("(at pl 'brk)", + "(list [0 250000] [0 250000 5000000] " + " [0 250000] [0 250000 5000000])"); + + /* Flatten via unfiltered select. */ + ASSERT_EQ("(at (select {c: brk from: pl}) 'c)", + "(list [0 250000] [0 250000 5000000] " + " [0 250000] [0 250000 5000000])"); + + /* Filtered select gathers matching rows with correct contents. */ + ASSERT_EQ("(at (select {c: brk from: pl where: (== acct 'b)}) 'c)", + "(list [0 250000 5000000] [0 250000 5000000])"); + + /* Run the filtered select twice, releasing the first result in between + * (ASSERT_EQ releases it): the gather must retain the elements it + * copies out of the segments, or the second pass walks freed memory + * (double-free / use-after-free, issue #355). */ + ASSERT_EQ("(count (select {c: brk from: pl where: (== acct 'b)}))", "2"); + ASSERT_EQ("(count (select {c: brk from: pl where: (== acct 'b)}))", "2"); + + /* The parted view itself must stay usable after the reads. */ + ASSERT_EQ("(at pl 'acct)", "['a 'b 'a 'b]"); + PASS(); +} + +static test_result_t test_eval_parted_list_column(void) { + char root[512]; + int n = snprintf(root, sizeof(root), + "/tmp/rayforce_lang_parted_list_col_%ld", + (long)getpid()); + if (n <= 0 || (size_t)n >= sizeof(root)) + return (test_result_t){ TEST_FAIL, "parted fixture path overflow" }; + lang_parted_insert_rm_rf(root); + test_result_t result = test_eval_parted_list_column_impl(root); + lang_parted_insert_rm_rf(root); + return result; +} + /* ---- Test: upsert (update existing row) ---- */ static test_result_t test_eval_upsert(void) { /* Upsert by 'name key — row with name=2 exists, update it */ @@ -8639,6 +8711,7 @@ const test_entry_t lang_entries[] = { { "lang/eval/insert_parted_errors", test_eval_insert_parted_errors, lang_setup, lang_teardown }, { "lang/eval/insert_parted_key_types", test_eval_insert_parted_key_types, lang_setup, lang_teardown }, { "lang/eval/insert_parted_physical_types", test_eval_insert_parted_physical_types, lang_setup, lang_teardown }, + { "lang/eval/parted_list_column", test_eval_parted_list_column, lang_setup, lang_teardown }, { "lang/eval/upsert", test_eval_upsert, lang_setup, lang_teardown }, { "lang/eval/upsert_f64_key", test_eval_upsert_f64_key, lang_setup, lang_teardown }, { "lang/eval/upsert_str_key", test_eval_upsert_str_key, lang_setup, lang_teardown },