diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e6c09c1d0..1d0878f41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,6 +89,10 @@ jobs: # work-stealing ring real contention to race against. Linux + clang only. tsan: runs-on: ubuntu-latest + env: + # Keep Clang off transient hosted-runner ISA features that become + # -Werror diagnostics before the TSan suites can run. + RAY_MARCH: x86-64 steps: - uses: actions/checkout@v4 - name: TSan concurrency suites diff --git a/src/app/repl.c b/src/app/repl.c index daa223ad2..32e5e65a7 100644 --- a/src/app/repl.c +++ b/src/app/repl.c @@ -147,6 +147,10 @@ static void render_progress_full(int64_t done, int64_t total, if (total > 0) { pct = (double)done / (double)total; if (pct > 1.0) pct = 1.0; + /* A dispatch can finish before its enclosing query's cleanup and + * finalization phases. Reserve 100% for the final snapshot (which + * clears the line) so the live bar never claims completion early. */ + if (pct >= 1.0) pct = 0.99; int sub = (int)(pct * sub_total); full = sub / 8; frac = sub % 8; diff --git a/src/io/csv.c b/src/io/csv.c index 0c4e9277a..18f49a461 100644 --- a/src/io/csv.c +++ b/src/io/csv.c @@ -43,6 +43,7 @@ #include "core/numparse.h" #include "core/pool.h" #include "core/platform.h" /* ray_vm_map_fd_ro / ray_vm_unmap_file (tracked) */ +#include "core/qstats.h" /* suppress progress for internal finalize tasks */ #include "lang/format.h" #include "ops/hash.h" #include "ops/idxop.h" /* attach per-chunk zone index after load */ @@ -719,6 +720,12 @@ static int64_t build_row_offsets(const char* buf, size_t buf_size, * Only scans for \n; pure \r line endings (old Mac) treated as single row. * Empty lines are preserved as rows (for NULL handling). */ for (;;) { + if (RAY_UNLIKELY((n & 0xFFFF) == 0 && ray_interrupted())) { + scratch_free(hdr); + *offsets_out = NULL; + *hdr_out = NULL; + return -1; + } const char* nl = (const char*)memchr(p, '\n', (size_t)(end - p)); if (!nl) break; p = nl + 1; @@ -739,7 +746,17 @@ static int64_t build_row_offsets(const char* buf, size_t buf_size, /* Slow path: track quote parity, byte-by-byte. * Empty lines preserved as rows (for NULL handling). */ bool in_quote = false; + size_t checked = 0; while (p < end) { + if (RAY_UNLIKELY(++checked == 65536)) { + checked = 0; + if (ray_interrupted()) { + scratch_free(hdr); + *offsets_out = NULL; + *hdr_out = NULL; + return -1; + } + } char c = *p; if (c == '"') { in_quote = !in_quote; @@ -795,6 +812,10 @@ static int64_t build_row_offsets_limited(const char* buf, size_t buf_size, if (RAY_LIKELY(!data_has_quotes)) { for (;;) { + if (RAY_UNLIKELY((n & 0xFFFF) == 0 && ray_interrupted())) { + scratch_free(hdr); + return -1; + } const char* nl = (const char*)memchr(p, '\n', (size_t)(end - p)); if (!nl) { p = end; @@ -820,7 +841,15 @@ static int64_t build_row_offsets_limited(const char* buf, size_t buf_size, } } else { bool in_quote = false; + size_t checked = 0; while (p < end) { + if (RAY_UNLIKELY(++checked == 65536)) { + checked = 0; + if (ray_interrupted()) { + scratch_free(hdr); + return -1; + } + } char c = *p; if (c == '"') { in_quote = !in_quote; @@ -898,6 +927,8 @@ static bool csv_intern_strings(csv_strref_t** str_refs, int n_cols, return false; /* OOM: cannot grow sym table */ for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) + return false; if (refs[r].ptr == NULL) { /* Empty/missing field → sym 0 (the canonical empty * symbol). SYM columns are no-null by design. */ @@ -920,11 +951,15 @@ static bool csv_intern_strings(csv_strref_t** str_refs, int n_cols, static void csv_free_escaped_strrefs(csv_strref_t** str_refs, int n_cols, const csv_type_t* col_types, int64_t n_rows, - const char* buf, size_t buf_size) { + const char* buf, size_t buf_size, + const uint8_t* row_done, + const bool* col_had_escaped) { const char* buf_end = buf + buf_size; for (int c = 0; c < n_cols; c++) { if (col_types[c] != CSV_TYPE_STR || !str_refs[c]) continue; + if (col_had_escaped && !col_had_escaped[c]) continue; for (int64_t r = 0; r < n_rows; r++) { + if (row_done && !row_done[r]) continue; const char* p = str_refs[c][r].ptr; if (p && (p < buf || p >= buf_end)) ray_sys_free((void*)p); @@ -949,6 +984,8 @@ static bool csv_fill_str_cols(csv_strref_t** str_refs, int n_cols, * wouldn't fit in the u32 offset field. */ uint64_t pool_bytes = 0; for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) + return false; if (refs[r].ptr == NULL) continue; uint32_t l = refs[r].len; if (l > RAY_STR_INLINE_MAX) pool_bytes += l; @@ -967,6 +1004,8 @@ static bool csv_fill_str_cols(csv_strref_t** str_refs, int n_cols, uint32_t pool_off = 0; for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) + return false; memset(&dst[r], 0, sizeof(ray_str_t)); if (refs[r].ptr == NULL) continue; const char* p = refs[r].ptr; @@ -1037,6 +1076,8 @@ typedef struct { void** col_data; /* non-const: workers write parsed values into columns */ csv_strref_t** str_refs; /* [n_cols] — strref arrays for string columns, NULL for others */ bool* worker_had_null; /* [n_workers * n_cols] */ + bool* worker_had_escaped; /* [n_workers * n_cols] */ + uint8_t* row_done; /* [n_rows], marks initialized strref rows */ } csv_par_ctx_t; static void csv_parse_fn(void* arg, uint32_t worker_id, @@ -1045,8 +1086,11 @@ static void csv_parse_fn(void* arg, uint32_t worker_id, char esc_buf[8192]; const char* buf_end = ctx->buf + ctx->buf_size; bool* my_had_null = &ctx->worker_had_null[(size_t)worker_id * (size_t)ctx->n_cols]; + bool* my_had_escaped = &ctx->worker_had_escaped[(size_t)worker_id * (size_t)ctx->n_cols]; for (int64_t row = start; row < end_row; row++) { + if (RAY_UNLIKELY(((row - start) & 1023) == 0 && ray_interrupted())) + return; const char* p = ctx->buf + ctx->row_offsets[row]; const char* row_end = (row + 1 < ctx->n_rows) ? ctx->buf + ctx->row_offsets[row + 1] @@ -1188,6 +1232,7 @@ static void csv_parse_fn(void* arg, uint32_t worker_id, * (freed below) — both die before csv_fill_str_cols * reads the strref. Persist escaped fields. */ if (fld < ctx->buf || fld >= buf_end) { + my_had_escaped[c] = true; if (dyn_esc && fld == dyn_esc) { dyn_esc = NULL; /* transfer ownership */ } else { @@ -1205,6 +1250,7 @@ static void csv_parse_fn(void* arg, uint32_t worker_id, } if (RAY_UNLIKELY(dyn_esc != NULL)) ray_sys_free(dyn_esc); } + if (ctx->row_done) ctx->row_done[row] = 1; } } @@ -1212,18 +1258,22 @@ static void csv_parse_fn(void* arg, uint32_t worker_id, * Serial parse fallback (small files or no thread pool) * -------------------------------------------------------------------------- */ -static void csv_parse_serial(const char* buf, size_t buf_size, +static bool csv_parse_serial(const char* buf, size_t buf_size, const int64_t* row_offsets, int64_t n_rows, int n_cols, char delim, const csv_type_t* col_types, const int8_t* resolved_types, void** col_data, csv_strref_t** str_refs, - bool* col_had_null) { + bool* col_had_null, + bool* col_had_escaped, + uint8_t* row_done) { char esc_buf[8192]; const char* buf_end = buf + buf_size; for (int64_t row = 0; row < n_rows; row++) { + if (RAY_UNLIKELY((row & 1023) == 0 && ray_interrupted())) + return false; const char* p = buf + row_offsets[row]; const char* row_end = (row + 1 < n_rows) ? buf + row_offsets[row + 1] @@ -1363,6 +1413,7 @@ static void csv_parse_serial(const char* buf, size_t buf_size, * (freed below) — both die before csv_fill_str_cols * reads the strref. Persist escaped fields. */ if (fld < buf || fld >= buf_end) { + col_had_escaped[c] = true; if (dyn_esc && fld == dyn_esc) { dyn_esc = NULL; /* transfer ownership */ } else { @@ -1380,7 +1431,9 @@ static void csv_parse_serial(const char* buf, size_t buf_size, } if (RAY_UNLIKELY(dyn_esc != NULL)) ray_sys_free(dyn_esc); } + if (row_done) row_done[row] = 1; } + return true; } /* Per-column elem size for the hash-attach cap. Mirrors the integer @@ -1520,7 +1573,7 @@ static int8_t csv_auto_width_to_ray(csv_type_t w) { /* Accumulate per-column min/max/has_null over a block of rows for the columns * flagged RAY_CSV_AUTO_TAG in resolved_types; non-AUTO columns are skipped. * Mirrors the field-walk (and short-row null handling) of csv_parse_serial. */ -static void csv_auto_scan_rows(const char* buf, const char* buf_end, +static bool csv_auto_scan_rows(const char* buf, const char* buf_end, const int64_t* row_offsets, int64_t n_rows, int ncols, char delim, const int8_t* resolved_types, @@ -1528,6 +1581,8 @@ static void csv_auto_scan_rows(const char* buf, const char* buf_end, bool* col_had_null) { char esc_buf[8192]; for (int64_t row = 0; row < n_rows; row++) { + if (RAY_UNLIKELY((row & 1023) == 0 && ray_interrupted())) + return false; const char* p = buf + row_offsets[row]; const char* row_end = (row + 1 < n_rows) ? buf + row_offsets[row + 1] : buf_end; @@ -1557,44 +1612,48 @@ static void csv_auto_scan_rows(const char* buf, const char* buf_end, if (RAY_UNLIKELY(dyn_esc != NULL)) ray_sys_free(dyn_esc); } } + return true; } /* Resolve every RAY_CSV_AUTO_TAG column in resolved_types[] to a concrete * width using a stats scan over the already-built whole-file row_offsets. * No-op when the schema carries no `INT` column. */ -static void csv_resolve_auto_in_place(const char* buf, size_t file_size, +static bool csv_resolve_auto_in_place(const char* buf, size_t file_size, const int64_t* row_offsets, int64_t n_rows, int ncols, char delim, int8_t* resolved_types) { bool any = false; for (int c = 0; c < ncols; c++) if (resolved_types[c] == RAY_CSV_AUTO_TAG) any = true; - if (!any) return; + if (!any) return true; int64_t col_min[CSV_MAX_COLS], col_max[CSV_MAX_COLS]; bool col_had_null[CSV_MAX_COLS]; for (int c = 0; c < ncols; c++) { col_min[c] = INT64_MAX; col_max[c] = INT64_MIN; col_had_null[c] = false; } - csv_auto_scan_rows(buf, buf + file_size, row_offsets, n_rows, ncols, delim, - resolved_types, col_min, col_max, col_had_null); + if (!csv_auto_scan_rows(buf, buf + file_size, row_offsets, n_rows, ncols, + delim, resolved_types, col_min, col_max, + col_had_null)) + return false; for (int c = 0; c < ncols; c++) if (resolved_types[c] == RAY_CSV_AUTO_TAG) resolved_types[c] = csv_auto_width_to_ray( csv_resolve_int_width(col_min[c], col_max[c], col_had_null[c])); + return true; } /* Same as csv_resolve_auto_in_place, but for the streaming writers which never * build whole-file offsets: stream the file in chunks accumulating stats, * then resolve. Bounded memory (one chunk of offsets at a time). */ -static void csv_resolve_auto_streamed(const char* buf, size_t file_size, +static bool csv_resolve_auto_streamed(const char* buf, size_t file_size, size_t data_offset, int ncols, char delim, bool data_has_quotes, int8_t* resolved_types) { bool any = false; for (int c = 0; c < ncols; c++) if (resolved_types[c] == RAY_CSV_AUTO_TAG) any = true; - if (!any) return; + if (!any) return true; int64_t col_min[CSV_MAX_COLS], col_max[CSV_MAX_COLS]; bool col_had_null[CSV_MAX_COLS]; @@ -1604,6 +1663,7 @@ static void csv_resolve_auto_streamed(const char* buf, size_t file_size, size_t off = data_offset; while (off < file_size) { + if (ray_interrupted()) return false; ray_t* hdr = NULL; int64_t* roff = NULL; size_t next = off; @@ -1611,10 +1671,13 @@ static void csv_resolve_auto_streamed(const char* buf, size_t file_size, CSV_PART_ROWS_DEFAULT, data_has_quotes, &roff, &hdr, &next); - if (cnt <= 0) { scratch_free(hdr); break; } - csv_auto_scan_rows(buf, buf + file_size, roff, cnt, ncols, delim, - resolved_types, col_min, col_max, col_had_null); + if (cnt < 0) { scratch_free(hdr); return false; } + if (cnt == 0) { scratch_free(hdr); break; } + bool scan_ok = csv_auto_scan_rows(buf, buf + file_size, roff, cnt, + ncols, delim, resolved_types, + col_min, col_max, col_had_null); scratch_free(hdr); + if (!scan_ok) return false; if (next <= off) break; off = next; } @@ -1623,6 +1686,7 @@ static void csv_resolve_auto_streamed(const char* buf, size_t file_size, if (resolved_types[c] == RAY_CSV_AUTO_TAG) resolved_types[c] = csv_auto_width_to_ray( csv_resolve_int_width(col_min[c], col_max[c], col_had_null[c])); + return true; } static ray_t* csv_materialize_rows(const char* buf, size_t file_size, @@ -1661,6 +1725,8 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, bool col_had_null[CSV_MAX_COLS]; if (ncols > 0) memset(col_had_null, 0, (size_t)ncols * sizeof(bool)); + bool col_had_escaped[CSV_MAX_COLS]; + memset(col_had_escaped, 0, sizeof(col_had_escaped)); csv_type_t parse_types[CSV_MAX_COLS]; for (int c = 0; c < ncols; c++) { @@ -1695,6 +1761,14 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, ray_t* str_ref_hdrs[CSV_MAX_COLS]; memset(str_ref_bufs, 0, sizeof(str_ref_bufs)); memset(str_ref_hdrs, 0, sizeof(str_ref_hdrs)); + ray_t* row_done_hdr = NULL; + uint8_t* row_done = has_text_cols + ? (uint8_t*)scratch_calloc(&row_done_hdr, (size_t)n_rows) + : NULL; + if (has_text_cols && !row_done) { + for (int c = 0; c < ncols; c++) ray_release(col_vecs[c]); + return NULL; + } for (int c = 0; c < ncols; c++) { if (parse_types[c] == CSV_TYPE_STR) { size_t sz = (size_t)n_rows * sizeof(csv_strref_t); @@ -1702,6 +1776,7 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, if (!str_ref_bufs[c]) { for (int j = 0; j < ncols; j++) ray_release(col_vecs[j]); for (int j = 0; j < c; j++) scratch_free(str_ref_hdrs[j]); + scratch_free(row_done_hdr); return NULL; } } @@ -1713,12 +1788,15 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, if (use_parallel) { uint32_t n_workers = ray_pool_total_workers(pool); - size_t whn_sz = (size_t)n_workers * (size_t)ncols * sizeof(bool); - bool* worker_had_null_buf = (bool*)ray_sys_alloc(whn_sz); - if (!worker_had_null_buf) { + size_t worker_flags_sz = (size_t)n_workers * (size_t)ncols * sizeof(bool); + bool* worker_flags = (bool*)ray_sys_alloc(worker_flags_sz * 2); + if (!worker_flags) { use_parallel = false; } else { - memset(worker_had_null_buf, 0, whn_sz); + memset(worker_flags, 0, worker_flags_sz * 2); + bool* worker_had_null_buf = worker_flags; + bool* worker_had_escaped_buf = worker_flags + + (size_t)n_workers * (size_t)ncols; csv_par_ctx_t ctx = { .buf = buf, @@ -1732,6 +1810,8 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, .col_data = col_data, .str_refs = str_ref_bufs, .worker_had_null = worker_had_null_buf, + .worker_had_escaped = worker_had_escaped_buf, + .row_done = row_done, }; ray_pool_dispatch(pool, csv_parse_fn, &ctx, n_rows); @@ -1740,19 +1820,31 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, for (int c = 0; c < ncols; c++) { if (worker_had_null_buf[(size_t)w * (size_t)ncols + (size_t)c]) col_had_null[c] = true; + if (worker_had_escaped_buf[(size_t)w * (size_t)ncols + (size_t)c]) + col_had_escaped[c] = true; } } - ray_sys_free(worker_had_null_buf); + ray_sys_free(worker_flags); } } if (!use_parallel) { - csv_parse_serial(buf, file_size, row_offsets, n_rows, - ncols, delimiter, parse_types, resolved_types, col_data, - str_ref_bufs, col_had_null); + (void)csv_parse_serial(buf, file_size, row_offsets, n_rows, + ncols, delimiter, parse_types, resolved_types, + col_data, str_ref_bufs, col_had_null, + col_had_escaped, row_done); } } + if (ray_interrupted()) { + csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, + buf, file_size, row_done, col_had_escaped); + for (int c = 0; c < ncols; c++) scratch_free(str_ref_hdrs[c]); + scratch_free(row_done_hdr); + for (int c = 0; c < ncols; c++) ray_release(col_vecs[c]); + return ray_error("cancel", "interrupted"); + } + if (has_text_cols) { csv_finalize_ctx_t fctx = { .str_refs = str_ref_bufs, @@ -1768,16 +1860,21 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, }; ray_pool_t* fpool = ray_pool_get(); if (fpool && ray_pool_total_workers(fpool) >= 2) { + uint32_t qmode = ray_qstats_mode(); + ray_qstats_set_mode(qmode & ~RAY_QS_PROGRESS); ray_pool_dispatch_n(fpool, csv_finalize_task, &fctx, 2); + ray_qstats_set_mode(qmode); } else { csv_finalize_task(&fctx, 0, 0, 1); csv_finalize_task(&fctx, 0, 1, 2); } - if (!fctx.fill_ok || !fctx.intern_ok) { - csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, buf, file_size); + if (!fctx.fill_ok || !fctx.intern_ok || ray_interrupted()) { + csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, + buf, file_size, row_done, col_had_escaped); for (int c = 0; c < ncols; c++) scratch_free(str_ref_hdrs[c]); + scratch_free(row_done_hdr); for (int c = 0; c < ncols; c++) ray_release(col_vecs[c]); - return NULL; + return ray_interrupted() ? ray_error("cancel", "interrupted") : NULL; } } @@ -1790,8 +1887,14 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, sym_max_ids[c] = max_id; } - csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, buf, file_size); + csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, + buf, file_size, NULL, col_had_escaped); for (int c = 0; c < ncols; c++) scratch_free(str_ref_hdrs[c]); + scratch_free(row_done_hdr); + if (ray_interrupted()) { + for (int c = 0; c < ncols; c++) ray_release(col_vecs[c]); + return ray_error("cancel", "interrupted"); + } for (int c = 0; c < ncols; c++) { ray_t* vec = col_vecs[c]; @@ -1815,10 +1918,24 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, void* dst = ray_data(narrow); if (new_w == RAY_SYM_W8) { uint8_t* d = (uint8_t*)dst; - for (int64_t r = 0; r < n_rows; r++) d[r] = (uint8_t)src[r]; + for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) { + ray_release(narrow); + for (int j = 0; j < ncols; j++) ray_release(col_vecs[j]); + return ray_error("cancel", "interrupted"); + } + d[r] = (uint8_t)src[r]; + } } else { uint16_t* d = (uint16_t*)dst; - for (int64_t r = 0; r < n_rows; r++) d[r] = (uint16_t)src[r]; + for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) { + ray_release(narrow); + for (int j = 0; j < ncols; j++) ray_release(col_vecs[j]); + return ray_error("cancel", "interrupted"); + } + d[r] = (uint16_t)src[r]; + } } narrow->attrs |= (col_vecs[c]->attrs & RAY_ATTR_HAS_NULLS); ray_release(col_vecs[c]); @@ -1837,14 +1954,26 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, * stays as well — it's the entropy signal we just measured). See * csv_should_attach_hash for the selectivity + memory cap. */ for (int c = 0; c < ncols; c++) { + if (ray_interrupted()) { + for (int j = 0; j < ncols; j++) ray_release(col_vecs[j]); + return ray_error("cancel", "interrupted"); + } ray_t* v = col_vecs[c]; if (!v || RAY_IS_ERR(v)) continue; if (v->len < (1 << 16)) continue; /* < one chunk, skip */ ray_t* r = ray_index_attach_chunk_zone(&v, 16); + if (ray_interrupted()) { + for (int j = 0; j < ncols; j++) ray_release(col_vecs[j]); + return ray_error("cancel", "interrupted"); + } if (r && !RAY_IS_ERR(r)) col_vecs[c] = v; /* attach succeeded */ /* On failure the original column stays in col_vecs[c]; ignore. */ } for (int c = 0; c < ncols; c++) { + if (ray_interrupted()) { + for (int j = 0; j < ncols; j++) ray_release(col_vecs[j]); + return ray_error("cancel", "interrupted"); + } ray_t* v = col_vecs[c]; if (!csv_should_attach_hash(v)) continue; /* ray_index_attach_hash drops any existing index on the @@ -1853,6 +1982,10 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, * is known to be high-entropy, chunk-skip never fires * anyway, so the chunk_zone is dead weight. */ ray_t* r = ray_index_attach_hash(&v); + if (ray_interrupted()) { + for (int j = 0; j < ncols; j++) ray_release(col_vecs[j]); + return ray_error("cancel", "interrupted"); + } if (r && !RAY_IS_ERR(r)) col_vecs[c] = v; } @@ -1905,6 +2038,8 @@ static const char* csv_skip_matching_header(const char* p, const char* buf_end, ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, const int8_t* col_types_in, int32_t n_types, const int64_t* col_names_in, int32_t n_names) { + if (ray_interrupted()) return ray_error("cancel", "interrupted"); + /* ---- 1. Open file and get size ---- */ int fd = open(path, O_RDONLY); if (fd < 0) return ray_error("io", NULL); @@ -1960,6 +2095,18 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, return ray_error("range", "csv read: header has too many columns, got %lld (max %d)", (long long)ncols, CSV_MAX_COLS); } + if (col_types_in && n_types != ncols) { + ray_vm_unmap_file(buf, file_size); + return ray_error("length", + "csv read: schema has %lld types but file has %d columns", + (long long)n_types, ncols); + } + if (col_names_in && n_names != ncols) { + ray_vm_unmap_file(buf, file_size); + return ray_error("length", + "csv read: schema has %lld names but file has %d columns", + (long long)n_names, ncols); + } /* ---- 5. Parse header row ---- */ const char* p = buf; @@ -1980,7 +2127,7 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, * lines are null data rows. */ if (p < buf_end && *p == '\r') p++; if (p < buf_end && *p == '\n') p++; - } else if (col_names_in && n_names >= ncols) { + } else if (col_names_in) { for (int c = 0; c < ncols; c++) col_name_ids[c] = col_names_in[c]; const char* after = csv_skip_matching_header(buf, buf_end, delimiter, @@ -2002,6 +2149,11 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, int64_t n_rows = build_row_offsets(buf, file_size, data_offset, &row_offsets, &row_offsets_hdr); + if (n_rows < 0) { + ray_vm_unmap_file(buf, file_size); + return ray_error("cancel", "interrupted"); + } + if (n_rows == 0) { /* Empty file → empty table */ ray_t* tbl = ray_table_new(ncols); @@ -2019,15 +2171,18 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, /* ---- 7. Resolve column types ---- */ int8_t resolved_types[CSV_MAX_COLS]; - if (col_types_in && n_types >= ncols) { + if (col_types_in) { /* Explicit types provided by caller — validate against known types */ for (int c = 0; c < ncols; c++) { int8_t t = col_types_in[c]; if (t < RAY_BOOL || (t >= RAY_TYPE_COUNT && t != RAY_CSV_AUTO_TAG) || t == RAY_TABLE) { - /* Invalid type constant — fall through to error */ - goto fail_offsets; + scratch_free(row_offsets_hdr); + ray_vm_unmap_file(buf, file_size); + return ray_error("type", + "csv read: unsupported type code %d in column %d", + (int)t, c); } resolved_types[c] = t; } @@ -2036,16 +2191,14 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, ncols, delimiter, esc_buf, resolved_types)) goto fail_offsets; - } else { - /* col_types_in provided but too short — error */ - goto fail_offsets; } /* `INT` schema columns: resolve to a concrete narrowest width over all * rows before allocating vectors, so the explicit-width path below sees a * real type. */ - csv_resolve_auto_in_place(buf, file_size, row_offsets, n_rows, - ncols, delimiter, resolved_types); + if (!csv_resolve_auto_in_place(buf, file_size, row_offsets, n_rows, + ncols, delimiter, resolved_types)) + goto fail_offsets_cancel; /* ---- 8. Allocate column vectors ---- */ ray_t* col_vecs[CSV_MAX_COLS]; @@ -2070,6 +2223,9 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, bool col_had_null[CSV_MAX_COLS]; if (ncols > 0) memset(col_had_null, 0, (size_t)ncols * sizeof(bool)); + bool col_had_escaped[CSV_MAX_COLS]; + memset(col_had_escaped, 0, sizeof(col_had_escaped)); + /* Build csv_type_t array for parse functions (maps td types → csv types) */ csv_type_t parse_types[CSV_MAX_COLS]; for (int c = 0; c < ncols; c++) { @@ -2106,6 +2262,14 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, ray_t* str_ref_hdrs[CSV_MAX_COLS]; memset(str_ref_bufs, 0, sizeof(str_ref_bufs)); memset(str_ref_hdrs, 0, sizeof(str_ref_hdrs)); + ray_t* row_done_hdr = NULL; + uint8_t* row_done = has_text_cols + ? (uint8_t*)scratch_calloc(&row_done_hdr, (size_t)n_rows) + : NULL; + if (has_text_cols && !row_done) { + for (int c = 0; c < ncols; c++) ray_release(col_vecs[c]); + goto fail_offsets; + } for (int c = 0; c < ncols; c++) { if (parse_types[c] == CSV_TYPE_STR) { size_t sz = (size_t)n_rows * sizeof(csv_strref_t); @@ -2113,6 +2277,7 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, if (!str_ref_bufs[c]) { for (int j = 0; j < ncols; j++) ray_release(col_vecs[j]); for (int j = 0; j < c; j++) scratch_free(str_ref_hdrs[j]); + scratch_free(row_done_hdr); goto fail_offsets; } } @@ -2124,12 +2289,15 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, if (use_parallel) { uint32_t n_workers = ray_pool_total_workers(pool); - size_t whn_sz = (size_t)n_workers * (size_t)ncols * sizeof(bool); - bool* worker_had_null_buf = (bool*)ray_sys_alloc(whn_sz); - if (!worker_had_null_buf) { + size_t worker_flags_sz = (size_t)n_workers * (size_t)ncols * sizeof(bool); + bool* worker_flags = (bool*)ray_sys_alloc(worker_flags_sz * 2); + if (!worker_flags) { use_parallel = false; } else { - memset(worker_had_null_buf, 0, whn_sz); + memset(worker_flags, 0, worker_flags_sz * 2); + bool* worker_had_null_buf = worker_flags; + bool* worker_had_escaped_buf = worker_flags + + (size_t)n_workers * (size_t)ncols; csv_par_ctx_t ctx = { .buf = buf, @@ -2143,6 +2311,8 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, .col_data = col_data, .str_refs = str_ref_bufs, .worker_had_null = worker_had_null_buf, + .worker_had_escaped = worker_had_escaped_buf, + .row_done = row_done, }; ray_pool_dispatch(pool, csv_parse_fn, &ctx, n_rows); @@ -2152,19 +2322,24 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, for (int c = 0; c < ncols; c++) { if (worker_had_null_buf[(size_t)w * (size_t)ncols + (size_t)c]) col_had_null[c] = true; + if (worker_had_escaped_buf[(size_t)w * (size_t)ncols + (size_t)c]) + col_had_escaped[c] = true; } } - ray_sys_free(worker_had_null_buf); + ray_sys_free(worker_flags); } } if (!use_parallel) { - csv_parse_serial(buf, file_size, row_offsets, n_rows, - ncols, delimiter, parse_types, resolved_types, col_data, - str_ref_bufs, col_had_null); + (void)csv_parse_serial(buf, file_size, row_offsets, n_rows, + ncols, delimiter, parse_types, resolved_types, + col_data, str_ref_bufs, col_had_null, + col_had_escaped, row_done); } } + if (ray_interrupted()) goto fail_parsed_cancel; + /* ---- 9b. Materialize RAY_STR columns AND batch-intern sym columns ---- * These two phases touch disjoint columns and (after the GUID fix) * intern_strings is the only one that mutates the global sym table. @@ -2185,14 +2360,24 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, }; ray_pool_t* fpool = ray_pool_get(); if (fpool && ray_pool_total_workers(fpool) >= 2) { + /* Finalization has two coarse internal tasks, not rows. Letting + * the generic pool progress pump expose them resets a completed + * n_rows parse to 0/2 (visibly 100% -> 50%). Keep profiling + * active, but preserve the row progress until query completion. */ + uint32_t qmode = ray_qstats_mode(); + ray_qstats_set_mode(qmode & ~RAY_QS_PROGRESS); ray_pool_dispatch_n(fpool, csv_finalize_task, &fctx, 2); + ray_qstats_set_mode(qmode); } else { csv_finalize_task(&fctx, 0, 0, 1); csv_finalize_task(&fctx, 0, 1, 2); } - if (!fctx.fill_ok || !fctx.intern_ok) { - csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, buf, file_size); + if (!fctx.fill_ok || !fctx.intern_ok || ray_interrupted()) { + if (ray_interrupted()) goto fail_parsed_cancel; + csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, + buf, file_size, NULL, col_had_escaped); for (int c = 0; c < ncols; c++) scratch_free(str_ref_hdrs[c]); + scratch_free(row_done_hdr); for (int c = 0; c < ncols; c++) ray_release(col_vecs[c]); goto fail_offsets; } @@ -2202,14 +2387,19 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, if (resolved_types[c] != RAY_SYM) continue; uint32_t* ids = (uint32_t*)col_data[c]; int64_t max_id = 0; - for (int64_t r = 0; r < n_rows; r++) + for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) + goto fail_parsed_cancel; if ((int64_t)ids[r] > max_id) max_id = ids[r]; + } sym_max_ids[c] = max_id; } /* Free heap-allocated escaped string copies, then strref buffers */ - csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, buf, file_size); + csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, + buf, file_size, NULL, col_had_escaped); for (int c = 0; c < ncols; c++) scratch_free(str_ref_hdrs[c]); + scratch_free(row_done_hdr); /* ---- 9c. Set HAS_NULLS for columns that saw a null ---- * @@ -2239,10 +2429,22 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, void* dst = ray_data(narrow); if (new_w == RAY_SYM_W8) { uint8_t* d = (uint8_t*)dst; - for (int64_t r = 0; r < n_rows; r++) d[r] = (uint8_t)src[r]; + for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) { + ray_release(narrow); + goto fail_cols_cancel; + } + d[r] = (uint8_t)src[r]; + } } else { /* RAY_SYM_W16 */ uint16_t* d = (uint16_t*)dst; - for (int64_t r = 0; r < n_rows; r++) d[r] = (uint16_t)src[r]; + for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) { + ray_release(narrow); + goto fail_cols_cancel; + } + d[r] = (uint16_t)src[r]; + } } narrow->attrs |= (col_vecs[c]->attrs & RAY_ATTR_HAS_NULLS); ray_release(col_vecs[c]); @@ -2258,16 +2460,20 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, * Second pass upgrades high-entropy columns to a hash index; * see csv_should_attach_hash. */ for (int c = 0; c < ncols; c++) { + if (ray_interrupted()) goto fail_cols_cancel; ray_t* v = col_vecs[c]; if (!v || RAY_IS_ERR(v)) continue; if (v->len < (1 << 16)) continue; ray_t* r = ray_index_attach_chunk_zone(&v, 16); + if (ray_interrupted()) goto fail_cols_cancel; if (r && !RAY_IS_ERR(r)) col_vecs[c] = v; } for (int c = 0; c < ncols; c++) { + if (ray_interrupted()) goto fail_cols_cancel; ray_t* v = col_vecs[c]; if (!csv_should_attach_hash(v)) continue; ray_t* r = ray_index_attach_hash(&v); + if (ray_interrupted()) goto fail_cols_cancel; if (r && !RAY_IS_ERR(r)) col_vecs[c] = v; } @@ -2291,6 +2497,17 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, return result; /* Error paths */ +fail_parsed_cancel: + csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows, + buf, file_size, row_done, col_had_escaped); + for (int c = 0; c < ncols; c++) scratch_free(str_ref_hdrs[c]); + scratch_free(row_done_hdr); +fail_cols_cancel: + for (int c = 0; c < ncols; c++) ray_release(col_vecs[c]); +fail_offsets_cancel: + scratch_free(row_offsets_hdr); + ray_vm_unmap_file(buf, file_size); + return ray_error("cancel", "interrupted"); fail_offsets: scratch_free(row_offsets_hdr); fail_unmap: @@ -2434,6 +2651,7 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool const int8_t* col_types_in, int32_t n_types, const int64_t* col_names_in, int32_t n_names, const char* dir, int64_t rows_per_chunk) { + if (ray_interrupted()) return RAY_ERR_CANCEL; if (!path || !dir) return RAY_ERR_DOMAIN; if (rows_per_chunk <= 0) rows_per_chunk = CSV_PART_ROWS_DEFAULT; @@ -2481,6 +2699,11 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool ray_vm_unmap_file(buf, file_size); return RAY_ERR_RANGE; } + if ((col_types_in && n_types != ncols) || + (col_names_in && n_names != ncols)) { + ray_vm_unmap_file(buf, file_size); + return RAY_ERR_LENGTH; + } const char* p = buf; char esc_buf[8192]; @@ -2497,7 +2720,7 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool } if (p < buf_end && *p == '\r') p++; if (p < buf_end && *p == '\n') p++; - } else if (col_names_in && n_names >= ncols) { + } else if (col_names_in) { for (int c = 0; c < ncols; c++) col_name_ids[c] = col_names_in[c]; const char* after = csv_skip_matching_header(buf, buf_end, delimiter, @@ -2514,7 +2737,7 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool size_t data_offset = (size_t)(p - buf); bool data_has_quotes = memchr(buf + data_offset, '"', file_size - data_offset) != NULL; int8_t resolved_types[CSV_MAX_COLS]; - if (col_types_in && n_types >= ncols) { + if (col_types_in) { for (int c = 0; c < ncols; c++) { int8_t t = col_types_in[c]; if (t < RAY_BOOL || @@ -2534,6 +2757,10 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool &sample_offsets, &sample_offsets_hdr, NULL); + if (sample_n < 0) { + ray_vm_unmap_file(buf, file_size); + return RAY_ERR_CANCEL; + } bool infer_ok = csv_infer_types_from_offsets( buf, buf_end, sample_offsets, sample_n, ncols, delimiter, esc_buf, resolved_types); @@ -2542,9 +2769,6 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool ray_vm_unmap_file(buf, file_size); return RAY_ERR_OOM; } - } else { - ray_vm_unmap_file(buf, file_size); - return RAY_ERR_TYPE; } for (int c = 0; c < ncols; c++) { @@ -2576,8 +2800,11 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool /* `INT` schema columns: resolve to a concrete narrowest width over the * whole file before opening the fixed-width streaming column writers. */ - csv_resolve_auto_streamed(buf, file_size, data_offset, ncols, delimiter, - data_has_quotes, resolved_types); + if (!csv_resolve_auto_streamed(buf, file_size, data_offset, ncols, + delimiter, data_has_quotes, resolved_types)) { + ray_vm_unmap_file(buf, file_size); + return RAY_ERR_CANCEL; + } err = ray_mkdir_p(dir); if (err != RAY_OK) { @@ -2660,7 +2887,7 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool &row_offsets_hdr, &next_offset); if (cnt <= 0) { scratch_free(row_offsets_hdr); - err = RAY_ERR_IO; + err = (cnt < 0) ? RAY_ERR_CANCEL : RAY_ERR_IO; break; } } @@ -2670,8 +2897,9 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool resolved_types); scratch_free(row_offsets_hdr); if (!tbl || RAY_IS_ERR(tbl)) { + err = (tbl && RAY_IS_ERR(tbl)) ? ray_err_from_obj(tbl) + : RAY_ERR_OOM; if (tbl) ray_release(tbl); - err = RAY_ERR_OOM; break; } @@ -2738,6 +2966,7 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool const int64_t* col_names_in, int32_t n_names, const char* root, const char* table_name, int64_t rows_per_part) { + if (ray_interrupted()) return RAY_ERR_CANCEL; if (!path || !root || !table_name) return RAY_ERR_DOMAIN; if (rows_per_part <= 0) rows_per_part = CSV_PART_ROWS_DEFAULT; bool trace = getenv("RAY_CSV_TRACE") != NULL; @@ -2786,6 +3015,11 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool ray_vm_unmap_file(buf, file_size); return RAY_ERR_RANGE; } + if ((col_types_in && n_types != ncols) || + (col_names_in && n_names != ncols)) { + ray_vm_unmap_file(buf, file_size); + return RAY_ERR_LENGTH; + } const char* p = buf; char esc_buf[8192]; @@ -2802,7 +3036,7 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool } if (p < buf_end && *p == '\r') p++; if (p < buf_end && *p == '\n') p++; - } else if (col_names_in && n_names >= ncols) { + } else if (col_names_in) { for (int c = 0; c < ncols; c++) col_name_ids[c] = col_names_in[c]; const char* after = csv_skip_matching_header(buf, buf_end, delimiter, @@ -2825,7 +3059,7 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool } int8_t resolved_types[CSV_MAX_COLS]; - if (col_types_in && n_types >= ncols) { + if (col_types_in) { for (int c = 0; c < ncols; c++) { int8_t t = col_types_in[c]; if (t < RAY_BOOL || @@ -2845,6 +3079,10 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool &sample_offsets, &sample_offsets_hdr, NULL); + if (sample_n < 0) { + ray_vm_unmap_file(buf, file_size); + return RAY_ERR_CANCEL; + } bool infer_ok = csv_infer_types_from_offsets( buf, buf_end, sample_offsets, sample_n, ncols, delimiter, esc_buf, resolved_types); @@ -2853,15 +3091,15 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool ray_vm_unmap_file(buf, file_size); return RAY_ERR_OOM; } - } else { - ray_vm_unmap_file(buf, file_size); - return RAY_ERR_TYPE; } /* `INT` schema columns: resolve to a concrete narrowest width over the * whole file so every partition writes the same column type. */ - csv_resolve_auto_streamed(buf, file_size, data_offset, ncols, delimiter, - data_has_quotes, resolved_types); + if (!csv_resolve_auto_streamed(buf, file_size, data_offset, ncols, + delimiter, data_has_quotes, resolved_types)) { + ray_vm_unmap_file(buf, file_size); + return RAY_ERR_CANCEL; + } err = ray_mkdir_p(root); if (err != RAY_OK) { @@ -2887,7 +3125,7 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool fprintf(stderr, "csv.parted: row-offset failure part=%" PRId64 " offset=%zu\n", part, chunk_offset); scratch_free(row_offsets_hdr); - err = RAY_ERR_IO; + err = (cnt < 0) ? RAY_ERR_CANCEL : RAY_ERR_IO; break; } } @@ -2895,9 +3133,10 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool ray_t* tbl = csv_materialize_rows(buf, file_size, row_offsets, cnt, ncols, delimiter, col_name_ids, resolved_types); if (!tbl || RAY_IS_ERR(tbl)) { + err = (tbl && RAY_IS_ERR(tbl)) ? ray_err_from_obj(tbl) + : RAY_ERR_OOM; if (tbl) ray_release(tbl); scratch_free(row_offsets_hdr); - err = RAY_ERR_OOM; if (trace) fprintf(stderr, "csv.parted: materialize failure part=%" PRId64 " rows=%" PRId64 "\n", part, cnt); diff --git a/src/lang/compile.c b/src/lang/compile.c index 7475c5053..bd83adc38 100644 --- a/src/lang/compile.c +++ b/src/lang/compile.c @@ -278,6 +278,10 @@ static void compile_list(compiler_t *c, ray_t *ast) { ray_t *name_obj = elems[1]; if (name_obj->type != -RAY_SYM) { c->error = true; return; } compile_expr(c, elems[2]); + /* Match ray_set_fn: globals must never retain a single-use lazy + * DAG handle. Materializing one alias consumes its graph and + * would leave every other global read pointing at a spent handle. */ + emit(c, OP_FORCE); int32_t idx = add_constant(c, name_obj); if (idx < 256) { emit(c, OP_STOREGLOBAL); @@ -332,6 +336,9 @@ static void compile_list(compiler_t *c, ray_t *ast) { /* (if cond then else?) */ if (sym_id == sf_if && n >= 3) { compile_expr(c, elems[1]); + /* Match ray_cond_fn: truthiness belongs to the materialized value, + * not to the non-NULL lazy handle that happens to contain it. */ + emit(c, OP_FORCE); int32_t jmpf_pos = emit_jump(c, OP_JMPF); compile_expr(c, elems[2]); if (n >= 4) { diff --git a/src/ops/arith.c b/src/ops/arith.c index d22c8aba7..1bd67f2f3 100644 --- a/src/ops/arith.c +++ b/src/ops/arith.c @@ -138,7 +138,12 @@ ray_t* ray_add_fn(ray_t* a, ray_t* b) { if (both_f32_atoms(a, b)) return ray_f32((float)(as_f64(a) + as_f64(b))); if (is_float_op(a, b)) return make_f64(as_f64(a) + as_f64(b)); int8_t rt = promote_int_type(a, b); - return make_typed_int(rt, as_i64(a) + as_i64(b)); + /* Wrap on overflow (defined) rather than signed-overflow UB, matching the + * vector arithmetic kernel (src/ops/expr.c OP_ADD/SUB/MUL). The wrapped + * i64 (INT64_MIN on MAX+1) is the null sentinel, so results are unchanged + * — only the undefined arithmetic is removed. */ + int64_t la = as_i64(a), lb = as_i64(b); + return make_typed_int(rt, (int64_t)((uint64_t)la + (uint64_t)lb)); } ray_t* ray_sub_fn(ray_t* a, ray_t* b) { @@ -220,7 +225,9 @@ ray_t* ray_sub_fn(ray_t* a, ray_t* b) { return make_f64(r); } int8_t rt = promote_int_type_right(a, b); - return make_typed_int(rt, as_i64(a) - as_i64(b)); + /* uint64 wrap on overflow (defined), like ray_add_fn / the vector kernel. */ + int64_t la = as_i64(a), lb = as_i64(b); + return make_typed_int(rt, (int64_t)((uint64_t)la - (uint64_t)lb)); } ray_t* ray_mul_fn(ray_t* a, ray_t* b) { @@ -254,7 +261,9 @@ ray_t* ray_mul_fn(ray_t* a, ray_t* b) { if (both_f32_atoms(a, b)) return ray_f32((float)(as_f64(a) * as_f64(b))); if (is_float_op(a, b)) return make_f64(as_f64(a) * as_f64(b)); int8_t rt = promote_int_type(a, b); - return make_typed_int(rt, as_i64(a) * as_i64(b)); + /* uint64 wrap on overflow (defined), like ray_add_fn / the vector kernel. */ + int64_t la = as_i64(a), lb = as_i64(b); + return make_typed_int(rt, (int64_t)((uint64_t)la * (uint64_t)lb)); } ray_t* ray_div_fn(ray_t* a, ray_t* b) { diff --git a/src/ops/builtins.c b/src/ops/builtins.c index 5699b4636..c8672f6fd 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -505,8 +505,13 @@ static int8_t resolve_type_name(int64_t sym_id) { else if (len == 3 && memcmp(name, "F64", 3) == 0) result = RAY_F64; else if (len == 2 && memcmp(name, "B8", 2) == 0) result = RAY_BOOL; else if (len == 2 && memcmp(name, "U8", 2) == 0) result = RAY_U8; + else if (len == 3 && memcmp(name, "SYM", 3) == 0) result = RAY_SYM; else if (len == 6 && memcmp(name, "SYMBOL", 6) == 0) result = RAY_SYM; else if (len == 3 && memcmp(name, "STR", 3) == 0) result = RAY_STR; + /* CSV cells are scalar text, so the historical LIST schema spelling is + * materialized as the native packed STR column rather than a boxed list. + * This keeps schemas copied from older table displays loadable. */ + else if (len == 4 && memcmp(name, "LIST", 4) == 0) result = RAY_STR; else if (len == 3 && memcmp(name, "F32", 3) == 0) result = RAY_F32; else if (len == 4 && memcmp(name, "DATE", 4) == 0) result = RAY_DATE; else if (len == 4 && memcmp(name, "TIME", 4) == 0) result = RAY_TIME; @@ -1553,18 +1558,48 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_TIME) return ray_date((int64_t)val->i32); if (val->type == -RAY_TIMESTAMP) return ray_date(ts_days_floor(val->i64)); if (val->type == -RAY_STR) { - /* Parse "YYYY.MM.DD" format */ + /* Parse "YYYY.MM.DD" with a bounded cursor that must consume the + * whole string. The old sscanf path accepted trailing garbage + * ("2024.01.02junk") and, worse, never range-checked the month: + * a month > 13 drove the days-in-month table index out of bounds + * — e.g. (as 'DATE "9999.99.99") read md[99] (ASan OOB). Validate + * the month BEFORE indexing the table, and the day against the + * actual days in that (possibly leap) month. Mirrors the strict + * TIMESTAMP string cast. */ const char* sp = ray_str_ptr(val); - int y, m, d2; - if (sscanf(sp, "%d.%d.%d", &y, &m, &d2) != 3) return ray_error("domain", "as: cannot parse str as date, expected YYYY.MM.DD"); + size_t sl = ray_str_len(val); + size_t i = 0; + int y = 0, m = 0, d2 = 0; + #define DT_DIGITS(w, out) do { \ + (out) = 0; \ + for (int _k = 0; _k < (w); _k++) { \ + if (i >= sl || sp[i] < '0' || sp[i] > '9') \ + return ray_error("domain", "as: cannot parse str as date, expected YYYY.MM.DD"); \ + (out) = (out) * 10 + (sp[i] - '0'); i++; \ + } \ + } while (0) + DT_DIGITS(4, y); + if (i >= sl || sp[i] != '.') return ray_error("domain", "as: cannot parse str as date, expected YYYY.MM.DD"); + i++; + DT_DIGITS(2, m); + if (i >= sl || sp[i] != '.') return ray_error("domain", "as: cannot parse str as date, expected YYYY.MM.DD"); + i++; + DT_DIGITS(2, d2); + if (i != sl) return ray_error("domain", "as: cannot parse str as date, unexpected trailing characters"); + #undef DT_DIGITS + static const int dt_md[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; + int leap = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)); + if (m < 1 || m > 12) + return ray_error("domain", "as: cannot parse str as date, month out of range"); + int mdays = dt_md[m] + (m == 2 && leap ? 1 : 0); + if (d2 < 1 || d2 > mdays) + return ray_error("domain", "as: cannot parse str as date, day out of range for month"); int64_t days = 0; { int ty; for (ty = 2000; ty < y; ty++) days += (ty % 4 == 0 && (ty % 100 != 0 || ty % 400 == 0)) ? 366 : 365; for (ty = y; ty < 2000; ty++) days -= (ty % 4 == 0 && (ty % 100 != 0 || ty % 400 == 0)) ? 366 : 365; } - { static const int md2[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; - int leap = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)); - for (int mi = 1; mi < m; mi++) days += md2[mi] + (mi == 2 && leap ? 1 : 0); + { for (int mi = 1; mi < m; mi++) days += dt_md[mi] + (mi == 2 && leap ? 1 : 0); days += d2 - 1; } return ray_date(days); @@ -1592,21 +1627,60 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { * matching wall-clock semantics. */ return ray_time((int64_t)(ts_ns_in_day(val->i64) / 1000000LL)); if (val->type == -RAY_STR) { - /* Parse "HH:MM:SS[.mmm]" */ + /* Parse "[-]HH:MM[:SS][.fff]" with a bounded cursor that must + * consume the whole string. TIME is a signed duration — ms-of-day + * can exceed a day and go negative (see .csv.read round-tripping) — + * so the hour field is variable width and unbounded, but minutes + * and seconds are 0-59. The old sscanf path accepted trailing + * garbage ("12:34:56junk") and out-of-range fields ("25:99:99" → + * 26:40:39), silently corrupting the value; mirror the strict DATE + * / TIMESTAMP string casts. */ const char* sp = ray_str_ptr(val); - int th = 0, tm = 0, ts = 0, tms = 0; - int nr = sscanf(sp, "%d:%d:%d", &th, &tm, &ts); - if (nr < 2) return ray_error("domain", "as: cannot parse str as time, expected HH:MM:SS[.mmm]"); - const char* dot = strchr(sp, '.'); - if (dot) { - dot++; + size_t sl = ray_str_len(val); + size_t i = 0; + int64_t sign = 1; + if (i < sl && sp[i] == '-') { sign = -1; i++; } + /* Variable-width hour, >= 1 digit, capped so ms cannot overflow. */ + if (i >= sl || sp[i] < '0' || sp[i] > '9') + return ray_error("domain", "as: cannot parse str as time, expected [-]HH:MM[:SS][.fff]"); + int64_t hh = 0; + int hd = 0; + while (i < sl && sp[i] >= '0' && sp[i] <= '9') { + hh = hh * 10 + (sp[i] - '0'); i++; + if (++hd > 7) return ray_error("domain", "as: cannot parse str as time, hour field too long"); + } + /* Read exactly 2 digits into `out`, validate 0..59. */ + #define TM_2DIGIT(out) do { \ + if (i + 1 >= sl || sp[i] < '0' || sp[i] > '9' || sp[i+1] < '0' || sp[i+1] > '9') \ + return ray_error("domain", "as: cannot parse str as time, expected 2-digit field"); \ + (out) = (sp[i]-'0')*10 + (sp[i+1]-'0'); i += 2; \ + if ((out) > 59) return ray_error("domain", "as: cannot parse str as time, minute/second out of range"); \ + } while (0) + if (i >= sl || sp[i] != ':') + return ray_error("domain", "as: cannot parse str as time, expected ':' after hour"); + i++; + int mm = 0, ss = 0, tms = 0; + TM_2DIGIT(mm); + if (i < sl && sp[i] == ':') { i++; TM_2DIGIT(ss); } + #undef TM_2DIGIT + /* Optional fractional seconds → milliseconds; a bare trailing '.' + * is accepted as .000. */ + if (i < sl && sp[i] == '.') { + i++; char mbuf[4] = "000"; int mi = 0; - while (*dot >= '0' && *dot <= '9' && mi < 3) mbuf[mi++] = *dot++; + while (i < sl && sp[i] >= '0' && sp[i] <= '9') { + if (mi < 3) mbuf[mi++] = sp[i]; + i++; + } tms = (int)strtol(mbuf, NULL, 10); } - int32_t ms = (int32_t)th * 3600000 + (int32_t)tm * 60000 + (int32_t)ts * 1000 + tms; - return ray_time((int64_t)ms); + if (i != sl) + return ray_error("domain", "as: cannot parse str as time, unexpected trailing characters"); + int64_t ms = sign * (hh * 3600000LL + (int64_t)mm * 60000LL + (int64_t)ss * 1000LL + tms); + if (ms > INT32_MAX || ms < INT32_MIN) + return ray_error("domain", "as: cannot parse str as time, out of int32 millisecond range"); + return ray_time(ms); } /* Vector cast */ if (ray_is_vec(val) || val->type == RAY_LIST) diff --git a/src/ops/collection.c b/src/ops/collection.c index cfc0ada95..8380545d1 100644 --- a/src/ops/collection.c +++ b/src/ops/collection.c @@ -1048,16 +1048,33 @@ ray_t* distinct_vec_eager(ray_t* x) { } } - hashset_t hs; - if (!hashset_init(&hs, x, len)) { + /* Parallel radix kernel for large fixed-width columns — same + * partition scheme as exec_count_distinct, producing the same row-id + * set the hashset pass below would (one first-occurrence id per + * value). NULL means the kernel declined (type, size, or pool) and + * the hashset handles it. Either way the ids flow into the shared + * sort + gather tail, so result semantics are identical. */ + int64_t count = 0; + ray_t* rids = distinct_radix_first_ids(x); + if (rids && RAY_IS_ERR(rids)) { if (idx != idx_stack) ray_sys_free(idx); - return ray_error("oom", NULL); + return rids; } - int64_t count = 0; - for (int64_t i = 0; i < len; i++) { - if (hashset_insert(&hs, i)) idx[count++] = i; + if (rids) { + count = ray_len(rids); + memcpy(idx, ray_data(rids), (size_t)count * sizeof(int64_t)); + ray_release(rids); + } else { + hashset_t hs; + if (!hashset_init(&hs, x, len)) { + if (idx != idx_stack) ray_sys_free(idx); + return ray_error("oom", NULL); + } + for (int64_t i = 0; i < len; i++) { + if (hashset_insert(&hs, i)) idx[count++] = i; + } + hashset_destroy(&hs); } - hashset_destroy(&hs); /* Sort unique indices by value for numeric/temporal types — preserves * pre-existing distinct semantics. qsort-based; was O(count^2). */ diff --git a/src/ops/graph.c b/src/ops/graph.c index fdaa9de3a..142335301 100644 --- a/src/ops/graph.c +++ b/src/ops/graph.c @@ -1766,6 +1766,8 @@ ray_t* ray_lazy_wrap(ray_graph_t* g, ray_op_t* op) { ray_t* ray_lazy_append(ray_t* lazy, uint16_t opcode) { ray_graph_t* g = RAY_LAZY_GRAPH(lazy); ray_op_t* prev = RAY_LAZY_OP(lazy); + if (!g || !prev) + return ray_error("domain", "lazy handle already materialized"); /* Determine output type based on opcode */ int8_t out_type; @@ -1833,6 +1835,8 @@ ray_t* ray_lazy_append(ray_t* lazy, uint16_t opcode) { ray_t* ray_lazy_append_param(ray_t* lazy, uint16_t opcode, int64_t param) { ray_graph_t* g = RAY_LAZY_GRAPH(lazy); ray_op_t* prev = RAY_LAZY_OP(lazy); + if (!g || !prev) + return ray_error("domain", "lazy handle already materialized"); int8_t out_type; switch (opcode) { @@ -1865,6 +1869,12 @@ ray_t* ray_lazy_materialize(ray_t* val) { ray_graph_t* g = RAY_LAZY_GRAPH(val); ray_op_t* op = RAY_LAZY_OP(val); + if (!g || !op) { + RAY_LAZY_GRAPH(val) = NULL; + RAY_LAZY_OP(val) = NULL; + ray_release(val); + return ray_error("domain", "lazy handle already materialized"); + } /* Run the full optimizer pipeline before execution. ray_optimize may return a different root (e.g. predicate pushdown). */ @@ -1876,6 +1886,7 @@ ray_t* ray_lazy_materialize(ray_t* val) { /* Clear graph pointer before releasing to prevent double-free in * ray_release_owned_refs */ RAY_LAZY_GRAPH(val) = NULL; + RAY_LAZY_OP(val) = NULL; ray_release(val); return result; } diff --git a/src/ops/group.c b/src/ops/group.c index 629dd81fc..b6fd38d2d 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -101,7 +101,6 @@ typedef struct { * instead of being whatever (uint64) wrap left in sum_i. */ double sum_d; int64_t cnt; - int64_t null_count; int64_t zero_count; bool has_first; } reduce_acc_t; @@ -112,7 +111,7 @@ static void reduce_acc_init(reduce_acc_t* acc) { acc->sum_i = 0; acc->min_i = INT64_MAX; acc->max_i = INT64_MIN; acc->prod_i = 1; acc->first_i = 0; acc->last_i = 0; acc->sum_sq_i = 0; acc->sum_d = 0; - acc->cnt = 0; acc->null_count = 0; acc->zero_count = 0; acc->has_first = false; + acc->cnt = 0; acc->zero_count = 0; acc->has_first = false; } /* Lexicographic SYM compare — resolves both sym_ids to strings and @@ -265,6 +264,32 @@ static ray_t* agg_wide_reduce(ray_t* input, uint16_t op, return result; } +/* Reduction field mask. Every REDUCE_LOOP_* invocation receives a compile-time + * constant mask selected by opcode BEFORE entering the element loop. The + * compiler therefore removes every accumulator update that the requested + * reduction does not need: OP_SUM emits a sum-only loop, OP_MIN a min-only + * loop, OP_VAR the sum/sum-square/count loop, and so on. */ +#define RED_NEED_SUM (1u << 0) +#define RED_NEED_SUM_SQ (1u << 1) +#define RED_NEED_PROD (1u << 2) +#define RED_NEED_SUM_D (1u << 3) /* integer stream accumulated as f64 */ +#define RED_NEED_COUNT (1u << 4) +#define RED_NEED_ZERO (1u << 5) +#define RED_NEED_MIN (1u << 6) +#define RED_NEED_MAX (1u << 7) +#define RED_NEED_FIRST (1u << 8) +#define RED_NEED_LAST (1u << 9) + +#define RED_MASK_ANY (RED_NEED_COUNT | RED_NEED_ZERO) +#define RED_MASK_MIN (RED_NEED_COUNT | RED_NEED_MIN) +#define RED_MASK_MAX (RED_NEED_COUNT | RED_NEED_MAX) +#define RED_MASK_FIRST (RED_NEED_COUNT | RED_NEED_FIRST) +#define RED_MASK_LAST (RED_NEED_COUNT | RED_NEED_LAST) +#define RED_MASK_AVG_I (RED_NEED_SUM_D | RED_NEED_COUNT) +#define RED_MASK_AVG_F (RED_NEED_SUM | RED_NEED_COUNT) +#define RED_MASK_STATS_I (RED_NEED_SUM_D | RED_NEED_SUM_SQ | RED_NEED_COUNT) +#define RED_MASK_STATS_F (RED_NEED_SUM | RED_NEED_SUM_SQ | RED_NEED_COUNT) + /* Integer reduction loop — reads native type T, accumulates as i64. * HAS_NULLS and HAS_IDX must be integer literal constants (0 or 1) so the * compiler dead-code-eliminates the corresponding branches in every @@ -276,108 +301,231 @@ static ray_t* agg_wide_reduce(ray_t* input, uint16_t op, * NULL_I32, NULL_I64). For BOOL/U8 the sentinel slot is unused * (those types are non-nullable; dispatcher pins HAS_NULLS=0) so any * value works; we pass 0 for compileability. */ -#define REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, HAS_NULLS, HAS_IDX, idx) \ +#define REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, HAS_NULLS, HAS_IDX, idx, NEEDS) \ do { \ const T* d = (const T*)(base); \ for (int64_t i = start; i < end; i++) { \ int64_t row = (HAS_IDX) ? (idx)[i] : i; \ T raw = d[row]; \ - if ((HAS_NULLS) && raw == (T)(NULL_SENT)) { (acc)->null_count++; continue; } \ + if ((HAS_NULLS) && raw == (T)(NULL_SENT)) continue; \ int64_t v = (int64_t)raw; \ /* sum/sum_sq may overflow on signed arithmetic — use defined \ * unsigned wrap (same semantic, no UBSan whine). */ \ - (acc)->sum_i = (int64_t)((uint64_t)(acc)->sum_i + (uint64_t)v); \ - (acc)->sum_sq_i = (int64_t)((uint64_t)(acc)->sum_sq_i + (uint64_t)v * (uint64_t)v); \ - (acc)->prod_i = (int64_t)((uint64_t)(acc)->prod_i * (uint64_t)v); \ - (acc)->sum_d += (double)v; \ - if (v == 0) (acc)->zero_count++; \ - if (v < (acc)->min_i) (acc)->min_i = v; \ - if (v > (acc)->max_i) (acc)->max_i = v; \ - if (!(acc)->has_first) { (acc)->first_i = v; (acc)->has_first = true; } \ - (acc)->last_i = v; (acc)->cnt++; \ + if ((NEEDS) & RED_NEED_SUM) \ + (acc)->sum_i = (int64_t)((uint64_t)(acc)->sum_i + (uint64_t)v); \ + if ((NEEDS) & RED_NEED_SUM_SQ) \ + (acc)->sum_sq_i = (int64_t)((uint64_t)(acc)->sum_sq_i + (uint64_t)v * (uint64_t)v); \ + if ((NEEDS) & RED_NEED_PROD) \ + (acc)->prod_i = (int64_t)((uint64_t)(acc)->prod_i * (uint64_t)v); \ + if ((NEEDS) & RED_NEED_SUM_D) (acc)->sum_d += (double)v; \ + if (((NEEDS) & RED_NEED_ZERO) && v == 0) (acc)->zero_count++; \ + if (((NEEDS) & RED_NEED_MIN) && v < (acc)->min_i) (acc)->min_i = v; \ + if (((NEEDS) & RED_NEED_MAX) && v > (acc)->max_i) (acc)->max_i = v; \ + if (((NEEDS) & RED_NEED_FIRST) && !(acc)->has_first) { \ + (acc)->first_i = v; (acc)->has_first = true; \ + } \ + if ((NEEDS) & RED_NEED_LAST) (acc)->last_i = v; \ + if ((NEEDS) & RED_NEED_COUNT) (acc)->cnt++; \ + } \ + } while (0) + +/* BOOL/U8 nulls, when present, live in the vector bitmap rather than in-band + * as a sentinel. Keep a sibling loop so opcode specialization remains true + * for these types as well. */ +#define REDUCE_LOOP_BITMAP_I(T, input, base, start, end, acc, HAS_NULLS, HAS_IDX, idx, NEEDS) \ + do { \ + const T* d = (const T*)(base); \ + for (int64_t i = start; i < end; i++) { \ + int64_t row = (HAS_IDX) ? (idx)[i] : i; \ + if ((HAS_NULLS) && ray_vec_is_null((input), row)) continue; \ + int64_t v = (int64_t)d[row]; \ + if ((NEEDS) & RED_NEED_SUM) \ + (acc)->sum_i = (int64_t)((uint64_t)(acc)->sum_i + (uint64_t)v); \ + if ((NEEDS) & RED_NEED_SUM_SQ) \ + (acc)->sum_sq_i = (int64_t)((uint64_t)(acc)->sum_sq_i + (uint64_t)v * (uint64_t)v); \ + if ((NEEDS) & RED_NEED_PROD) \ + (acc)->prod_i = (int64_t)((uint64_t)(acc)->prod_i * (uint64_t)v); \ + if ((NEEDS) & RED_NEED_SUM_D) (acc)->sum_d += (double)v; \ + if (((NEEDS) & RED_NEED_ZERO) && v == 0) (acc)->zero_count++; \ + if (((NEEDS) & RED_NEED_MIN) && v < (acc)->min_i) (acc)->min_i = v; \ + if (((NEEDS) & RED_NEED_MAX) && v > (acc)->max_i) (acc)->max_i = v; \ + if (((NEEDS) & RED_NEED_FIRST) && !(acc)->has_first) { \ + (acc)->first_i = v; (acc)->has_first = true; \ + } \ + if ((NEEDS) & RED_NEED_LAST) (acc)->last_i = v; \ + if ((NEEDS) & RED_NEED_COUNT) (acc)->cnt++; \ } \ } while (0) /* Float reduction loop — see REDUCE_LOOP_I for HAS_NULLS/HAS_IDX semantics. * F32/F64 null = NaN; both accumulate in the shared F64 reduction lanes. */ -#define REDUCE_LOOP_F(T, base, start, end, acc, HAS_NULLS, HAS_IDX, idx) \ +#define REDUCE_LOOP_F(T, base, start, end, acc, HAS_NULLS, HAS_IDX, idx, NEEDS) \ do { \ const T* d = (const T*)(base); \ for (int64_t i = start; i < end; i++) { \ int64_t row = (HAS_IDX) ? (idx)[i] : i; \ double v = (double)d[row]; \ - if ((HAS_NULLS) && v != v) { (acc)->null_count++; continue; } \ - (acc)->sum_f += v; (acc)->sum_sq_f += v * v; (acc)->prod_f *= v; \ - if (v == 0.0) (acc)->zero_count++; \ - if (v < (acc)->min_f) (acc)->min_f = v; \ - if (v > (acc)->max_f) (acc)->max_f = v; \ - if (!(acc)->has_first) { (acc)->first_f = v; (acc)->has_first = true; } \ - (acc)->last_f = v; (acc)->cnt++; \ + if ((HAS_NULLS) && v != v) continue; \ + if ((NEEDS) & RED_NEED_SUM) (acc)->sum_f += v; \ + if ((NEEDS) & RED_NEED_SUM_SQ) (acc)->sum_sq_f += v * v; \ + if ((NEEDS) & RED_NEED_PROD) (acc)->prod_f *= v; \ + if (((NEEDS) & RED_NEED_ZERO) && v == 0.0) (acc)->zero_count++; \ + if (((NEEDS) & RED_NEED_MIN) && v < (acc)->min_f) (acc)->min_f = v; \ + if (((NEEDS) & RED_NEED_MAX) && v > (acc)->max_f) (acc)->max_f = v; \ + if (((NEEDS) & RED_NEED_FIRST) && !(acc)->has_first) { \ + (acc)->first_f = v; (acc)->has_first = true; \ + } \ + if ((NEEDS) & RED_NEED_LAST) (acc)->last_f = v; \ + if ((NEEDS) & RED_NEED_COUNT) (acc)->cnt++; \ } \ } while (0) /* Dispatch helper: expand REDUCE_LOOP_I/F with compile-time 0/1 constants for * HAS_NULLS and HAS_IDX based on the runtime pointers so the compiler can * dead-code-eliminate the branches inside each specialisation. */ -#define DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx) \ +#define DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, NEEDS) \ do { \ if (!(has_nulls) && !(idx)) \ - REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, 0, 0, idx); \ + REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, 0, 0, idx, NEEDS); \ else if (!(has_nulls)) \ - REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, 0, 1, idx); \ + REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, 0, 1, idx, NEEDS); \ else if (!(idx)) \ - REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, 1, 0, idx); \ + REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, 1, 0, idx, NEEDS); \ else \ - REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, 1, 1, idx); \ + REDUCE_LOOP_I(T, NULL_SENT, base, start, end, acc, 1, 1, idx, NEEDS); \ + } while (0) + +#define DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, NEEDS) \ + do { \ + if (!(has_nulls) && !(idx)) \ + REDUCE_LOOP_BITMAP_I(T, input, base, start, end, acc, 0, 0, idx, NEEDS); \ + else if (!(has_nulls)) \ + REDUCE_LOOP_BITMAP_I(T, input, base, start, end, acc, 0, 1, idx, NEEDS); \ + else if (!(idx)) \ + REDUCE_LOOP_BITMAP_I(T, input, base, start, end, acc, 1, 0, idx, NEEDS); \ + else \ + REDUCE_LOOP_BITMAP_I(T, input, base, start, end, acc, 1, 1, idx, NEEDS); \ + } while (0) + +#define DISPATCH_F(T, base, start, end, acc, has_nulls, idx, NEEDS) \ + do { \ + if (!(has_nulls) && !(idx)) \ + REDUCE_LOOP_F(T, base, start, end, acc, 0, 0, idx, NEEDS); \ + else if (!(has_nulls)) \ + REDUCE_LOOP_F(T, base, start, end, acc, 0, 1, idx, NEEDS); \ + else if (!(idx)) \ + REDUCE_LOOP_F(T, base, start, end, acc, 1, 0, idx, NEEDS); \ + else \ + REDUCE_LOOP_F(T, base, start, end, acc, 1, 1, idx, NEEDS); \ + } while (0) + +/* Select the accumulator shape once per dispatched range. NEEDS remains a + * literal at every loop expansion, which is the key property: no opcode test + * or unused accumulator dependency survives in the generated hot loop. */ +#define DISPATCH_I_OPCODE(T, NULL_SENT, base, start, end, acc, has_nulls, idx, opcode) \ + do { \ + switch (opcode) { \ + case OP_SUM: DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_NEED_SUM); break; \ + case OP_PROD: DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_NEED_PROD); break; \ + case OP_ALL: DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_NEED_ZERO); break; \ + case OP_ANY: DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_MASK_ANY); break; \ + case OP_MIN: DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_MASK_MIN); break; \ + case OP_MAX: DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_MASK_MAX); break; \ + case OP_AVG: DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_MASK_AVG_I); break; \ + case OP_VAR: case OP_VAR_POP: case OP_STDDEV: case OP_STDDEV_POP: \ + DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_MASK_STATS_I); break; \ + case OP_FIRST: DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_MASK_FIRST); break; \ + case OP_LAST: DISPATCH_I(T, NULL_SENT, base, start, end, acc, has_nulls, idx, RED_MASK_LAST); break; \ + default: break; \ + } \ + } while (0) + +#define DISPATCH_BITMAP_I_OPCODE(T, input, base, start, end, acc, has_nulls, idx, opcode) \ + do { \ + switch (opcode) { \ + case OP_SUM: DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_NEED_SUM); break; \ + case OP_PROD: DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_NEED_PROD); break; \ + case OP_ALL: DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_NEED_ZERO); break; \ + case OP_ANY: DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_MASK_ANY); break; \ + case OP_MIN: DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_MASK_MIN); break; \ + case OP_MAX: DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_MASK_MAX); break; \ + case OP_AVG: DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_MASK_AVG_I); break; \ + case OP_VAR: case OP_VAR_POP: case OP_STDDEV: case OP_STDDEV_POP: \ + DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_MASK_STATS_I); break; \ + case OP_FIRST: DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_MASK_FIRST); break; \ + case OP_LAST: DISPATCH_BITMAP_I(T, input, base, start, end, acc, has_nulls, idx, RED_MASK_LAST); break; \ + default: break; \ + } \ + } while (0) + +#define DISPATCH_F_OPCODE(T, base, start, end, acc, has_nulls, idx, opcode) \ + do { \ + switch (opcode) { \ + case OP_SUM: DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_NEED_SUM); break; \ + case OP_PROD: DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_NEED_PROD); break; \ + case OP_ALL: DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_NEED_ZERO); break; \ + case OP_ANY: DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_MASK_ANY); break; \ + case OP_MIN: DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_MASK_MIN); break; \ + case OP_MAX: DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_MASK_MAX); break; \ + case OP_AVG: DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_MASK_AVG_F); break; \ + case OP_VAR: case OP_VAR_POP: case OP_STDDEV: case OP_STDDEV_POP: \ + DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_MASK_STATS_F); break; \ + case OP_FIRST: DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_MASK_FIRST); break; \ + case OP_LAST: DISPATCH_F(T, base, start, end, acc, has_nulls, idx, RED_MASK_LAST); break; \ + default: break; \ + } \ + } while (0) + +#define REDUCE_SYM_EXTREME(input, base, start, end, acc, idx, dom, HAS_NULLS, HAS_IDX, WANT_MIN) \ + do { \ + for (int64_t i = start; i < end; i++) { \ + int64_t row = (HAS_IDX) ? (idx)[i] : i; \ + int64_t v = read_col_i64(base, row, (input)->type, (input)->attrs); \ + if ((HAS_NULLS) && v == 0) continue; \ + if ((acc)->cnt == 0) { \ + if (WANT_MIN) (acc)->min_i = v; else (acc)->max_i = v; \ + } else if (WANT_MIN) { \ + if (sym_lex_lt(dom, v, (acc)->min_i)) (acc)->min_i = v; \ + } else { \ + if (sym_lex_gt(dom, v, (acc)->max_i)) (acc)->max_i = v; \ + } \ + (acc)->cnt++; \ + } \ } while (0) -#define DISPATCH_F(T, base, start, end, acc, has_nulls, idx) \ +#define DISPATCH_SYM_EXTREME(input, base, start, end, acc, has_nulls, idx, dom, WANT_MIN) \ do { \ if (!(has_nulls) && !(idx)) \ - REDUCE_LOOP_F(T, base, start, end, acc, 0, 0, idx); \ + REDUCE_SYM_EXTREME(input, base, start, end, acc, idx, dom, 0, 0, WANT_MIN); \ else if (!(has_nulls)) \ - REDUCE_LOOP_F(T, base, start, end, acc, 0, 1, idx); \ + REDUCE_SYM_EXTREME(input, base, start, end, acc, idx, dom, 0, 1, WANT_MIN); \ else if (!(idx)) \ - REDUCE_LOOP_F(T, base, start, end, acc, 1, 0, idx); \ + REDUCE_SYM_EXTREME(input, base, start, end, acc, idx, dom, 1, 0, WANT_MIN); \ else \ - REDUCE_LOOP_F(T, base, start, end, acc, 1, 1, idx); \ + REDUCE_SYM_EXTREME(input, base, start, end, acc, idx, dom, 1, 1, WANT_MIN); \ } while (0) static void reduce_range(ray_t* input, int64_t start, int64_t end, reduce_acc_t* acc, bool has_nulls, - const int64_t* idx) { + const int64_t* idx, uint16_t opcode) { void* base = ray_data(input); switch (input->type) { - case RAY_BOOL: case RAY_U8: { - /* BOOL/U8 are non-nullable; has_nulls is always false here, - * so the per-element null check is dead code in practice. */ - const uint8_t* d = (const uint8_t*)base; - for (int64_t i = start; i < end; i++) { - int64_t row = idx ? idx[i] : i; - if (has_nulls && ray_vec_is_null(input, row)) { acc->null_count++; continue; } - int64_t v = (int64_t)d[row]; - acc->sum_i = (int64_t)((uint64_t)acc->sum_i + (uint64_t)v); - acc->sum_sq_i = (int64_t)((uint64_t)acc->sum_sq_i + (uint64_t)v * (uint64_t)v); - acc->prod_i = (int64_t)((uint64_t)acc->prod_i * (uint64_t)v); - acc->sum_d += (double)v; - if (v == 0) acc->zero_count++; - if (v < acc->min_i) acc->min_i = v; - if (v > acc->max_i) acc->max_i = v; - if (!acc->has_first) { acc->first_i = v; acc->has_first = true; } - acc->last_i = v; acc->cnt++; - } - break; - } + case RAY_BOOL: case RAY_U8: + DISPATCH_BITMAP_I_OPCODE(uint8_t, input, base, start, end, acc, + has_nulls, idx, opcode); break; case RAY_I16: - DISPATCH_I(int16_t, NULL_I16, base, start, end, acc, has_nulls, idx); break; + DISPATCH_I_OPCODE(int16_t, NULL_I16, base, start, end, acc, + has_nulls, idx, opcode); break; case RAY_I32: case RAY_DATE: case RAY_TIME: - DISPATCH_I(int32_t, NULL_I32, base, start, end, acc, has_nulls, idx); break; + DISPATCH_I_OPCODE(int32_t, NULL_I32, base, start, end, acc, + has_nulls, idx, opcode); break; case RAY_I64: case RAY_TIMESTAMP: - DISPATCH_I(int64_t, NULL_I64, base, start, end, acc, has_nulls, idx); break; + DISPATCH_I_OPCODE(int64_t, NULL_I64, base, start, end, acc, + has_nulls, idx, opcode); break; case RAY_F32: - DISPATCH_F(float, base, start, end, acc, has_nulls, idx); break; + DISPATCH_F_OPCODE(float, base, start, end, acc, has_nulls, idx, opcode); break; case RAY_F64: - DISPATCH_F(double, base, start, end, acc, has_nulls, idx); break; + DISPATCH_F_OPCODE(double, base, start, end, acc, has_nulls, idx, opcode); break; case RAY_SYM: { /* Adaptive-width SYM columns — read_col_i64 produces the i64 * sym id; id 0 is the canonical null sym (interned empty string @@ -386,55 +534,12 @@ static void reduce_range(ray_t* input, int64_t start, int64_t end, * id. Same 4-way dispatch to eliminate the per-element * null/idx branches. */ struct ray_sym_domain_s* dom = ray_sym_vec_domain(input); - if (!has_nulls && !idx) { - for (int64_t i = start; i < end; i++) { - int64_t v = read_col_i64(base, i, input->type, input->attrs); - acc->sum_i += v; acc->sum_sq_i += v * v; - acc->prod_i = (int64_t)((uint64_t)acc->prod_i * (uint64_t)v); - if (acc->cnt == 0) { acc->min_i = v; acc->max_i = v; } - else { if (sym_lex_lt(dom, v, acc->min_i)) acc->min_i = v; - if (sym_lex_gt(dom, v, acc->max_i)) acc->max_i = v; } - if (!acc->has_first) { acc->first_i = v; acc->has_first = true; } - acc->last_i = v; acc->cnt++; - } - } else if (!has_nulls) { - for (int64_t i = start; i < end; i++) { - int64_t row = idx[i]; - int64_t v = read_col_i64(base, row, input->type, input->attrs); - acc->sum_i += v; acc->sum_sq_i += v * v; - acc->prod_i = (int64_t)((uint64_t)acc->prod_i * (uint64_t)v); - if (acc->cnt == 0) { acc->min_i = v; acc->max_i = v; } - else { if (sym_lex_lt(dom, v, acc->min_i)) acc->min_i = v; - if (sym_lex_gt(dom, v, acc->max_i)) acc->max_i = v; } - if (!acc->has_first) { acc->first_i = v; acc->has_first = true; } - acc->last_i = v; acc->cnt++; - } - } else if (!idx) { - for (int64_t i = start; i < end; i++) { - int64_t v = read_col_i64(base, i, input->type, input->attrs); - if (v == 0) { acc->null_count++; continue; } - acc->sum_i += v; acc->sum_sq_i += v * v; - acc->prod_i = (int64_t)((uint64_t)acc->prod_i * (uint64_t)v); - if (acc->cnt == 0) { acc->min_i = v; acc->max_i = v; } - else { if (sym_lex_lt(dom, v, acc->min_i)) acc->min_i = v; - if (sym_lex_gt(dom, v, acc->max_i)) acc->max_i = v; } - if (!acc->has_first) { acc->first_i = v; acc->has_first = true; } - acc->last_i = v; acc->cnt++; - } - } else { - for (int64_t i = start; i < end; i++) { - int64_t row = idx[i]; - int64_t v = read_col_i64(base, row, input->type, input->attrs); - if (v == 0) { acc->null_count++; continue; } - acc->sum_i += v; acc->sum_sq_i += v * v; - acc->prod_i = (int64_t)((uint64_t)acc->prod_i * (uint64_t)v); - if (acc->cnt == 0) { acc->min_i = v; acc->max_i = v; } - else { if (sym_lex_lt(dom, v, acc->min_i)) acc->min_i = v; - if (sym_lex_gt(dom, v, acc->max_i)) acc->max_i = v; } - if (!acc->has_first) { acc->first_i = v; acc->has_first = true; } - acc->last_i = v; acc->cnt++; - } - } + if (opcode == OP_MIN) + DISPATCH_SYM_EXTREME(input, base, start, end, acc, has_nulls, + idx, dom, 1); + else if (opcode == OP_MAX) + DISPATCH_SYM_EXTREME(input, base, start, end, acc, has_nulls, + idx, dom, 0); break; } default: break; @@ -447,43 +552,86 @@ typedef struct { reduce_acc_t* accs; /* one per worker */ bool has_nulls; const int64_t* idx; /* NULL = no selection; else int64[total_pass] */ + uint16_t opcode; } par_reduce_ctx_t; static void par_reduce_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { par_reduce_ctx_t* c = (par_reduce_ctx_t*)ctx; reduce_range(c->input, start, end, &c->accs[worker_id], - c->has_nulls, c->idx); + c->has_nulls, c->idx, c->opcode); } static void reduce_merge(reduce_acc_t* dst, const reduce_acc_t* src, int8_t in_type, - struct ray_sym_domain_s* sym_dom) { - if (in_type == RAY_F64 || in_type == RAY_F32) { - dst->sum_f += src->sum_f; - dst->sum_sq_f += src->sum_sq_f; - dst->prod_f *= src->prod_f; - if (src->min_f < dst->min_f) dst->min_f = src->min_f; - if (src->max_f > dst->max_f) dst->max_f = src->max_f; - } else { - /* Defined unsigned wrap — matches REDUCE_LOOP_I's per-row path. */ - dst->sum_i = (int64_t)((uint64_t)dst->sum_i + (uint64_t)src->sum_i); - dst->sum_sq_i = (int64_t)((uint64_t)dst->sum_sq_i + (uint64_t)src->sum_sq_i); - dst->prod_i = (int64_t)((uint64_t)dst->prod_i * (uint64_t)src->prod_i); - dst->sum_d += src->sum_d; - if (in_type == RAY_SYM) { - /* Lex compare for SYM min/max (see sym_lex_lt). */ - if (src->cnt > 0) { - if (dst->cnt == 0) { dst->min_i = src->min_i; dst->max_i = src->max_i; } - else { if (sym_lex_lt(sym_dom, src->min_i, dst->min_i)) dst->min_i = src->min_i; - if (sym_lex_gt(sym_dom, src->max_i, dst->max_i)) dst->max_i = src->max_i; } - } + struct ray_sym_domain_s* sym_dom, uint16_t opcode) { + bool fp = in_type == RAY_F64 || in_type == RAY_F32; + switch (opcode) { + case OP_SUM: + if (fp) dst->sum_f += src->sum_f; + else dst->sum_i = (int64_t)((uint64_t)dst->sum_i + (uint64_t)src->sum_i); + break; + case OP_PROD: + if (fp) dst->prod_f *= src->prod_f; + else dst->prod_i = (int64_t)((uint64_t)dst->prod_i * (uint64_t)src->prod_i); + break; + case OP_ALL: + dst->zero_count += src->zero_count; + break; + case OP_ANY: + dst->zero_count += src->zero_count; + dst->cnt += src->cnt; + break; + case OP_MIN: + if (src->cnt > 0) { + if (dst->cnt == 0) { + if (fp) dst->min_f = src->min_f; + else dst->min_i = src->min_i; + } else if (fp) { + if (src->min_f < dst->min_f) dst->min_f = src->min_f; + } else if (in_type == RAY_SYM) { + if (sym_lex_lt(sym_dom, src->min_i, dst->min_i)) dst->min_i = src->min_i; + } else if (src->min_i < dst->min_i) { + dst->min_i = src->min_i; + } + dst->cnt += src->cnt; + } + break; + case OP_MAX: + if (src->cnt > 0) { + if (dst->cnt == 0) { + if (fp) dst->max_f = src->max_f; + else dst->max_i = src->max_i; + } else if (fp) { + if (src->max_f > dst->max_f) dst->max_f = src->max_f; + } else if (in_type == RAY_SYM) { + if (sym_lex_gt(sym_dom, src->max_i, dst->max_i)) dst->max_i = src->max_i; + } else if (src->max_i > dst->max_i) { + dst->max_i = src->max_i; + } + dst->cnt += src->cnt; + } + break; + case OP_AVG: + if (fp) dst->sum_f += src->sum_f; + else dst->sum_d += src->sum_d; + dst->cnt += src->cnt; + break; + case OP_VAR: case OP_VAR_POP: case OP_STDDEV: case OP_STDDEV_POP: + if (fp) { + dst->sum_f += src->sum_f; + dst->sum_sq_f += src->sum_sq_f; } else { - if (src->min_i < dst->min_i) dst->min_i = src->min_i; - if (src->max_i > dst->max_i) dst->max_i = src->max_i; + dst->sum_d += src->sum_d; + dst->sum_sq_i = (int64_t)((uint64_t)dst->sum_sq_i + + (uint64_t)src->sum_sq_i); } + dst->cnt += src->cnt; + break; + case OP_FIRST: case OP_LAST: + dst->cnt += src->cnt; + break; + default: + break; } - dst->cnt += src->cnt; - dst->null_count += src->null_count; - dst->zero_count += src->zero_count; /* reduce_merge does not merge first/last; caller handles these separately. * Since workers process sequential ranges, worker 0's first is the global first, * and the last worker's last is the global last. */ @@ -1027,6 +1175,300 @@ ray_t* exec_count_distinct(ray_graph_t* g, ray_op_t* op, ray_t* input) { return ray_i64(total_distinct); } +/* ════════════════════════════════════════════════════════════════════ + * Parallel distinct values — first-occurrence row ids. + * + * Same three-pass radix layout as exec_count_distinct above (histogram + * → scatter → per-partition dedup), except the scatter carries the row + * id alongside each value and the dedup marks first occurrences in a + * shared byte array instead of counting. A given value lands in + * exactly one partition, so each row id is claimed by at most one + * task — the byte array needs no atomics. Partition slices are in + * ascending row order (cursors are prefix-summed over tasks in task + * order, tasks scan rows in order), so "first hit in the slice" is the + * globally first occurrence, and the final sequential sweep of the + * byte array yields ids in first-appearance order — identical to the + * eager hashset path's contract. + * ════════════════════════════════════════════════════════════════════ */ + +typedef struct { + const void* base; + int64_t* out_buf; /* partitioned values (output) */ + int64_t* rid_buf; /* partitioned row ids (output) */ + int64_t* cursor; /* per-task × P; advances per scatter */ + uint64_t p_mask; + int64_t grain; + int64_t total; + uint8_t is_f64; + int8_t type; +} dv_scatter_ctx_t; + +static void dv_scatter_fn(void* ctx, uint32_t worker_id, + int64_t start, int64_t end) { + (void)worker_id; + (void)end; + dv_scatter_ctx_t* x = (dv_scatter_ctx_t*)ctx; + int64_t task_idx = start; + int64_t row_start = task_idx * x->grain; + int64_t row_end = row_start + x->grain; + if (row_end > x->total) row_end = x->total; + int64_t* cur = x->cursor + (size_t)task_idx * (x->p_mask + 1); + int64_t* out = x->out_buf; + int64_t* rid = x->rid_buf; + const void* base = x->base; + uint64_t p_mask = x->p_mask; + #define DV_SCATTER_BODY(LOAD) \ + for (int64_t i = row_start; i < row_end; i++) { \ + int64_t val = (LOAD); \ + uint64_t h = (uint64_t)val * CD_HASH_K1; \ + h ^= h >> 33; \ + uint64_t p = (h ^ (h >> 33)) & p_mask; \ + int64_t c = cur[p]++; \ + out[c] = val; \ + rid[c] = i; \ + } + if (x->is_f64) { + const double* d = (const double*)base; + for (int64_t i = row_start; i < row_end; i++) { + double fv = d[i]; + if (fv != fv) fv = (double)NAN; + else fv = clear_neg_zero(fv); + int64_t val; + memcpy(&val, &fv, sizeof(int64_t)); + uint64_t h = (uint64_t)val * CD_HASH_K1; + h ^= h >> 33; + uint64_t p = (h ^ (h >> 33)) & p_mask; + int64_t c = cur[p]++; + out[c] = val; + rid[c] = i; + } + } else if (x->type == RAY_I64 || x->type == RAY_TIMESTAMP) { + const int64_t* d = (const int64_t*)base; + DV_SCATTER_BODY(d[i]) + } else if (x->type == RAY_I32 || x->type == RAY_DATE || x->type == RAY_TIME) { + const int32_t* d = (const int32_t*)base; + DV_SCATTER_BODY(d[i]) + } else if (x->type == RAY_I16) { + const int16_t* d = (const int16_t*)base; + DV_SCATTER_BODY(d[i]) + } + #undef DV_SCATTER_BODY +} + +typedef struct { + const int64_t* values; /* partitioned values */ + const int64_t* rids; /* partitioned row ids */ + const int64_t* part_off; /* P+1 partition bounds */ + int64_t* part_count; /* OUT: per-partition distinct count (-1 = oom) */ + uint8_t* first; /* OUT: len bytes; 1 = first occurrence */ +} dv_part_ctx_t; + +static void dv_part_dedup_fn(void* ctx, uint32_t worker_id, + int64_t start, int64_t end) { + (void)worker_id; + dv_part_ctx_t* x = (dv_part_ctx_t*)ctx; + for (int64_t p = start; p < end; p++) { + int64_t off = x->part_off[p]; + int64_t cnt = x->part_off[p + 1] - off; + if (cnt == 0) { x->part_count[p] = 0; continue; } + + uint64_t cap = (uint64_t)cnt * 2; + if (cap < 32) cap = 32; + uint64_t c = 1; + while (c && c < cap) c <<= 1; + if (!c) { x->part_count[p] = -1; continue; } + cap = c; + uint64_t mask = cap - 1; + int cd_shift = 64 - __builtin_ctzll(cap); + + ray_t* set_hdr = NULL; + ray_t* used_hdr = NULL; + int64_t* set = (int64_t*)scratch_alloc (&set_hdr, + (size_t)cap * sizeof(int64_t)); + uint8_t* used = (uint8_t*)scratch_calloc(&used_hdr, + (size_t)cap * sizeof(uint8_t)); + if (!set || !used) { + if (set_hdr) scratch_free(set_hdr); + if (used_hdr) scratch_free(used_hdr); + x->part_count[p] = -1; + continue; + } + + const int64_t* vals = x->values + off; + const int64_t* rids = x->rids + off; + int64_t count = 0; + for (int64_t j = 0; j < cnt; j++) { + int64_t val = vals[j]; + uint64_t h = (uint64_t)val * CD_HASH_K1; + uint64_t slot = h >> cd_shift; /* Fibonacci hash: high bits */ + while (used[slot]) { + if (set[slot] == val) goto dv_part_next; + slot = (slot + 1) & mask; + } + set[slot] = val; + used[slot] = 1; + x->first[rids[j]] = 1; + count++; + dv_part_next:; + } + scratch_free(set_hdr); + scratch_free(used_hdr); + x->part_count[p] = count; + } +} + +ray_t* distinct_radix_first_ids(ray_t* input) { + if (!input || RAY_IS_ERR(input)) return NULL; + + int8_t in_type = input->type; + int64_t len = input->len; + + switch (in_type) { + case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + break; + case RAY_F64: + /* The kernel canonicalizes every NaN to one value. The eager + * hashset only does that under the HAS_NULLS gate (ungated NaNs + * are pairwise-distinct there) — bail so behavior is identical. */ + if (!(input->attrs & RAY_ATTR_HAS_NULLS)) return NULL; + break; + default: + return NULL; + } + + ray_pool_t* pool = ray_pool_get(); + if (!pool || len < (1 << 16)) return NULL; + + uint32_t nw = ray_pool_total_workers(pool); + uint32_t p_bits; + if (nw <= 8) p_bits = 4; + else if (nw <= 32) p_bits = 5; + else p_bits = 6; + uint64_t P = (uint64_t)1 << p_bits; + uint64_t p_mask = P - 1; + + int64_t grain = (int64_t)RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS; + if (grain <= 0) grain = 8192; + int64_t n_tasks_64 = (len + grain - 1) / grain; + if (n_tasks_64 <= 0 || n_tasks_64 > (1u << 16)) return NULL; + uint32_t n_tasks = (uint32_t)n_tasks_64; + + void* base = ray_data(input); + + /* Pass 1: per-task histogram (identical to exec_count_distinct's). */ + ray_t* hist_hdr = NULL; + int64_t* hist = (int64_t*)scratch_calloc(&hist_hdr, + (size_t)P * n_tasks * sizeof(int64_t)); + if (!hist) return ray_error("oom", NULL); + cd_count_ctx_t hctx = { + .base = base, .counts = hist, + .p_bits = p_bits, .p_mask = p_mask, + .grain = grain, .total = len, + .stride_log2 = 0, .is_f64 = (in_type == RAY_F64), + .type = in_type, .attrs = input->attrs, + }; + ray_pool_dispatch_n(pool, cd_hist_fn, &hctx, n_tasks); + + ray_t* off_hdr = NULL; + int64_t* part_off = (int64_t*)scratch_alloc(&off_hdr, + (size_t)(P + 1) * sizeof(int64_t)); + if (!part_off) { scratch_free(hist_hdr); return ray_error("oom", NULL); } + ray_t* cur_hdr = NULL; + int64_t* cursor = (int64_t*)scratch_alloc(&cur_hdr, + (size_t)P * n_tasks * sizeof(int64_t)); + if (!cursor) { + scratch_free(off_hdr); scratch_free(hist_hdr); + return ray_error("oom", NULL); + } + + int64_t total = 0; + for (uint64_t p = 0; p < P; p++) { + part_off[p] = total; + for (uint32_t t = 0; t < n_tasks; t++) { + cursor[(size_t)t * P + p] = total; + total += hist[(size_t)t * P + p]; + } + } + part_off[P] = total; + if (total != len) { + scratch_free(cur_hdr); scratch_free(off_hdr); scratch_free(hist_hdr); + return ray_error("nyi", "distinct: histogram mismatch"); + } + + /* Pass 2: scatter (value, row id) pairs. */ + ray_t* buf_hdr = NULL; + int64_t* out_buf = (int64_t*)scratch_alloc(&buf_hdr, + (size_t)len * sizeof(int64_t)); + ray_t* rid_hdr = NULL; + int64_t* rid_buf = (int64_t*)scratch_alloc(&rid_hdr, + (size_t)len * sizeof(int64_t)); + if (!out_buf || !rid_buf) { + if (buf_hdr) scratch_free(buf_hdr); + if (rid_hdr) scratch_free(rid_hdr); + scratch_free(cur_hdr); scratch_free(off_hdr); scratch_free(hist_hdr); + return ray_error("oom", NULL); + } + dv_scatter_ctx_t sctx = { + .base = base, .out_buf = out_buf, .rid_buf = rid_buf, .cursor = cursor, + .p_mask = p_mask, .grain = grain, .total = len, + .is_f64 = (in_type == RAY_F64), .type = in_type, + }; + ray_pool_dispatch_n(pool, dv_scatter_fn, &sctx, n_tasks); + + /* Pass 3: per-partition dedup, marking first occurrences. */ + ray_t* first_hdr = NULL; + uint8_t* first = (uint8_t*)scratch_calloc(&first_hdr, (size_t)len); + ray_t* pcnt_hdr = NULL; + int64_t* part_count = first ? (int64_t*)scratch_alloc(&pcnt_hdr, + (size_t)P * sizeof(int64_t)) + : NULL; + if (!first || !part_count) { + if (first_hdr) scratch_free(first_hdr); + if (pcnt_hdr) scratch_free(pcnt_hdr); + scratch_free(rid_hdr); scratch_free(buf_hdr); scratch_free(cur_hdr); + scratch_free(off_hdr); scratch_free(hist_hdr); + return ray_error("oom", NULL); + } + dv_part_ctx_t dctx = { + .values = out_buf, .rids = rid_buf, .part_off = part_off, + .part_count = part_count, .first = first, + }; + ray_pool_dispatch_n(pool, dv_part_dedup_fn, &dctx, (uint32_t)P); + + int64_t total_distinct = 0; + for (uint64_t p = 0; p < P; p++) { + if (part_count[p] < 0) { + scratch_free(pcnt_hdr); scratch_free(first_hdr); + scratch_free(rid_hdr); scratch_free(buf_hdr); scratch_free(cur_hdr); + scratch_free(off_hdr); scratch_free(hist_hdr); + return ray_error("oom", NULL); + } + total_distinct += part_count[p]; + } + + scratch_free(pcnt_hdr); scratch_free(rid_hdr); scratch_free(buf_hdr); + scratch_free(cur_hdr); scratch_free(off_hdr); scratch_free(hist_hdr); + + /* Sweep the byte array in row order — first-appearance order ids. */ + ray_t* ids = ray_vec_new(RAY_I64, total_distinct); + if (!ids || RAY_IS_ERR(ids)) { + scratch_free(first_hdr); + return ids ? ids : ray_error("oom", NULL); + } + int64_t* out_ids = (int64_t*)ray_data(ids); + int64_t k = 0; + for (int64_t i = 0; i < len; i++) + if (first[i]) out_ids[k++] = i; + ids->len = k; + scratch_free(first_hdr); + if (k != total_distinct) { + ray_release(ids); + return ray_error("nyi", "distinct: first-occurrence sweep mismatch"); + } + return ids; +} + /* ════════════════════════════════════════════════════════════════════ * Parallel partitioned grouped count(distinct). * @@ -2707,13 +3149,20 @@ ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input) { if (g && g->selection) { ray_rowsel_t* sm = ray_rowsel_meta(g->selection); if (sm->nrows == len) { - sel_idx_block = ray_rowsel_to_indices(g->selection); - if (!sel_idx_block) return ray_error("oom", NULL); - sel_idx = (const int64_t*)ray_data(sel_idx_block); scan_n = sm->total_pass; + /* COUNT needs only the selected cardinality. Do not materialise + * indices—and, below, do not scan the input column at all. */ + if (op->opcode != OP_COUNT) { + sel_idx_block = ray_rowsel_to_indices(g->selection); + if (!sel_idx_block) return ray_error("oom", NULL); + sel_idx = (const int64_t*)ray_data(sel_idx_block); + } } } + if (op->opcode == OP_COUNT) + return ray_i64(scan_n); + /* Wide elements and boxed LIST cells cannot use the 8-byte reduce * accumulators; resolve their supported operations by materialising the * winning row instead. COUNT keeps the generic length-based path. */ @@ -2762,7 +3211,8 @@ ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input) { for (uint32_t i = 0; i < nw; i++) reduce_acc_init(&accs[i]); par_reduce_ctx_t ctx = { .input = input, .accs = accs, - .has_nulls = has_nulls, .idx = sel_idx }; + .has_nulls = has_nulls, .idx = sel_idx, + .opcode = op->opcode }; ray_pool_dispatch(pool, par_reduce_fn, &ctx, scan_n); /* Merge: worker 0 is the base, merge the rest in order */ @@ -2770,8 +3220,8 @@ ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input) { reduce_acc_init(&merged); merged = accs[0]; for (uint32_t i = 1; i < nw; i++) { - if (!accs[i].has_first) continue; - reduce_merge(&merged, &accs[i], in_type, ray_sym_vec_domain(input)); + reduce_merge(&merged, &accs[i], in_type, ray_sym_vec_domain(input), + op->opcode); } /* first = accs[first worker with data], last = accs[last worker with data] */ for (uint32_t i = 0; i < nw; i++) { @@ -2828,7 +3278,7 @@ ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input) { reduce_acc_t acc; reduce_acc_init(&acc); - reduce_range(input, 0, scan_n, &acc, has_nulls, sel_idx); + reduce_range(input, 0, scan_n, &acc, has_nulls, sel_idx, op->opcode); if (sel_idx_block) ray_release(sel_idx_block); switch (op->opcode) { diff --git a/src/ops/idxop.c b/src/ops/idxop.c index 130769648..97dd5ff01 100644 --- a/src/ops/idxop.c +++ b/src/ops/idxop.c @@ -453,6 +453,7 @@ static ray_err_t chunk_zone_scan_int(ray_t* v, ray_index_t* ix, const uint8_t* base = (const uint8_t*)ray_data(v); for (uint32_t g = 0; g < n_chunks; g++) { + if (RAY_UNLIKELY(ray_interrupted())) return RAY_ERR_CANCEL; int64_t s = (int64_t)g * csz; int64_t e = s + csz; if (e > n) e = n; int64_t mn = INT64_MAX, mx = INT64_MIN; @@ -491,6 +492,7 @@ static ray_err_t chunk_zone_scan_float(ray_t* v, ray_index_t* ix, const uint8_t* base = (const uint8_t*)ray_data(v); for (uint32_t g = 0; g < n_chunks; g++) { + if (RAY_UNLIKELY(ray_interrupted())) return RAY_ERR_CANCEL; int64_t s = (int64_t)g * csz; int64_t e = s + csz; if (e > n) e = n; double mn = INFINITY, mx = -INFINITY; @@ -965,6 +967,12 @@ ray_t* ray_index_attach_hash(ray_t** vp) { int64_t n_keys = 0, n_groups = 0; for (int64_t i = 0; i < n; i++) { + if (RAY_UNLIKELY((i & 0xFFFF) == 0 && ray_interrupted())) { + scratch_free(btab_hdr); + scratch_free(rgid_hdr); + ray_release(gkeys); + return ray_error("cancel", "interrupted"); + } if (ray_vec_is_null(v, i)) { rgid[i] = -1; continue; } /* SYM is null-free → always false */ int64_t kw = (v->type == RAY_SYM) ? ray_read_sym(base, i, RAY_SYM, v->attrs) /* domain id, width-aware */ @@ -1003,14 +1011,26 @@ ray_t* ray_index_attach_hash(ray_t** vp) { int64_t* of = (int64_t*)ray_data(offs); int64_t* rw = (int64_t*)ray_data(rows); memset(of, 0, (size_t)(n_groups + 1) * sizeof(int64_t)); - for (int64_t i = 0; i < n; i++) + for (int64_t i = 0; i < n; i++) { + if (RAY_UNLIKELY((i & 0xFFFF) == 0 && ray_interrupted())) + goto hash_cancel_csr; if (rgid[i] >= 0) of[rgid[i] + 1]++; - for (int64_t g = 0; g < n_groups; g++) + } + for (int64_t g = 0; g < n_groups; g++) { + if (RAY_UNLIKELY((g & 0xFFFF) == 0 && ray_interrupted())) + goto hash_cancel_csr; of[g + 1] += of[g]; - for (int64_t i = 0; i < n; i++) + } + for (int64_t i = 0; i < n; i++) { + if (RAY_UNLIKELY((i & 0xFFFF) == 0 && ray_interrupted())) + goto hash_cancel_csr; if (rgid[i] >= 0) rw[of[rgid[i]]++] = i; - for (int64_t g = n_groups; g > 0; g--) + } + for (int64_t g = n_groups; g > 0; g--) { + if (RAY_UNLIKELY((g & 0xFFFF) == 0 && ray_interrupted())) + goto hash_cancel_csr; of[g] = of[g - 1]; + } of[0] = 0; scratch_free(rgid_hdr); @@ -1027,6 +1047,11 @@ ray_t* ray_index_attach_hash(ray_t** vp) { int64_t* tbl = (int64_t*)ray_data(table); memset(tbl, 0, (size_t)cap * sizeof(int64_t)); for (int64_t g = 0; g < n_groups; g++) { + if (RAY_UNLIKELY((g & 0xFFFF) == 0 && ray_interrupted())) { + ray_release(table); ray_release(gkeys); + ray_release(offs); ray_release(rows); + return ray_error("cancel", "interrupted"); + } uint64_t slot = mix64((uint64_t)gk[g]) & mask; while (tbl[slot] != 0) slot = (slot + 1) & mask; tbl[slot] = g + 1; @@ -1049,6 +1074,13 @@ ray_t* ray_index_attach_hash(ray_t** vp) { ix->u.hash.order_sym = -1; return attach_finalize(v, idx); + +hash_cancel_csr: + scratch_free(rgid_hdr); + ray_release(gkeys); + ray_release(offs); + ray_release(rows); + return ray_error("cancel", "interrupted"); } /* -------------------------------------------------------------------------- diff --git a/src/ops/internal.h b/src/ops/internal.h index 800faf4f4..9699add54 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -1045,6 +1045,14 @@ ray_t* exec_window_join(ray_graph_t* g, ray_op_t* op, ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input); ray_t* exec_count_distinct(ray_graph_t* g, ray_op_t* op, ray_t* input); +/* Parallel distinct for large fixed-width columns: radix-partitioned + * dedup (exec_count_distinct's layout) returning an I64 vec of + * first-occurrence row ids in first-appearance order. Returns NULL + * when the kernel doesn't apply (unsupported type, small input, no + * pool) — caller falls back to the eager hashset. Errors are + * RAY_IS_ERR ray_t*. */ +ray_t* distinct_radix_first_ids(ray_t* input); + /* Single-pass per-group count(distinct). Returns I64 vec of length * n_groups, or NULL if `src->type` isn't a supported scalar/SYM type * (caller falls back to per-group exec_count_distinct). Errors are diff --git a/src/ops/temporal.c b/src/ops/temporal.c index 00bbbcb61..9ea07c88a 100644 --- a/src/ops/temporal.c +++ b/src/ops/temporal.c @@ -101,16 +101,67 @@ static int64_t rte_extract_one(int64_t us, int field) { * rest of the runtime). The previous version of this helper treated * TIMESTAMP as µs, which made (yyyy ts) decode to absurd years (26204 * on 2024-03-15) — a 1000× unit mismatch. */ -static inline int64_t rte_to_us(int8_t type, int64_t raw) { - if (type == RAY_DATE || type == -RAY_DATE) return raw * RTE_USEC_PER_DAY; - if (type == RAY_TIME || type == -RAY_TIME) return raw * 1000LL; - /* RAY_TIMESTAMP / -RAY_TIMESTAMP: ns → µs (floor toward -inf). */ - return raw >= 0 ? raw / 1000LL - : -(((-raw) + 999LL) / 1000LL); +static inline bool rte_to_us_ck(int8_t type, int64_t raw, int64_t* out) { + if (type == RAY_DATE || type == -RAY_DATE) { + /* DATE is int32 days, so `raw` can be as large as INT32_MAX — a date + * hundreds of millennia out. day * µs-per-day then overflows int64 + * (UBSan). Such a value is simply not representable in the µs domain + * the extract/truncate math uses; report it so the caller emits a + * null, consistent with how a null input is handled. */ + if (raw > INT64_MAX / RTE_USEC_PER_DAY || raw < INT64_MIN / RTE_USEC_PER_DAY) + return false; + *out = raw * RTE_USEC_PER_DAY; + return true; + } + if (type == RAY_TIME || type == -RAY_TIME) { *out = raw * 1000LL; return true; } + /* RAY_TIMESTAMP / -RAY_TIMESTAMP: ns → µs, floor toward -inf. Done with + * truncate-then-adjust rather than negating: the old `-((-raw)+999)/1000` + * overflowed for `raw` within 999 of INT64_MIN (the low edge of the + * representable range). */ + int64_t q = raw / 1000LL; + if (raw % 1000LL != 0 && raw < 0) q--; + *out = q; + return true; +} + +/* Extract one field from a raw temporal slot. Returns false when the source + * value is not representable in the µs extract domain (caller emits null). */ +static inline bool rte_extract_elem(int8_t t, int64_t raw, int field, int64_t* out) { + int64_t us; + if (!rte_to_us_ck(t, raw, &us)) return false; + *out = rte_extract_one(us, field); + return true; } -/* Inverse of rte_to_us for TIMESTAMP output paths (truncate). */ -static inline int64_t rte_us_to_ts_raw(int64_t us) { return us * 1000LL; } +/* Truncate a raw temporal slot to a TIMESTAMP-ns bucket. Returns false when + * the source, or the bucketed result, is outside the int64 nanosecond range + * (caller emits null): a value hundreds of millennia out cannot be a + * TIMESTAMP. The floor uses overflow-safe arithmetic and the ACTUAL bucketed + * result is range-checked (mirroring exec_date_trunc), so a value whose + * floored bucket is still representable — e.g. the low day boundary + * 1707.09.23 — round-trips instead of being rejected by a pre-floor headroom + * that disagreed with the DAG path. */ +static inline bool rte_trunc_elem(int8_t t, int64_t raw, int64_t bucket, int64_t* out_ns) { + int64_t us; + if (!rte_to_us_ck(t, raw, &us)) return false; + /* Floor `us` to the bucket boundary (toward -inf). `us - r` truncates + * toward zero (magnitude only shrinks, never overflows); a negative + * remainder needs one more bucket subtracted to floor toward -inf — the + * one step that can underflow (a DATE reaches `us` across the full µs + * range), so guard it. */ + int64_t r = us % bucket; + int64_t out_us = us - r; + if (r < 0) { + if (out_us < INT64_MIN + bucket) return false; + out_us -= bucket; + } + /* Range-check the ACTUAL floored result against the int64 nanosecond + * domain (out_us × 1000), matching exec_date_trunc — not a conservative + * pre-floor headroom, which rejected representable boundary values. */ + if (out_us > INT64_MAX / 1000LL || out_us < INT64_MIN / 1000LL) return false; + *out_ns = out_us * 1000LL; + return true; +} ray_t* ray_temporal_extract(ray_t* input, int field) { if (!input || RAY_IS_ERR(input)) return input; @@ -124,9 +175,9 @@ ray_t* ray_temporal_extract(ray_t* input, int field) { if (t != -RAY_DATE && t != -RAY_TIME && t != -RAY_TIMESTAMP) return ray_error("type", "extract: expected date/time/timestamp, got %s", ray_type_name(t)); if (RAY_ATOM_IS_NULL(input)) return ray_typed_null(-RAY_I64); - int64_t raw = input->i64; - int64_t us = rte_to_us(t, raw); - return ray_i64(rte_extract_one(us, field)); + int64_t ev; + if (!rte_extract_elem(t, input->i64, field, &ev)) return ray_typed_null(-RAY_I64); + return ray_i64(ev); } /* Vector input. */ @@ -158,31 +209,35 @@ ray_t* ray_temporal_extract(ray_t* input, int field) { const int32_t* d32 = (const int32_t*)base; if (src_has_nulls) { for (int64_t i = 0; i < len; i++) { - if (ray_vec_is_null(input, i)) { + if (ray_vec_is_null(input, i) || + !rte_extract_elem(t, (int64_t)d32[i], field, &out[i])) { out[i] = NULL_I64; ray_vec_set_null(result, i, true); - continue; } - out[i] = rte_extract_one(rte_to_us(t, (int64_t)d32[i]), field); } } else { for (int64_t i = 0; i < len; i++) - out[i] = rte_extract_one(rte_to_us(t, (int64_t)d32[i]), field); + if (!rte_extract_elem(t, (int64_t)d32[i], field, &out[i])) { + out[i] = NULL_I64; + ray_vec_set_null(result, i, true); + } } } else { const int64_t* d64 = (const int64_t*)base; if (src_has_nulls) { for (int64_t i = 0; i < len; i++) { - if (ray_vec_is_null(input, i)) { + if (ray_vec_is_null(input, i) || + !rte_extract_elem(t, d64[i], field, &out[i])) { out[i] = NULL_I64; ray_vec_set_null(result, i, true); - continue; } - out[i] = rte_extract_one(rte_to_us(t, d64[i]), field); } } else { for (int64_t i = 0; i < len; i++) - out[i] = rte_extract_one(rte_to_us(t, d64[i]), field); + if (!rte_extract_elem(t, d64[i], field, &out[i])) { + out[i] = NULL_I64; + ray_vec_set_null(result, i, true); + } } } return result; @@ -252,13 +307,13 @@ ray_t* ray_temporal_truncate(ray_t* input, int kind) { if (t != -RAY_DATE && t != -RAY_TIME && t != -RAY_TIMESTAMP) return ray_error("type", "truncate: expected date/time/timestamp, got %s", ray_type_name(t)); if (RAY_ATOM_IS_NULL(input)) return ray_typed_null(-RAY_TIMESTAMP); - int64_t us = rte_to_us(t, input->i64); int64_t bucket = (kind == RAY_EXTRACT_DAY) ? RTE_USEC_PER_DAY : RTE_USEC_PER_SEC; - int64_t r = us % bucket; - int64_t out_us = us - r - (r < 0 ? bucket : 0); - return ray_timestamp(rte_us_to_ts_raw(out_us)); + int64_t out_ns; + if (!rte_trunc_elem(t, input->i64, bucket, &out_ns)) + return ray_typed_null(-RAY_TIMESTAMP); + return ray_timestamp(out_ns); } /* Vector input. */ @@ -287,38 +342,30 @@ ray_t* ray_temporal_truncate(ray_t* input, int kind) { if (t == RAY_DATE || t == RAY_TIME) { const int32_t* d32 = (const int32_t*)base; if (src_has_nulls) { - for (int64_t i = 0; i < len; i++) { - if (ray_vec_is_null(input, i)) { - out[i] = NULL_I64; ray_vec_set_null(result, i, true); continue; + for (int64_t i = 0; i < len; i++) + if (ray_vec_is_null(input, i) || + !rte_trunc_elem(t, (int64_t)d32[i], bucket, &out[i])) { + out[i] = NULL_I64; ray_vec_set_null(result, i, true); } - int64_t us = rte_to_us(t, (int64_t)d32[i]); - int64_t r = us % bucket; - out[i] = rte_us_to_ts_raw(us - r - (r < 0 ? bucket : 0)); - } } else { - for (int64_t i = 0; i < len; i++) { - int64_t us = rte_to_us(t, (int64_t)d32[i]); - int64_t r = us % bucket; - out[i] = rte_us_to_ts_raw(us - r - (r < 0 ? bucket : 0)); - } + for (int64_t i = 0; i < len; i++) + if (!rte_trunc_elem(t, (int64_t)d32[i], bucket, &out[i])) { + out[i] = NULL_I64; ray_vec_set_null(result, i, true); + } } } else { const int64_t* d64 = (const int64_t*)base; if (src_has_nulls) { - for (int64_t i = 0; i < len; i++) { - if (ray_vec_is_null(input, i)) { - out[i] = NULL_I64; ray_vec_set_null(result, i, true); continue; + for (int64_t i = 0; i < len; i++) + if (ray_vec_is_null(input, i) || + !rte_trunc_elem(t, d64[i], bucket, &out[i])) { + out[i] = NULL_I64; ray_vec_set_null(result, i, true); } - int64_t us = rte_to_us(t, d64[i]); - int64_t r = us % bucket; - out[i] = rte_us_to_ts_raw(us - r - (r < 0 ? bucket : 0)); - } } else { - for (int64_t i = 0; i < len; i++) { - int64_t us = rte_to_us(t, d64[i]); - int64_t r = us % bucket; - out[i] = rte_us_to_ts_raw(us - r - (r < 0 ? bucket : 0)); - } + for (int64_t i = 0; i < len; i++) + if (!rte_trunc_elem(t, d64[i], bucket, &out[i])) { + out[i] = NULL_I64; ray_vec_set_null(result, i, true); + } } } return result; @@ -383,14 +430,26 @@ ray_t* exec_extract(ray_graph_t* g, ray_op_t* op) { if (IN32) { \ /* RAY_DATE: int32 days → µs; RAY_TIME: int32 ms → µs */ \ int32_t raw32 = ((const int32_t*)m.morsel_ptr)[i]; \ + /* A DATE hundreds of millennia out (int32 days) would \ + * overflow days×µs-per-day; it is not representable in \ + * the µs domain, so emit a null like a null input. */ \ + if (in_type == RAY_DATE && \ + ((int64_t)raw32 > INT64_MAX / USEC_PER_DAY || \ + (int64_t)raw32 < INT64_MIN / USEC_PER_DAY)) { \ + out[off + i] = NULL_I64; \ + ray_vec_set_null(result, off + i, true); \ + continue; \ + } \ us = (in_type == RAY_DATE) \ ? (int64_t)raw32 * USEC_PER_DAY \ : (int64_t)raw32 * 1000LL; \ } else { \ - /* RAY_TIMESTAMP: int64 nanoseconds → µs */ \ + /* RAY_TIMESTAMP: int64 nanoseconds → µs, floor toward \ + * -inf. Truncate-then-adjust instead of negating: the \ + * old -((-ns)+999)/1000 overflowed near INT64_MIN. */ \ int64_t ns = ((const int64_t*)m.morsel_ptr)[i]; \ - us = ns >= 0 ? ns / 1000LL \ - : -(((-ns) + 999LL) / 1000LL); \ + us = ns / 1000LL; \ + if (ns % 1000LL != 0 && ns < 0) us--; \ } \ if (field == RAY_EXTRACT_EPOCH) { \ out[off + i] = us; \ @@ -534,13 +593,29 @@ ray_t* exec_date_trunc(ray_graph_t* g, ray_op_t* op) { int64_t us; \ if (IN32) { \ int32_t raw32 = ((const int32_t*)m.morsel_ptr)[i]; \ + /* Bound the DATE by the int64-NANOSECOND representable \ + * day range, not just the µs one: the YEAR/MONTH arms \ + * below re-multiply days_from_civil(...) — a day count \ + * floored DOWN to the period start, up to a year beyond \ + * `raw32` — by DT_USEC_PER_DAY, and the result is then \ + * ×1000 to nanoseconds. Matches rte_trunc_elem; a DATE \ + * outside this range is not a TIMESTAMP, so null it. */ \ + if (in_type == RAY_DATE && \ + ((int64_t)raw32 > INT64_MAX / 1000 / DT_USEC_PER_DAY || \ + (int64_t)raw32 < INT64_MIN / 1000 / DT_USEC_PER_DAY)) { \ + out[off + i] = NULL_I64; \ + ray_vec_set_null(result, off + i, true); \ + continue; \ + } \ us = (in_type == RAY_DATE) \ ? (int64_t)raw32 * DT_USEC_PER_DAY \ : (int64_t)raw32 * 1000LL; \ } else { \ + /* ns → µs, floor toward -inf, overflow-free (the old \ + * -((-ns)+999)/1000 overflowed near INT64_MIN). */ \ int64_t ns = ((const int64_t*)m.morsel_ptr)[i]; \ - us = ns >= 0 ? ns / 1000LL \ - : -(((-ns) + 999LL) / 1000LL); \ + us = ns / 1000LL; \ + if (ns % 1000LL != 0 && ns < 0) us--; \ } \ int64_t out_us; \ switch (field) { \ @@ -598,6 +673,12 @@ ray_t* exec_date_trunc(ray_graph_t* g, ray_op_t* op) { out_us = us; \ break; \ } \ + /* Result must fit int64 nanoseconds (out_us × 1000). */ \ + if (out_us > INT64_MAX / 1000LL || out_us < INT64_MIN / 1000LL) { \ + out[off + i] = NULL_I64; \ + ray_vec_set_null(result, off + i, true); \ + continue; \ + } \ out[off + i] = out_us * 1000LL; /* µs → ns for RAY_TIMESTAMP */ \ } \ off += n; \ diff --git a/test/rfl/arith/overflow_wrap.rfl b/test/rfl/arith/overflow_wrap.rfl new file mode 100644 index 000000000..81ab3d6eb --- /dev/null +++ b/test/rfl/arith/overflow_wrap.rfl @@ -0,0 +1,40 @@ +;; overflow_wrap.rfl — scalar integer +, -, * must wrap on overflow with +;; DEFINED behavior, not signed-integer-overflow UB. +;; +;; ray_add_fn / ray_sub_fn / ray_mul_fn computed `as_i64(a) OP as_i64(b)` +;; directly, so an i64 result that overflowed was undefined behavior — UBSan +;; reported it at src/ops/arith.c:141 (+), :223 (-), :257 (*). The wrapped +;; value (INT64_MIN for MAX+1, which is the i64 null sentinel) was already +;; what the code returned, so this only removes the UB; results are unchanged. +;; Matches the vector arithmetic kernel (src/ops/expr.c OP_ADD/SUB/MUL), which +;; already wraps via uint64. + +;; ── addition ──────────────────────────────────────────────────────── +;; MAX + 1 wraps to INT64_MIN, which prints as the i64 null. +(nil? (+ 9223372036854775807 1)) -- true +;; MAX + 2 wraps to INT64_MIN + 1 (a concrete, non-null value). +(+ 9223372036854775807 2) -- -9223372036854775807 +;; Just-below-overflow is exact. +(+ 9223372036854775806 1) -- 9223372036854775807 + +;; ── subtraction ───────────────────────────────────────────────────── +;; -MAX - 2 wraps around to +MAX. +(- -9223372036854775807 2) -- 9223372036854775807 +;; 0 - INT64_MIN overflows (INT64_MIN has no positive counterpart) → wraps +;; back to INT64_MIN = null. +(nil? (- 0 -9223372036854775808)) -- true + +;; ── multiplication ────────────────────────────────────────────────── +(* 9223372036854775807 2) -- -2 +(* 9223372036854775807 3) -- 9223372036854775805 +;; INT64_MIN * -1 overflows → wraps to INT64_MIN = null. +(nil? (* -9223372036854775808 -1)) -- true + +;; ── ordinary arithmetic and narrow types are unaffected ───────────── +(+ 2 3) -- 5 +(- 10 4) -- 6 +(* 6 7) -- 42 +(* 1000000 1000000) -- 1000000000000 +(+ 100h 200h) -- 300h +(+ 5i 6i) -- 11i +(+ 2.5 3.5) -- 6.0 diff --git a/test/rfl/collection/distinct.rfl b/test/rfl/collection/distinct.rfl index 8708cdb4c..f52b15f4d 100644 --- a/test/rfl/collection/distinct.rfl +++ b/test/rfl/collection/distinct.rfl @@ -256,3 +256,45 @@ (distinct (* "bad" 5)) !- type (distinct (round "x")) !- type (distinct (at (sqrt 'foo) 0)) !- type + +;; ---- Parallel radix path ---- +;; Vectors of >= 65536 rows route fixed-width types through the +;; radix-partitioned kernel (distinct_radix_first_ids); everything below +;; must agree with the small-vector hashset semantics above: value-sorted +;; output, declared nulls collapsed to one (sentinel sorts first). + +;; i64: duplicates spread across the whole vector, null in the tail +(set big (concat (concat [5 7 5] (take [9] 100000)) (concat [7 3 0Nl] (take [5] 100000)))) +(count big) -- 200006 +(distinct big) -- [0Nl 3 5 7 9] +;; the fused count(distinct) kernel (OP_COUNT_DISTINCT) must agree with +;; the materializing kernel — two independent implementations +(count (distinct big)) -- 5 +;; idempotent on the radix path +(distinct (distinct big)) -- [0Nl 3 5 7 9] +;; dedup invariant at radix scale +(count (distinct big)) -- (count (distinct (concat big big))) + +;; f64 with declared nulls: every NaN collapses to a single null +;; (order of the null among sorted values is comparator-defined for +;; NaN, so assert cardinality + null survival, not full ordering) +(set bigf (concat (take [1.5] 80000) (concat [0Nf 2.5 1.5 0Nf] (take [2.5] 80000)))) +(count (distinct bigf)) -- 3 +(count (distinct (concat bigf bigf))) -- 3 + +;; i32 (cast keeps the null): same values through the 4-byte lane +(count (distinct (as 'I32 big))) -- 5 + +;; i16 lane +(set bigh (concat (take [1h] 70000) (concat [3h 2h] (take [2h] 70000)))) +(distinct bigh) -- [1 2 3] + +;; temporal lanes: time (i32) and timestamp (i64) +(set bigt (concat (take [09:30:00.000] 70000) (concat [09:31:00.000 0Nt] (take [09:30:00.000] 70000)))) +(distinct bigt) -- [0Nt 09:30:00.000 09:31:00.000] +(set bigp (concat (take [2024.01.01D10:00:00.000000000] 70000) (take [2024.01.02D10:00:00.000000000] 70000))) +(distinct bigp) -- [2024.01.01D10:00:00.000000000 2024.01.02D10:00:00.000000000] + +;; exactly at the engage threshold (1 << 16 rows) +(set edge (concat (take [1] 65535) [2])) +(distinct edge) -- [1 2] diff --git a/test/rfl/group/reduce_range_arms.rfl b/test/rfl/group/reduce_range_arms.rfl index 8c830aa68..bb8f4ae42 100644 --- a/test/rfl/group/reduce_range_arms.rfl +++ b/test/rfl/group/reduce_range_arms.rfl @@ -2,11 +2,10 @@ ;; reduce_range type x null specialisations (src/ops/group.c). ;; ;; reduce_range is the inner reduction kernel for direct (raw-vec) -;; sum/min/max/avg/first/last/var/stddev calls. It dispatches per -;; `input->type` (BOOL/U8, I16, I32, I64, F64, DATE, TIME, TIMESTAMP, -;; SYM), then each integer/float arm goes through DISPATCH_I/F which -;; macro-expands into four (HAS_NULLS x HAS_IDX) loop bodies so the -;; compiler can DCE the inner per-row branches. +;; sum/prod/all/any/min/max/avg/first/last/var/stddev calls. It dispatches +;; first by opcode, then type and (HAS_NULLS x HAS_IDX), so the compiler +;; emits a loop containing only the accumulator fields needed by that +;; opcode. These assertions cover both serial loops and parallel merges. ;; ;; ARCHITECTURE NOTE on missed regions: the HAS_IDX=1 specialisations ;; in DISPATCH_I/F (and the corresponding `idx ? idx[i] : i` branch in @@ -102,3 +101,20 @@ ;; F64 + nulls + avg: F64 reduce_range HAS_NULLS=1 plus the OP_AVG ;; finaliser's null-aware divisor (uses non-null count). (avg (as 'F64 [10.0 0N 20.0 0N 30.0])) -- 20.0 + + +;; ─── Parallel opcode-specialised loops and merges ─────────────────── +;; RAY_PARALLEL_THRESHOLD is 65536. Keep these vectors above it so each +;; requested accumulator shape is also checked across worker-local merges. +(set _Rspec (til 70000)) +(sum _Rspec) -- 2449965000 +(prod _Rspec) -- 0 +(prod (+ 1 (% _Rspec 1))) -- 1 +(min _Rspec) -- 0 +(max _Rspec) -- 69999 +(avg _Rspec) -- 34999.5 +(all (> (+ _Rspec 1) 0)) -- true +(any (== _Rspec 69999)) -- true +(any (< _Rspec 0)) -- false +(< (abs (- (var_pop _Rspec) 408333333.25)) 0.001) -- true +(del _Rspec) -- 0 diff --git a/test/rfl/io/csv_types.rfl b/test/rfl/io/csv_types.rfl index b6b270199..de067b59c 100644 --- a/test/rfl/io/csv_types.rfl +++ b/test/rfl/io/csv_types.rfl @@ -353,6 +353,21 @@ (set Tcardlostr (.csv.read [STR] "rf_csv_card_lo.csv")) (type (at Tcardlostr 'k)) -- 'STR +;; ════════════════════════════════════════════════════════════════════════════ +;; Explicit schema aliases and exact width validation. +;; SYM is the canonical name printed by `type`; SYMBOL remains the long alias. +;; Historical LIST text columns materialize as packed STR columns. A schema +;; must describe every CSV column exactly instead of failing later as OOM. +;; ════════════════════════════════════════════════════════════════════════════ +(.sys.exec "printf 's,text\nfoo,hello\nbar,world\n' > rf_test_csv_types_alias.csv") -- 0 +(set Talias (.csv.read [SYM LIST] "rf_test_csv_types_alias.csv")) +(type (at Talias 's)) -- 'SYM +(type (at Talias 'text)) -- 'STR +(at (at Talias 'text) 0) -- "hello" +(.csv.read [SYM] "rf_test_csv_types_alias.csv") !- length +(.csv.read [SYM LIST I64] "rf_test_csv_types_alias.csv") !- length +(.sys.exec "rm -f rf_test_csv_types_alias.csv") -- 0 + ;; ── cleanup ───────────────────────────────────────────────────────────────── (.sys.exec "rm -f rf_csv_card_*.csv") -- 0 (.sys.exec "rm -f rf_test_csv_types_*.csv") -- 0 diff --git a/test/rfl/temporal/extract_trunc_overflow.rfl b/test/rfl/temporal/extract_trunc_overflow.rfl new file mode 100644 index 000000000..b5d948457 --- /dev/null +++ b/test/rfl/temporal/extract_trunc_overflow.rfl @@ -0,0 +1,94 @@ +;; extract_trunc_overflow.rfl — regression for signed-overflow UB in the +;; DATE/TIMESTAMP → microseconds conversion shared by the four temporal +;; decomposition kernels (standalone + DAG, extract + truncate). +;; +;; Bugs (all UBSan signed-overflow in src/ops/temporal.c): +;; * a DATE is int32 days, so an extreme value multiplied by µs-per-day +;; overflowed int64 — (dd (as 'DATE 2147483647)) tripped `raw * 86400000000`; +;; * the ns→µs floor for TIMESTAMP negated the input, so a value within +;; 999 of INT64_MIN overflowed `(-raw) + 999`; +;; * the DAG date_trunc YEAR/MONTH arms re-multiply days_from_civil(...) — a +;; day count floored down to the period start — by µs-per-day, so a DATE +;; that cleared the µs bound still overflowed the ns range (d.year of +;; (as 'DATE -106751991)). +;; +;; Fix: reject the un-representable DATE (emit null, as for a null input) and +;; do the TIMESTAMP floor with truncate-then-adjust so it never negates. The +;; truncate DATE bound is the int64-NANOSECOND representable day range so the +;; re-multiply cannot overflow. Covers both the standalone kernels +;; (yyyy/dd/mm/hh and (date …)) and the DAG kernels (dotted col.field). + +;; ── standalone extract atom path ──────────────────────────────────── +;; Extreme DATE (large magnitude, both signs) → null instead of overflow. +;; NB: -2147483648 == NULL_I32, i.e. a null DATE, so it would exit at the +;; null-input early-out and never exercise the guard; use a non-null value. +(nil? (yyyy (as 'DATE 2147483647))) -- true +(nil? (mm (as 'DATE 2147483647))) -- true +(nil? (dd (as 'DATE -200000000))) -- true +;; Minimum-edge TIMESTAMP no longer overflows the ns→µs floor. +(mm (as 'TIMESTAMP -9223372036854775807)) -- 9 +(hh (as 'TIMESTAMP -9223372036854775807)) -- 0 +;; Ordinary values are unaffected. +(yyyy 2024.03.15D14:27:31.123456789) -- 2024 +(mm 2024.03.15D14:27:31.123456789) -- 3 +(dd 2024.03.15D14:27:31.123456789) -- 15 +(hh 2024.03.15D14:27:31.123456789) -- 14 +(yyyy 2024.03.15) -- 2024 +(dd 2000.01.01) -- 1 + +;; ── standalone extract vector path ────────────────────────────────── +;; A mix of ordinary, null and extreme rows: only the extreme row nulls. +(set Ex (yyyy (as 'DATE [0 366 2147483647]))) +(at Ex 0) -- 2000 +(at Ex 1) -- 2001 +(nil? (at Ex 2)) -- true + +;; ── DAG extract kernel (dotted-path in select) ────────────────────── +(set T (table [d ts] (list (as 'DATE [0 366 2147483647]) (as 'TIMESTAMP [0 86400000000000 -9223372036854775807])))) +(set Ey (at (select {v: d.yyyy from: T}) 'v)) +(at Ey 0) -- 2000 +(at Ey 1) -- 2001 +(nil? (at Ey 2)) -- true +;; TIMESTAMP min edge decodes without overflow through the DAG kernel too. +(set Em (at (select {v: ts.mm from: T}) 'v)) +(at Em 0) -- 1 +(at Em 2) -- 9 + +;; ── DAG date_trunc kernel (dotted-path .date) ─────────────────────── +;; Extreme DATE truncates to null (not representable as a TIMESTAMP); +;; ordinary rows are unchanged. +(set Td (at (select {v: d.date from: T}) 'v)) +(at Td 0) -- 2000.01.01D00:00:00.000000000 +(at Td 1) -- 2001.01.01D00:00:00.000000000 +(nil? (at Td 2)) -- true + +;; ── DAG date_trunc YEAR / MONTH arms (the re-multiply path) ────────── +;; d.year of a large-magnitude negative DATE used to overflow the second +;; days_from_civil(...) * µs-per-day multiply; it must null, not UB. +(set Tn (table [d] (list (as 'DATE [-106751991 8840 200000000])))) +(set Ty (at (select {v: d.year from: Tn}) 'v)) +(nil? (at Ty 0)) -- true +(at Ty 1) -- 2024.01.01D00:00:00.000000000 +(nil? (at Ty 2)) -- true +(set Tmo (at (select {v: d.month from: Tn}) 'v)) +(nil? (at Tmo 0)) -- true +(at Tmo 1) -- 2024.03.01D00:00:00.000000000 +(nil? (at Tmo 2)) -- true + +;; ── standalone truncate kernel via (date ) ──────────────── +;; Ordinary values truncate to the day; values outside the int64-ns range +;; null instead of wrapping. +(date (as 'TIMESTAMP 86400000000000)) -- 2000.01.02D00:00:00.000000000 +(nil? (date (as 'TIMESTAMP -9223372036854775807))) -- true +(date (as 'DATE 8766)) -- 2024.01.01D00:00:00.000000000 +(nil? (date (as 'DATE 2000000000))) -- true + +;; ── low day boundary: floor result is representable (PR #386 review) ─ +;; A TIMESTAMP whose day-floored value is still inside the int64-ns range +;; must round-trip, not null. The old pre-floor headroom rejected it — so +;; the standalone (date …) path disagreed with the DAG ts.date path. The +;; floor now uses overflow-safe arithmetic and range-checks the actual +;; result, so both paths agree at the boundary. +(date (as 'TIMESTAMP -9223286400000000000)) -- 1707.09.23D00:00:00.000000000 +(set Tbnd (table [ts] (list (as 'TIMESTAMP [-9223286400000000000])))) +(at (at (select {v: ts.date from: Tbnd}) 'v) 0) -- 1707.09.23D00:00:00.000000000 diff --git a/test/rfl/type/as.rfl b/test/rfl/type/as.rfl index 5f6c13ac3..316e24c85 100644 --- a/test/rfl/type/as.rfl +++ b/test/rfl/type/as.rfl @@ -262,6 +262,22 @@ (as 'date 2000.01.02D00:00:00.000000000) -- 2000.01.02 ;; date <- String (as 'date "2024.03.20") -- 2024.03.20 +;; Leap day is valid in a leap year, rejected otherwise. +(as 'date "2024.02.29") -- 2024.02.29 +(as 'date "2023.02.29") !- domain +;; date <- String: malformed input must be REJECTED, not silently parsed. +;; A month past 12 used to index the days-in-month table out of bounds +;; (ASan OOB read); trailing garbage and loose fields were also accepted. +(as 'date "9999.99.99") !- domain +(as 'date "2024.13.01") !- domain +(as 'date "2024.00.10") !- domain +(as 'date "2024.02.31") !- domain +(as 'date "2024.04.31") !- domain +(as 'date "2024.01.00") !- domain +(as 'date "2024.01.02junk") !- domain +(as 'date "2024.1.2") !- domain +(as 'date "2024/01/02") !- domain +(as 'date "2024-01-02") !- domain ;; ========== DATE VECTOR CASTS ========== (type (as 'DATE [0 1 2])) -- 'DATE (as 'I64 (as 'DATE [0 1 2])) -- [0 1 2] @@ -309,6 +325,21 @@ (as 'time "20:00:00") -- 20:00:00.000 (as 'time "20:00:00.") -- 20:00:00.000 (as 'time "20:00:00.0") -- 20:00:00.000 +;; TIME is a signed duration: hours may exceed a day and go negative, +;; and HH:MM (no seconds) is accepted. +(as 'time "25:00:00") -- 25:00:00.000 +(as 'time "-5:00:00") -- -05:00:00.000 +(as 'time "12:34") -- 12:34:00.000 +;; Malformed TIME strings must be REJECTED, not silently normalized. +;; The old sscanf path accepted trailing garbage and out-of-range fields +;; ("25:99:99" wrapped to 26:40:39). +(as 'time "12:34:56junk") !- domain +(as 'time "12:34:56.789junk") !- domain +(as 'time "25:99:99") !- domain +(as 'time "99:99:99") !- domain +(as 'time "12x34x56") !- domain +(as 'time "12:3") !- domain +(as 'time "x") !- domain ;; time literals with 1-3 digit fractional seconds 10:00:00.1 -- 10:00:00.001 10:00:00.01 -- 10:00:00.001 diff --git a/test/test_compile.c b/test/test_compile.c index 586440c3d..6e12ad2a7 100644 --- a/test/test_compile.c +++ b/test/test_compile.c @@ -34,6 +34,7 @@ #include "lang/eval.h" #include "lang/env.h" #include "lang/parse.h" +#include "ops/ops.h" #include /* __RUNTIME is internal test plumbing; runtime API declarations come from @@ -87,14 +88,12 @@ static void compile_teardown(void) { } while (0) /* ════════════════════════════════════════════════════════════════════ - * 1. (set name val) inside a compiled lambda body (line 225-230) - * The compiler emits OP_CALLD for set because set modifies the - * global environment and the compiler defers to the interpreter. + * 1. (set name val) inside a compiled lambda body + * The compiler evaluates the value in the current frame, forces lazy + * results, and stores the concrete value in the global environment. * ════════════════════════════════════════════════════════════════════ */ static test_result_t test_compile_set_inside_fn(void) { - /* Define a fn that calls (set ...) inside its body using a constant - * value (not a local variable) so the deferred AST can resolve. - * The compile path for (set name val) delegates to OP_CALLD. */ + /* Define a fn that calls (set ...) inside its body. */ EVAL_I64( "(do " "(set f (fn [] (set compile_set_g 42) compile_set_g)) " @@ -103,6 +102,30 @@ static test_result_t test_compile_set_inside_fn(void) { PASS(); } +/* A global written by compiled `set` must hold the concrete result, not the + * single-use lazy handle returned by first/distinct/etc. */ +static test_result_t test_compile_set_forces_lazy_value(void) { + EVAL_I64( + "(do " + "(set xs [5 1 4 2]) " + "(set f (fn [] (do (set lazy_set_g (first xs)) 0))) " + "(f) " + "(+ lazy_set_g lazy_set_g))", + 10); + PASS(); +} + +static test_result_t test_compile_set_forces_lazy_chain(void) { + EVAL_I64( + "(do " + "(set xs [\"aaa\" \"bbb\" \"aaa\"]) " + "(set f (fn [] (do (set lazy_set_all (distinct xs)) 0))) " + "(f) " + "(+ (+ 0 (count lazy_set_all)) (count lazy_set_all)))", + 4); + PASS(); +} + /* ════════════════════════════════════════════════════════════════════ * 2. (if cond then) WITHOUT else branch (lines 268-277) * Compiler emits a zero literal for the false branch. @@ -123,6 +146,43 @@ static test_result_t test_compile_if_no_else_false(void) { PASS(); } +/* A compiled condition must test the value produced by a lazy aggregate. */ +static test_result_t test_compile_if_forces_lazy_condition(void) { + EVAL_I64( + "(do (set xs [0 1 4 2]) (set f (fn [] (if (first xs) 1 0))) (f))", + 0); + PASS(); +} + +/* A stale lazy alias is rejected before graph construction dereferences its + * cleared root. This is a defensive backstop for callers outside bindings. */ +static test_result_t test_compile_spent_lazy_returns_error(void) { + ray_t* vec = ray_eval_str("[1 2 1]"); + TEST_ASSERT_NOT_NULL(vec); + TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); + ray_t* lazy = ray_distinct_fn(vec); + TEST_ASSERT_NOT_NULL(lazy); + TEST_ASSERT_FALSE(RAY_IS_ERR(lazy)); + ray_retain(lazy); /* preserve one alias after materialization consumes one */ + ray_t* concrete = ray_lazy_materialize(lazy); + TEST_ASSERT_NOT_NULL(concrete); + TEST_ASSERT_FALSE(RAY_IS_ERR(concrete)); + + ray_t* err = ray_lazy_append(lazy, OP_COUNT); + TEST_ASSERT_NOT_NULL(err); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); + ray_error_free(err); + + err = ray_lazy_materialize(lazy); /* consumes the final lazy alias */ + TEST_ASSERT_NOT_NULL(err); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); + ray_error_free(err); + + ray_release(concrete); + ray_release(vec); + PASS(); +} + /* ════════════════════════════════════════════════════════════════════ * 3. (do ...) inside a compiled lambda body (lines 282-288) * Compiler emits OP_POP between each expression. @@ -948,8 +1008,12 @@ static test_result_t test_compile_default_switch_case(void) { * ════════════════════════════════════════════════════════════════════ */ const test_entry_t compile_entries[] = { { "compile/set_inside_fn", test_compile_set_inside_fn, compile_setup, compile_teardown }, + { "compile/set_forces_lazy_value", test_compile_set_forces_lazy_value, compile_setup, compile_teardown }, + { "compile/set_forces_lazy_chain", test_compile_set_forces_lazy_chain, compile_setup, compile_teardown }, { "compile/if_no_else_true", test_compile_if_no_else_true, compile_setup, compile_teardown }, { "compile/if_no_else_false", test_compile_if_no_else_false, compile_setup, compile_teardown }, + { "compile/if_forces_lazy_condition", test_compile_if_forces_lazy_condition, compile_setup, compile_teardown }, + { "compile/spent_lazy_returns_error", test_compile_spent_lazy_returns_error, compile_setup, compile_teardown }, { "compile/do_inside_fn", test_compile_do_inside_fn, compile_setup, compile_teardown }, { "compile/do_multi_exprs", test_compile_do_multi_exprs, compile_setup, compile_teardown }, { "compile/nested_fn", test_compile_nested_fn, compile_setup, compile_teardown }, diff --git a/test/test_csv.c b/test/test_csv.c index 47c50945f..c0f1bb615 100644 --- a/test/test_csv.c +++ b/test/test_csv.c @@ -25,6 +25,7 @@ #include #include #include "mem/heap.h" +#include "core/qstats.h" #include "io/csv.h" #include "table/sym.h" #include @@ -1545,6 +1546,103 @@ static test_result_t test_csv_resolve_int_width(void) { PASS(); } +typedef struct { + int calls; + bool cancel_on_first; + bool went_backwards; + uint64_t last_done; + uint64_t last_total; +} csv_progress_probe_t; + +static void csv_progress_probe_cb(const ray_progress_t* p, void* user) { + csv_progress_probe_t* probe = (csv_progress_probe_t*)user; + if (p->final || p->rows_total == 0) return; + if (probe->last_total != 0 && + p->rows_done * probe->last_total < probe->last_done * p->rows_total) + probe->went_backwards = true; + probe->last_done = p->rows_done; + probe->last_total = p->rows_total; + probe->calls++; + if (probe->cancel_on_first && probe->calls == 1) + ray_request_interrupt(); +} + +/* Cancellation must be observed while pool workers are inside the CSV row + * loop, and cleanup must only inspect initialized strrefs. Sparse escaped + * fields exercise ownership cleanup without turning the fixture into an + * allocation benchmark. */ +static test_result_t test_csv_interrupt_mid_parse(void) { + ray_heap_init(); + (void)ray_sym_init(); + + FILE* f = fopen(TMP_CSV, "w"); + TEST_ASSERT_NOT_NULL(f); + fputs("id,payload\n", f); + for (int i = 0; i < 200000; i++) { + if ((i % 1000) == 0) + fprintf(f, "%d,\"escaped \"\"value\"\" %d\"\n", i, i); + else + fprintf(f, "%d,payload_%06d\n", i, i); + } + fclose(f); + + csv_progress_probe_t probe = {.cancel_on_first = true}; + ray_progress_set_callback(csv_progress_probe_cb, &probe, 1, 1); + ray_qstats_set_mode(RAY_QS_PROGRESS); + int8_t schema[] = {RAY_I32, RAY_STR}; + ray_t* loaded = ray_read_csv_opts(TMP_CSV, ',', true, schema, 2); + bool got_cancel = loaded && RAY_IS_ERR(loaded) && + strcmp(ray_err_code(loaded), "cancel") == 0; + + if (loaded) ray_release(loaded); + ray_progress_end(); + ray_progress_set_callback(NULL, NULL, 0, 0); + ray_qstats_set_mode(0); + ray_clear_interrupt(); + unlink(TMP_CSV); + ray_sym_destroy(); + ray_heap_destroy(); + + TEST_ASSERT_TRUE(probe.calls > 0); + TEST_ASSERT_TRUE(got_cancel); + PASS(); +} + +/* The row parser is followed by a two-task text finalizer. That internal + * dispatch must not replace n_rows progress with 0/2 and make the visible + * percentage jump from complete back to 50%. */ +static test_result_t test_csv_progress_never_goes_backwards(void) { + ray_heap_init(); + (void)ray_sym_init(); + + FILE* f = fopen(TMP_CSV, "w"); + TEST_ASSERT_NOT_NULL(f); + fputs("payload,symbol\n", f); + for (int i = 0; i < 100000; i++) + fprintf(f, "long_payload_%06d_for_progress,unique_symbol_%06d\n", i, i); + fclose(f); + + csv_progress_probe_t probe = {0}; + ray_progress_set_callback(csv_progress_probe_cb, &probe, 1, 1); + ray_qstats_set_mode(RAY_QS_PROGRESS); + int8_t schema[] = {RAY_STR, RAY_SYM}; + ray_t* loaded = ray_read_csv_opts(TMP_CSV, ',', true, schema, 2); + bool read_ok = loaded && !RAY_IS_ERR(loaded); + + if (loaded) ray_release(loaded); + ray_progress_end(); + ray_progress_set_callback(NULL, NULL, 0, 0); + ray_qstats_set_mode(0); + unlink(TMP_CSV); + ray_sym_destroy(); + ray_heap_destroy(); + + TEST_ASSERT_TRUE(read_ok); + TEST_ASSERT_TRUE(probe.calls > 0); + TEST_ASSERT_FALSE(probe.went_backwards); + PASS(); +} + const test_entry_t csv_entries[] = { { "csv/roundtrip_i64", test_csv_roundtrip_i64, NULL, NULL }, { "csv/roundtrip_guid", test_csv_guid_roundtrip, NULL, NULL }, @@ -1597,5 +1695,7 @@ const test_entry_t csv_entries[] = { { "csv/explicit_u8_schema_serial", test_csv_explicit_u8_schema_serial, NULL, NULL }, { "csv/resolve_int_width", test_csv_resolve_int_width, NULL, NULL }, + { "csv/interrupt_mid_parse", test_csv_interrupt_mid_parse, NULL, NULL }, + { "csv/progress_monotonic", test_csv_progress_never_goes_backwards, NULL, NULL }, { NULL, NULL, NULL, NULL }, };