diff --git a/Makefile b/Makefile index 72c230b95..3faeba387 100644 --- a/Makefile +++ b/Makefile @@ -48,7 +48,8 @@ UNAME_S := $(shell uname -s) RAY_MARCH ?= native DEBUG_CFLAGS = -fPIC $(WARNS) -std=$(STD) -g -O0 -march=$(RAY_MARCH) -DDEBUG \ - -fsanitize=address,undefined -fno-omit-frame-pointer + -fsanitize=address,undefined -fno-sanitize-recover=undefined \ + -fno-omit-frame-pointer RELEASE_CFLAGS = -fPIC $(WARNS) -std=$(STD) -O3 -march=$(RAY_MARCH) \ -funroll-loops -fomit-frame-pointer -fno-math-errno -falign-functions=64 \ -fassociative-math -ffp-contract=fast -fno-signed-zeros -fno-trapping-math diff --git a/docs/docs/c-api/dag.md b/docs/docs/c-api/dag.md index 5d6d61804..798099e15 100644 --- a/docs/docs/c-api/dag.md +++ b/docs/docs/c-api/dag.md @@ -206,6 +206,8 @@ ray_op_t* ray_filter(ray_graph_t* g, ray_op_t* input, Multi-column sort. Pass arrays of key nodes, sort directions (1=descending), and null ordering (1=nulls first). Uses parallel radix sort for numerics, merge sort for strings. +Passing `NULL` for `nulls_first` takes the default, which treats a null as the smallest value: nulls first when ascending, last when descending. A top-k over a column that holds nulls therefore returns those nulls, since they are the smallest rows. + ```c ray_op_t* ray_sort_op(ray_graph_t* g, ray_op_t* table_node, ray_op_t** keys, uint8_t* descs, diff --git a/docs/docs/queries/joins.md b/docs/docs/queries/joins.md index ec89f08eb..2bd42f551 100644 --- a/docs/docs/queries/joins.md +++ b/docs/docs/queries/joins.md @@ -126,6 +126,22 @@ The `anti-join` function keeps rows from the left table whose key does not appea ; 3 MSFT ``` +## Null-key semantics (equi-joins) + +`inner-join`, `left-join`, `full-join` and `anti-join` treat **a null key as equal to another null key**, and never equal to a non-null one: + +```lisp +(set left (table [k v] (list (as 'SYM ["a" ""]) [1 2]))) +(set right (table [k w] (list (as 'SYM ["a" ""]) [10 20]))) + +(at (left-join [k] left right) 'w) ; [10 20] — the null key finds its match +(count (anti-join [k] left left)) ; 0 — X anti-joined with itself is empty +``` + +This is the rule the rest of the runtime already applies to key columns: `distinct` keeps exactly one null, group-by folds nulls into a single group, and `in` matches a null against a null. It differs from SQL, where `NULL = NULL` is unknown and a self-anti-join can return rows. The invariant that follows — `(anti-join [cols] X X)` is empty for every `X` and every key set — is what makes anti-join usable for "which of these tuples have I not seen yet". + +As-of join is the exception — its null keys never match. See its own [Null-key semantics](#null-key-semantics) section below. + ## As-of Join The `asof-join` function is designed for time-series data. For each row in the left table, it finds the most recent matching row in the right table where the time column is less than or equal to the left's time value. The last column in the key list is the temporal column; any preceding keys are exact-match equality keys. diff --git a/include/rayforce.h b/include/rayforce.h index cf8aa5d37..c2371849b 100644 --- a/include/rayforce.h +++ b/include/rayforce.h @@ -128,6 +128,11 @@ typedef enum { * singleton (global intern table) or a refcounted mmapped symfile. */ struct ray_sym_domain_s; +/* One file mapping shared by more than one block (src/mem/heap.h): a mapped + * string column and its pool live in the same region, so neither can end it + * alone. Held by the pool at aux[8..15] under mmod 3. */ +struct ray_file_map_s; + typedef union ray_t { /* Allocated: object header */ struct { @@ -173,9 +178,25 @@ typedef union ray_t { * 8-15 hold an int64 sym ID naming the target table. * link_lo[8] aliases bytes 0-7. See ops/linkop.h. */ struct { uint8_t link_lo[8]; int64_t link_target; }; + /* mmod 3 (string pools only): the shared mapping this block + * lives in. Typed rather than reached by offset, so it moves + * with the union if the layout is ever reshuffled. */ + struct { uint8_t _aux_map_lo[8]; struct ray_file_map_s* file_map; }; }; /* Bytes 16-31: metadata + value */ - uint8_t mmod; /* 0=heap, 1=file-mmap */ + /* Where this block's memory came from, and who ends it: + * 0 heap — the buddy allocator owns it + * 1 file-mmap — this block's own free munmaps the region, whose + * size it derives from its type and length + * 2 borrowed — somebody else owns the memory and ends it on its + * own schedule; free does nothing at all + * 3 file-mmap, shared — the region is described by a heap-side + * ray_file_map_t held in aux[8..15] and ends when the last + * block referencing it is freed. A string column and its pool + * live in one mapping, and a selection may keep the pool after + * the column is gone, so the pool carries this and the column + * merely holds a reference to it. */ + uint8_t mmod; uint8_t order; /* block order (block size = 2^order) */ int8_t type; /* negative=atom, positive=vector, 0=LIST */ uint8_t attrs; /* attribute flags */ @@ -360,6 +381,10 @@ bool ray_interrupted(void); typedef struct { const char* op_name; /* coarse: scan, group, pivot, join, ... */ const char* phase; /* optional finer label, e.g. "pivot: dedupe" */ + /* Units follow the op: normally rows, but while a byte-metered span is + * active (see ray_progress_span_begin) these two carry BYTES — the same + * values as bytes_done/bytes_total below — so that the percentage a + * callback derives from them is the span's, not some inner dispatch's. */ uint64_t rows_done; uint64_t rows_total; /* 0 = indeterminate */ double elapsed_sec; @@ -367,6 +392,12 @@ typedef struct { int64_t mem_total; /* bytes: total physical RAM (the disk-spill threshold) */ bool final; /* true on the last tick of a query — renderers use this to clear the line */ + /* Byte-metered ops (currently .csv.read) publish their real progress on a + * byte axis as well as the row counters, so a renderer can show + * "3.2G/8.1G" instead of a row count nobody can size. bytes_total == 0 + * means the op is not byte-metered and these two must be ignored. */ + uint64_t bytes_done; + uint64_t bytes_total; } ray_progress_t; typedef void (*ray_progress_cb)(const ray_progress_t* snapshot, void* user); @@ -407,6 +438,25 @@ bool ray_progress_active(void); void ray_progress_dispatch_begin(uint64_t phase_rows_total); void ray_progress_pump(void); +/* ===== Byte-metered span (main-thread only) ===== + * + * An op made of several internal phases — each of which may run its own pool + * dispatch over a different element count — cannot report honest progress + * through the per-dispatch pump: every dispatch restarts at 0%, so the bar + * saws. A SPAN gives such an op one monotone axis (bytes of input) that all + * of its phases share. + * + * ray_progress_span_begin declares the axis (bytes_total, e.g. the file size). + * ray_progress_span_phase declares that whatever runs next occupies + * [base, base+len) of that axis: the dispatch pump maps its own 0..100% into + * that window instead of publishing raw row counts, and a serial phase can + * drive the same window directly with ray_progress_span_set. The published + * value never decreases. All are no-ops with no callback registered. */ +void ray_progress_span_begin(const char* op_name, uint64_t bytes_total); +void ray_progress_span_phase(const char* phase, uint64_t base, uint64_t len); +void ray_progress_span_set(uint64_t bytes_done); +void ray_progress_span_end(void); + /* ===== COW / Ref Counting API ===== */ void ray_retain(ray_t* v); @@ -444,14 +494,14 @@ ray_t* ray_typed_null(int8_t type); * F32/F64 NaN NaN * GUID 16 all-zero bytes 16 all-zero bytes * BOOL/U8 ray_typed_null aux bit non-nullable - * SYM/STR no distinct null non-nullable + * SYM/STR canonical empty value canonical empty value * - * Empty SYM/STR values are ordinary values. A requested typed or input null - * for either type collapses to the ordinary empty value; its public null - * predicate remains false and a vector does not acquire HAS_NULLS. Callers - * compare sentinel-backed payloads directly (for example `x == NULL_I64` or - * `x != x` for NaN). Temporal types reuse NULL_I32 or NULL_I64 according to - * storage width. */ + * Empty SYM/STR values are their canonical in-band nulls. A requested typed + * or input null for either type collapses to that empty representation; the + * public null predicate recognizes it and vectors containing it acquire + * HAS_NULLS. Callers compare sentinel-backed payloads directly (for example + * `x == NULL_I64` or `x != x` for NaN). Temporal types reuse NULL_I32 or + * NULL_I64 according to storage width. */ #define NULL_I16 ((int16_t)INT16_MIN) #define NULL_I32 ((int32_t)INT32_MIN) #define NULL_I64 ((int64_t)INT64_MIN) @@ -460,8 +510,8 @@ ray_t* ray_typed_null(int8_t type); /* Atom null check. RAY_NULL_OBJ is the untyped null singleton. * Sentinel-backed atoms use payload comparison. BOOL/U8 typed-null atoms - * use the aux[0]&1 bit written by ray_typed_null. SYM/STR always return - * false because their empty payloads are ordinary values. */ + * use the aux[0]&1 bit written by ray_typed_null. SYM/STR use their + * canonical in-band empty values (sym 0 / "") as null. */ static inline bool ray_atom_is_null_fn(const union ray_t* x) { if (RAY_IS_NULL(x)) return true; if (x->type >= 0) return false; @@ -479,14 +529,11 @@ static inline bool ray_atom_is_null_fn(const union ray_t* x) { case RAY_TIME: return x->i32 == NULL_I32; case RAY_I16: return x->i16 == NULL_I16; case RAY_SYM: - /* SYM has no null — sym 0 is the empty symbol ' (a value), mirroring - * STR's empty "" below. A SYM atom is never null. */ - return false; + return x->i64 == 0; case RAY_STR: - /* STR has no null distinct from "" (char lists have no null, only - * symbols do). A STR atom is never null — the empty - * string is a value. */ - return false; + /* Empty SSO is the only STR atom whose value union is all zero; + * non-empty SSO and long-string pointers are both non-NULL. */ + return x->obj == NULL; case RAY_GUID: { /* GUID null = 16 all-zero bytes in obj's U8 buffer. * obj is always populated by ray_guid / ray_typed_null — @@ -516,6 +563,7 @@ ray_t* ray_vec_new(int8_t type, int64_t capacity); ray_t* ray_sym_vec_new(uint8_t sym_width, int64_t capacity); /* RAY_SYM with adaptive width */ ray_t* ray_vec_append(ray_t* vec, const void* elem); +ray_t* ray_vec_append_raw(ray_t* vec, const void* src, int64_t count); /* one reserve + one memcpy */ ray_t* ray_vec_set(ray_t* vec, int64_t idx, const void* elem); void* ray_vec_get(ray_t* vec, int64_t idx); ray_t* ray_vec_slice(ray_t* vec, int64_t offset, int64_t len); @@ -596,6 +644,7 @@ ray_err_t ray_env_set(int64_t sym_id, ray_t* val); ray_t* ray_table_new(int64_t ncols); ray_t* ray_table_add_col(ray_t* tbl, int64_t name_id, ray_t* col_vec); +ray_t* ray_table_validate_rectangular(ray_t* tbl, const char* context); ray_t* ray_table_get_col(ray_t* tbl, int64_t name_id); ray_t* ray_table_get_col_idx(ray_t* tbl, int64_t idx); int64_t ray_table_col_name(ray_t* tbl, int64_t idx); diff --git a/src/app/main.c b/src/app/main.c index fc9485431..06155c9eb 100644 --- a/src/app/main.c +++ b/src/app/main.c @@ -81,6 +81,7 @@ int main(int argc, char** argv) { int interactive = 0; const char* file = NULL; uint16_t port = 0; + char bind_host[64] = ""; /* -p HOST:PORT bind address; empty = all interfaces */ int n_cores = -1; /* total execution cores; -1 = leave pool lazy */ int timeit_init = 0; /* -t N: enable profiler at startup */ int qlog_init = 0; /* -Q N: enable query-statistics logging at startup */ @@ -91,7 +92,7 @@ int main(int argc, char** argv) { /* Parse args. Supported flags: * -f FILE run script file - * -p PORT IPC listen port + * -p PORT|HOST:PORT IPC listen port, optionally bound to HOST * -c N total execution cores, main included (0 = auto) * -t N enable timeit at startup (N != 0 turns on) * -Q N enable query-statistics logging (N != 0 turns on) @@ -103,8 +104,32 @@ int main(int argc, char** argv) { for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--interactive") == 0) interactive = 1; - else if ((strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--port") == 0) && i + 1 < argc) - port = (uint16_t)atoi(argv[++i]); + else if ((strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--port") == 0) && i + 1 < argc) { + /* PORT binds all interfaces; HOST:PORT confines the listener + * to one IPv4 address (#427). Strict digits-only port — a + * silently truncated "65536x" listener is worse than exiting. */ + const char* parg = argv[++i]; + const char* colon = strchr(parg, ':'); + const char* pstr = parg; + if (colon) { + size_t hlen = (size_t)(colon - parg); + if (hlen == 0 || hlen >= sizeof(bind_host)) { + fprintf(stderr, "bad -p bind address: %s\n", parg); + return 2; + } + memcpy(bind_host, parg, hlen); + bind_host[hlen] = '\0'; + pstr = colon + 1; + } + char* endp; + errno = 0; + long pv = strtol(pstr, &endp, 10); + if (endp == pstr || *endp != '\0' || errno == ERANGE || pv <= 0 || pv > 65535) { + fprintf(stderr, "bad -p port (must be 1..65535): %s\n", parg); + return 2; + } + port = (uint16_t)pv; + } else if ((strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--cores") == 0) && i + 1 < argc) { int v = atoi(argv[++i]); if (v < 0) v = 0; @@ -151,7 +176,8 @@ int main(int argc, char** argv) { "usage: %s [-f file] [-p port] [-c cores] [-t 0|1] [-i]" " [-u PW | -U PW] [-l BASE | -L BASE] [-m SIZE] [file.rfl] [-- app args]\n" " -f, --file FILE run script file (or pass as a positional arg)\n" - " -p, --port PORT listen for IPC clients on PORT\n" + " -p, --port PORT listen for IPC clients on PORT (all interfaces)\n" + " --port HOST:PORT bind the listener to HOST only (e.g. 127.0.0.1:7701)\n" " -c, --cores N total execution cores, main included (0 = auto)\n" " -t, --timeit N enable profiler at startup (N != 0)\n" " -i, --interactive start the REPL even after running a file\n" @@ -238,11 +264,12 @@ int main(int argc, char** argv) { /* Start IPC server if port specified */ if (port > 0) { - if (poll && ray_ipc_listen(poll, port) >= 0) - fprintf(stderr, "listening on port %u\n", port); + const char* bh = bind_host[0] ? bind_host : NULL; + if (poll && ray_ipc_listen_at(poll, bh, port) >= 0) + fprintf(stderr, "listening on %s:%u\n", bh ? bh : "*", port); else - fprintf(stderr, "failed to listen on port %u: %s\n", - port, strerror(errno)); + fprintf(stderr, "failed to listen on %s:%u: %s\n", + bh ? bh : "*", port, strerror(errno)); } /* Load script if specified */ diff --git a/src/app/repl.c b/src/app/repl.c index 32e5e65a7..80d8ecb50 100644 --- a/src/app/repl.c +++ b/src/app/repl.c @@ -40,6 +40,7 @@ #include "lang/parse.h" #include "lang/syscmd.h" #include "mem/heap.h" +#include "mem/sys.h" #include "ops/ops.h" #include "core/profile.h" #include "core/qlog.h" @@ -133,7 +134,8 @@ static const char* fmt_bytes(int64_t bytes, char* buf, size_t bufsz) { static void render_progress_full(int64_t done, int64_t total, const char* op, const char* phase, double elapsed_sec, - int64_t mem_used, int64_t mem_total) { + int64_t mem_used, int64_t mem_total, + int64_t bytes_done, int64_t bytes_total) { int cols = progress_term_cols(); /* Reserve a chunk for labels + percent + elapsed; give the rest * to the bar. Minimum bar is 10 cells, maximum 40. */ @@ -169,11 +171,22 @@ static void render_progress_full(int64_t done, int64_t total, (op && *op) ? ": " : " \xc2\xb7 ", phase); if (elapsed_sec > 0.0) tp += snprintf(tail + tp, sizeof(tail) - tp, " \xc2\xb7 %.1fs", elapsed_sec); + /* Byte-metered ops (CSV load) show input consumed / input size. It goes + * before the memory gauge because it is the thing the percentage is + * actually measuring. */ + if (bytes_total > 0) { + char db[16], tbb[16]; + fmt_bytes(bytes_done, db, sizeof(db)); + fmt_bytes(bytes_total, tbb, sizeof(tbb)); + tp += snprintf(tail + tp, sizeof(tail) - tp, " \xc2\xb7 %s/%s", db, tbb); + } + /* Live heap footprint against physical RAM — explicitly labelled "mem" + * so it can't be misread as a position in the input. */ if (mem_used > 0 && mem_total > 0) { char ub[16], tb[16]; fmt_bytes(mem_used, ub, sizeof(ub)); fmt_bytes(mem_total, tb, sizeof(tb)); - tp += snprintf(tail + tp, sizeof(tail) - tp, " \xc2\xb7 %s/%s", ub, tb); + tp += snprintf(tail + tp, sizeof(tail) - tp, " \xc2\xb7 mem %s/%s", ub, tb); } /* Clear the line first, then draw. Using \e[2K avoids leaving @@ -215,7 +228,8 @@ static void repl_query_progress_cb(const ray_progress_t* p, void* user) { if (p->final) { clear_progress(); return; } render_progress_full((int64_t)p->rows_done, (int64_t)p->rows_total, p->op_name, p->phase, p->elapsed_sec, - p->mem_used, p->mem_total); + p->mem_used, p->mem_total, + (int64_t)p->bytes_done, (int64_t)p->bytes_total); } /* ===== Profiler span tree printer (reads from g_ray_profile) ===== */ @@ -654,6 +668,56 @@ ray_t* ray_repl_disconnect_fn(ray_t** args, int64_t n) { return RAY_NULL_OBJ; } +/* strcmp comparator over char* cells, for sorting completion candidates. */ +static int repl_comp_cmp(const void* a, const void* b) { + return strcmp(*(const char* const*)a, *(const char* const*)b); +} + +/* (.repl.complete "prefix") -> sorted sym vector of namespace candidates + * whose name begins with `prefix`: builtins, keywords, and user bindings. + * + * This is the engine side of the REPL's own tab-completion (issue #441), + * exposed as a read-only verb so editor tooling can query it over IPC and + * get semantic completion of names the engine knows in the live session, + * not just a static keyword list. It reuses ray_env_lookup_prefix — the + * same primitive the terminal client's completion draws from — so the two + * can never drift. History-word completion is intentionally omitted: it + * is client-local and meaningless to a remote caller. */ +ray_t* ray_repl_complete_fn(ray_t* prefix_str) { + if (!ray_is_atom(prefix_str) || prefix_str->type != -RAY_STR) + return ray_error("type", ".repl.complete expects a string prefix, got %s", + ray_type_name(prefix_str->type)); + + const char* prefix = ray_str_ptr(prefix_str); + int64_t plen = (int64_t)ray_str_len(prefix_str); + + /* Size the candidate buffer to cover every global binding plus + * headroom for the static keyword list. ray_env_lookup_prefix caps + * itself at max_results and dedups, so this never overruns. */ + int64_t cap = (int64_t)ray_env_global_count() + 256; + const char** results = (const char**)ray_sys_alloc((size_t)cap * sizeof(const char*)); + if (!results) return ray_error("oom", NULL); + + int64_t count = ray_env_lookup_prefix(prefix ? prefix : "", plen, results, cap); + + /* Sort for a stable, editor-friendly ordering (mirrors .fs.list). */ + if (count > 1) + qsort(results, (size_t)count, sizeof(const char*), repl_comp_cmp); + + ray_t* out = ray_vec_new(RAY_SYM, count); + if (!out || RAY_IS_ERR(out)) { + ray_sys_free(results); + return out ? out : ray_error("oom", NULL); + } + out->len = count; + int64_t* ids = (int64_t*)ray_data(out); + for (int64_t i = 0; i < count; i++) + ids[i] = ray_sym_intern(results[i], strlen(results[i])); + + ray_sys_free(results); + return out; +} + /* eval_and_print's remote branch: send the raw input string to the * connected server with RAY_IPC_FLAG_VERBOSE set so server-side * stdout/stderr written during eval are captured and returned to us @@ -810,6 +874,15 @@ static void eval_and_print(ray_term_t* term, const char* input, if (profiling) profile_print(use_color); ray_heap_gc(); + /* Statement boundary. Check BEFORE stamping: the clock still holds the + * end of the previous statement, so what we measure is the gap between + * statements — the time the process actually sat idle. Stamping first + * would measure this statement's own duration instead, and a loop of + * statements longer than the threshold would then sweep after every one + * of them, discarding the working set the next is about to fault back + * in. */ + ray_heap_decay(); + ray_heap_note_activity(); } /* `type_label` and `cmd_match` were inlined into the previous bespoke @@ -856,6 +929,11 @@ static bool handle_command(ray_repl_t* repl, const char* str, size_t len) { ray_release(result); } + /* A piped REPL uses block-buffered stdout. Every command response is + * complete at this boundary, including output printed by handlers and + * errors printed above, so make it visible before waiting for more input. */ + fflush(stdout); + /* Track timeit echoing so the prompt reflects current state. */ repl->timeit = g_ray_profile.active; return true; @@ -1320,6 +1398,15 @@ int ray_repl_run_file(const char* path) { /* profile tree goes to stdout via profile_print; honour stdout's tty. */ if (profiling) profile_print(color_out); + /* A whole file is one unit of work, and unlike the REPL there is no + * decay check after it — so stamp at the END, not the start. A script + * that exits has nothing to give back; a script that starts a server + * and hands over to the poll loop leaves its load-time temporaries + * resident, and this is what lets the loop notice them. Stamping at + * the start would instead arm a check that the script's own (.sys.gc) + * calls would service mid-run, which is the one thing the threshold + * exists to avoid. */ + ray_heap_note_activity(); ray_heap_gc(); return rc; } diff --git a/src/app/repl.h b/src/app/repl.h index 80807bfa8..133e4df82 100644 --- a/src/app/repl.h +++ b/src/app/repl.h @@ -61,5 +61,6 @@ const char* ray_repl_remote_addr(void); ray_t* ray_repl_connect_fn(ray_t* host_port_str); ray_t* ray_repl_disconnect_fn(ray_t** args, int64_t n); +ray_t* ray_repl_complete_fn(ray_t* prefix_str); #endif /* RAY_IO_REPL_H */ diff --git a/src/core/epoll.c b/src/core/epoll.c index 680e73f2a..17fb05a32 100644 --- a/src/core/epoll.c +++ b/src/core/epoll.c @@ -26,6 +26,7 @@ #include "core/poll.h" #include "core/timer.h" #include "mem/sys.h" +#include "mem/heap.h" /* idle decay: bound the wait, sweep after wakeup */ #include #include #include @@ -186,6 +187,23 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) } } + /* A process waiting here is a process doing nothing, and this is the + * only moment it gets to notice. Bound the wait by the allocator's + * pending decay exactly as a timer would; once the decay has run + * there is nothing pending and the wait goes back to indefinite. + * + * Only when the loop is unbounded. ray_poll_run_for carries the + * caller's own deadline and runs a single pass, so shortening its + * wait here returns from it early with nothing done — a timer the + * caller was waiting on would not have fired yet. */ + { + int64_t decay = bounded ? -1 : ray_heap_decay_due_ms(); + if (decay >= 0) { + if (decay > INT_MAX) decay = INT_MAX; + if (wait_ms < 0 || decay < wait_ms) wait_ms = (int)decay; + } + } + int n = epoll_wait((int)poll->fd, events, RAY_POLL_MAX_EVENTS, wait_ms); if (n < 0) { if (errno == EINTR) continue; @@ -272,8 +290,18 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) next_event:; } - if (poll->timers) - ray_timers_fire_expired((ray_timers_t*)poll->timers); + if (poll->timers) { + /* A fired timer is work, and on a timer-driven server it is the + * only work there is: without this stamp the decay sees an idle + * process mid-workload, and — having disarmed itself — never + * looks again. */ + if (ray_timers_fire_expired((ray_timers_t*)poll->timers) > 0) + ray_heap_note_activity(); + } + /* After the events of this wakeup, not before: a request handled + * above has just re-stamped the activity clock, so a busy loop + * finds nothing due and pays one timestamp comparison. */ + ray_heap_decay(); if (bounded) break; } diff --git a/src/core/ipc.c b/src/core/ipc.c index 00b96cb75..dd8032aff 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -26,6 +26,7 @@ #endif #include "core/ipc.h" +#include "mem/heap.h" #include "mem/sys.h" #include "ops/ops.h" #include "store/journal.h" @@ -975,6 +976,11 @@ static ray_t* ipc_read_payload(ray_poll_t* poll, ray_selector_t* sel) send_response((ray_sock_t)cur->fd, result); } if (result != RAY_NULL_OBJ) ray_release(result); + /* The request is served: this is the end of the server's unit of work, + * and stamping here is what lets the poll loop tell an idle server from + * one between two requests. Stamping on frame arrival instead would + * make the measured gap the request's own duration. */ + ray_heap_note_activity(); return NULL; } @@ -1012,12 +1018,12 @@ static void ipc_on_close(ray_poll_t* poll, ray_selector_t* sel) ray_sock_close((ray_sock_t)sel->fd); } -int64_t ray_ipc_listen(ray_poll_t* poll, uint16_t port) +int64_t ray_ipc_listen_at(ray_poll_t* poll, const char* host, uint16_t port) { if (!poll) return -1; ipc_install_oob_cancel(); /* enable client Ctrl-C → SIGURG query cancel */ - ray_sock_t fd = ray_sock_listen(port); + ray_sock_t fd = ray_sock_listen_at(host, port); if (fd == RAY_INVALID_SOCK) return -1; ray_sock_set_nonblocking(fd); @@ -1035,6 +1041,11 @@ int64_t ray_ipc_listen(ray_poll_t* poll, uint16_t port) return id; } +int64_t ray_ipc_listen(ray_poll_t* poll, uint16_t port) +{ + return ray_ipc_listen_at(poll, NULL, port); +} + /* ====================================================================== * Server API * ====================================================================== */ @@ -1141,6 +1152,11 @@ static void conn_on_payload(ray_ipc_server_t* srv, ray_ipc_conn_t* c) if (c->hdr.msgtype == RAY_IPC_MSG_SYNC) send_response(c->fd, result); if (result != RAY_NULL_OBJ) ray_release(result); + /* The request is served: this is the end of the server's unit of work, + * and stamping here is what lets the poll loop tell an idle server from + * one between two requests. Stamping on frame arrival instead would + * make the measured gap the request's own duration. */ + ray_heap_note_activity(); ray_sys_free(c->rx_buf); c->rx_buf = NULL; @@ -1213,10 +1229,10 @@ static void conn_on_readable(ray_ipc_server_t* srv, ray_ipc_conn_t* c) } } -ray_err_t ray_ipc_server_init(ray_ipc_server_t* srv, uint16_t port) +ray_err_t ray_ipc_server_init_at(ray_ipc_server_t* srv, const char* host, uint16_t port) { memset(srv, 0, sizeof(*srv)); - srv->listen_fd = ray_sock_listen(port); + srv->listen_fd = ray_sock_listen_at(host, port); if (srv->listen_fd == RAY_INVALID_SOCK) return RAY_ERR_IO; ray_sock_set_nonblocking(srv->listen_fd); @@ -1245,6 +1261,11 @@ ray_err_t ray_ipc_server_init(ray_ipc_server_t* srv, uint16_t port) return RAY_OK; } +ray_err_t ray_ipc_server_init(ray_ipc_server_t* srv, uint16_t port) +{ + return ray_ipc_server_init_at(srv, NULL, port); +} + void ray_ipc_server_destroy(ray_ipc_server_t* srv) { for (uint32_t i = 0; i < srv->n_conns; i++) { diff --git a/src/core/ipc.h b/src/core/ipc.h index f880c2ad8..98bce8987 100644 --- a/src/core/ipc.h +++ b/src/core/ipc.h @@ -77,6 +77,8 @@ int64_t ray_ipc_current_handle(void); /* Register IPC listener on poll. Returns selector id or -1. */ int64_t ray_ipc_listen(ray_poll_t* poll, uint16_t port); +/* Bind to a specific IPv4 address; host NULL/empty means INADDR_ANY (#427). */ +int64_t ray_ipc_listen_at(ray_poll_t* poll, const char* host, uint16_t port); /* ===== Legacy server API (wraps poll internally for tests) ===== */ @@ -100,6 +102,7 @@ typedef struct ray_ipc_server { } ray_ipc_server_t; ray_err_t ray_ipc_server_init(ray_ipc_server_t* srv, uint16_t port); +ray_err_t ray_ipc_server_init_at(ray_ipc_server_t* srv, const char* host, uint16_t port); void ray_ipc_server_destroy(ray_ipc_server_t* srv); int ray_ipc_poll(ray_ipc_server_t* srv, int timeout_ms); diff --git a/src/core/kqueue.c b/src/core/kqueue.c index 0a5d43497..b73d89bb1 100644 --- a/src/core/kqueue.c +++ b/src/core/kqueue.c @@ -26,6 +26,7 @@ #include "core/poll.h" #include "core/timer.h" #include "mem/sys.h" +#include "mem/heap.h" /* idle decay: bound the wait, sweep after wakeup */ #include #include #include @@ -188,6 +189,21 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) } } + /* A process waiting here is a process doing nothing, and this is the + * only moment it gets to notice. Bound the wait by the allocator's + * pending decay exactly as a timer would; once the decay has run + * there is nothing pending and the wait goes back to indefinite. + * + * Only when the loop is unbounded. ray_poll_run_for carries the + * caller's own deadline and runs a single pass, so shortening its + * wait here returns from it early with nothing done — a timer the + * caller was waiting on would not have fired yet. */ + if (!bounded) { + int64_t decay = ray_heap_decay_due_ms(); + if (decay >= 0 && (wait_ms < 0 || decay < wait_ms)) + wait_ms = decay; + } + struct timespec ts; struct timespec* timeout = NULL; if (wait_ms >= 0) { @@ -276,8 +292,18 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) next_event:; } - if (poll->timers) - ray_timers_fire_expired((ray_timers_t*)poll->timers); + if (poll->timers) { + /* A fired timer is work, and on a timer-driven server it is the + * only work there is: without this stamp the decay sees an idle + * process mid-workload, and — having disarmed itself — never + * looks again. */ + if (ray_timers_fire_expired((ray_timers_t*)poll->timers) > 0) + ray_heap_note_activity(); + } + /* After the events of this wakeup, not before: a request handled + * above has just re-stamped the activity clock, so a busy loop + * finds nothing due and pays one timestamp comparison. */ + ray_heap_decay(); if (bounded) break; } diff --git a/src/core/pool.c b/src/core/pool.c index f7977ab9d..d883e9da2 100644 --- a/src/core/pool.c +++ b/src/core/pool.c @@ -78,7 +78,8 @@ static void worker_loop(void* arg) { ray_pool_t* pool = wctx.pool; - /* Each worker thread gets its own heap */ + /* Each worker thread gets its own heap — a fresh one, or one abandoned + * by an earlier worker (pools and slab caches intact). */ ray_heap_init(); ray_rc_sync = true; /* workers always use atomic refcounting */ @@ -113,7 +114,13 @@ static void worker_loop(void* arg) { * Eager madvise in heap_coalesce already releases pages on free. */ } - ray_heap_destroy(); + /* Abandon, do not destroy. Another thread may still hold — and later + * free — a block that came out of this heap, and the cross-thread free + * path resolves the owning heap through the registry without a lock, so + * a heap that could be unregistered and munmapped underneath that lookup + * would be a use-after-free. The heap stays registered with its pools + * and is adopted by the next worker thread that starts. */ + ray_heap_abandon(); } /* -------------------------------------------------------------------------- diff --git a/src/core/progress.c b/src/core/progress.c index 31dc8a6df..5d350dc8e 100644 --- a/src/core/progress.c +++ b/src/core/progress.c @@ -58,6 +58,14 @@ static uint64_t g_phase_base; /* qstats rows_done at dispatch start */ static uint64_t g_phase_total; /* elements this dispatch will process */ static uint64_t g_last_pump_ns; /* throttles the 256-slot sum */ +/* Byte-metered span state (main-thread only). g_span_total != 0 is the + * "a span is active" flag; while it is set the dispatch pump publishes a + * position on the byte axis instead of raw row counts. */ +static uint64_t g_span_total; /* size of the axis, 0 = no span */ +static uint64_t g_span_done; /* monotone position on the axis */ +static uint64_t g_span_base; /* current phase's window start */ +static uint64_t g_span_len; /* current phase's window length */ + static inline uint64_t mono_ns(void) { struct timespec ts; #ifdef CLOCK_MONOTONIC_COARSE @@ -93,6 +101,8 @@ static void fire(uint64_t now_ns, bool final) { .mem_used = (int64_t)(ms.bytes_allocated + ms.direct_bytes), .mem_total = ray_sys_total_ram(), .final = final, + .bytes_done = g_span_total ? g_span_done : 0, + .bytes_total = g_span_total, }; g_cb(&snap, g_user); g_last_fire_ns = now_ns; @@ -194,10 +204,59 @@ void ray_progress_pump(void) { g_last_pump_ns = now; uint64_t sum = ray_qstats_sum_rows(); uint64_t done = sum > g_phase_base ? sum - g_phase_base : 0; + if (g_span_total) { + /* Map this dispatch's own 0..100% into the phase's slice of the + * byte axis. A dispatch that runs without a phase declared (some + * nested helper) simply re-covers the last slice; the monotone + * clamp in ray_progress_span_set turns that into a pause, never a + * step backwards. */ + double frac = g_phase_total ? (double)done / (double)g_phase_total : 0.0; + if (frac > 1.0) frac = 1.0; + ray_progress_span_set(g_span_base + (uint64_t)(frac * (double)g_span_len)); + return; + } ray_progress_update(NULL, NULL, done, g_phase_total); /* keeps op label */ } +/* ── byte-metered span ─────────────────────────────────────────────────── */ + +void ray_progress_span_begin(const char* op_name, uint64_t bytes_total) { + if (!g_cb || bytes_total == 0) return; + g_span_total = bytes_total; + g_span_done = 0; + g_span_base = 0; + g_span_len = 0; + ray_progress_label(op_name, NULL); +} + +void ray_progress_span_phase(const char* phase, uint64_t base, uint64_t len) { + if (!g_cb || !g_span_total) return; + if (base > g_span_total) base = g_span_total; + if (base + len > g_span_total) len = g_span_total - base; + g_span_base = base; + g_span_len = len; + if (phase) g_phase = phase; + /* A phase boundary is also a floor: everything before it is done. */ + ray_progress_span_set(base); +} + +void ray_progress_span_set(uint64_t bytes_done) { + if (!g_cb || !g_span_total) return; + if (bytes_done > g_span_total) bytes_done = g_span_total; + if (bytes_done < g_span_done) return; /* monotone by construction */ + g_span_done = bytes_done; + ray_progress_update(NULL, NULL, g_span_done, g_span_total); +} + +void ray_progress_span_end(void) { + g_span_total = 0; + g_span_done = 0; + g_span_base = 0; + g_span_len = 0; +} + void ray_progress_end(void) { + ray_progress_span_end(); if (!g_cb) { g_start_ns = 0; return; diff --git a/src/core/sock.c b/src/core/sock.c index 5a5f83132..b462aa8ed 100644 --- a/src/core/sock.c +++ b/src/core/sock.c @@ -48,8 +48,22 @@ /* ===== Socket Implementation ===== */ -ray_sock_t ray_sock_listen(uint16_t port) +ray_sock_t ray_sock_listen_at(const char* host, uint16_t port) { + /* NULL/empty host keeps the historical INADDR_ANY bind. A host that + * does not parse as an IPv4 address is a loud bind failure — never a + * silent fallback to all interfaces, which would defeat the point of + * asking for a confined listener. */ + struct in_addr bind_addr; + if (host && *host) { + if (inet_pton(AF_INET, host, &bind_addr) != 1) { + errno = EINVAL; + return RAY_INVALID_SOCK; + } + } else { + bind_addr.s_addr = htonl(INADDR_ANY); + } + ray_sock_t fd = (ray_sock_t)socket(AF_INET, SOCK_STREAM, 0); if (fd == RAY_INVALID_SOCK) return RAY_INVALID_SOCK; @@ -59,7 +73,7 @@ ray_sock_t ray_sock_listen(uint16_t port) struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; - addr.sin_addr.s_addr = htonl(INADDR_ANY); + addr.sin_addr = bind_addr; addr.sin_port = htons(port); if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { @@ -73,6 +87,11 @@ ray_sock_t ray_sock_listen(uint16_t port) return fd; } +ray_sock_t ray_sock_listen(uint16_t port) +{ + return ray_sock_listen_at(NULL, port); +} + ray_sock_t ray_sock_accept(ray_sock_t srv) { ray_sock_t fd; diff --git a/src/core/sock.h b/src/core/sock.h index e8ea2f0aa..c11b6691d 100644 --- a/src/core/sock.h +++ b/src/core/sock.h @@ -37,6 +37,9 @@ #endif ray_sock_t ray_sock_listen(uint16_t port); +/* Bind to a specific IPv4 address; host NULL/empty means INADDR_ANY. An + * unparseable host fails the listen (errno EINVAL), never falls back. */ +ray_sock_t ray_sock_listen_at(const char* host, uint16_t port); ray_sock_t ray_sock_accept(ray_sock_t srv); /* Connect to host:port. timeout_ms > 0 bounds the connect: the socket * connects non-blocking and waits at most timeout_ms for completion (a diff --git a/src/core/timer.c b/src/core/timer.c index 4c9003d5b..ad1112fa0 100644 --- a/src/core/timer.c +++ b/src/core/timer.c @@ -167,14 +167,16 @@ int64_t ray_timers_next_deadline_ms(ray_timers_t* t) { return t->heap[0]->exp_ms; } -void ray_timers_fire_expired(ray_timers_t* t) { - if (!t || t->n == 0) return; +uint32_t ray_timers_fire_expired(ray_timers_t* t) { + if (!t || t->n == 0) return 0; int64_t now = ray_time_now_ms(); + uint32_t fired = 0; while (t->n > 0 && t->heap[0]->exp_ms <= now) { /* Pop the head: swap with tail, sift down. */ ray_timer_t* timer = t->heap[0]; + fired++; t->n--; if (t->n > 0) { t->heap[0] = t->heap[t->n]; @@ -225,6 +227,7 @@ void ray_timers_fire_expired(ray_timers_t* t) { /* Refresh `now` in case callbacks took meaningful time. */ now = ray_time_now_ms(); } + return fired; } void ray_timers_pump_for(ray_timers_t* t, int64_t budget_ms) { diff --git a/src/core/timer.h b/src/core/timer.h index 487c1e93d..0a5c83c36 100644 --- a/src/core/timer.h +++ b/src/core/timer.h @@ -65,7 +65,8 @@ int64_t ray_timers_next_deadline_ms(ray_timers_t* t); /* Fire every timer whose exp_ms <= now. Pops, calls callback via call_fn1, * then either re-pushes (forever / num>1) or frees (num==1 / num==0 one-shot). * Callback errors are printed to stderr and counted as a successful fire. */ -void ray_timers_fire_expired(ray_timers_t* t); +/* Fire every timer whose deadline has passed; returns how many ran. */ +uint32_t ray_timers_fire_expired(ray_timers_t* t); /* Current monotonic time in milliseconds. */ int64_t ray_time_now_ms(void); diff --git a/src/core/types.h b/src/core/types.h index bfbd765d1..c70b4dd65 100644 --- a/src/core/types.h +++ b/src/core/types.h @@ -73,4 +73,17 @@ static inline uint8_t ray_cast_f64_to_bool_null(double v) { return (v == v && v != 0.0) ? 1 : 0; } +/* Two's-complement wraparound integer add/mul. Signed overflow is UB in C; + * aggregate reductions (sum / prod, and their parted / table-scan / affine + * kernels) use these so an overflowing accumulator wraps deterministically + * rather than trapping. At -O2/-O3 they inline to a bare add/mul and do not + * inhibit autovectorization (signed and unsigned 64-bit add are the same ISA + * instruction). */ +static inline int64_t wrap_add_i64(int64_t a, int64_t b) { + return (int64_t)((uint64_t)a + (uint64_t)b); +} +static inline int64_t wrap_mul_i64(int64_t a, int64_t b) { + return (int64_t)((uint64_t)a * (uint64_t)b); +} + #endif /* RAY_TYPES_H */ diff --git a/src/io/csv.c b/src/io/csv.c index 153c128f3..ebe7338f6 100644 --- a/src/io/csv.c +++ b/src/io/csv.c @@ -43,10 +43,9 @@ #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 */ +#include "ops/idxop.h" /* ray_index_payload — shared hash-upgrade policy */ #include "store/col.h" #include "store/fileio.h" #include "store/splay.h" @@ -77,6 +76,29 @@ #define CSV_STR_DISTINCT_MIN 256 #define CSV_PART_ROWS_DEFAULT 1000000 +/* -------------------------------------------------------------------------- + * Whole-load progress axis. + * + * A CSV load is four phases that each traverse the file once, so no single + * counter (rows, morsels, dispatched elements) describes the load as a whole + * and every per-dispatch bar restarts at zero. The honest shared metric is + * BYTES OF INPUT, and each phase owns a fixed slice of that axis, weighted by + * its measured cost. Measured on an 8.1 GB / 10M-row / 105-column load with + * the parallel scan, per-column finalize and no load-time index attach: + * row-offset scan 4.34 s, parse 6.68 s, finalize (str fill + sym intern) + * 4.60 s, tail (sym max/narrow, table build) 0.58 s of 16.2 s. Rounded to + * 27 / 41 / 32, the tail riding in the finalize slice. The mix shifts with + * column types and core count, so these are pacing estimates — nothing + * depends on them for correctness. + * -------------------------------------------------------------------------- */ +#define CSV_PROG_PCT_SCAN 27 +#define CSV_PROG_PCT_PARSE 41 + +/* Byte position of `pct` percent along a file-sized axis. */ +static inline uint64_t csv_prog_at(size_t file_size, unsigned pct) { + return (uint64_t)((double)file_size * (double)pct / 100.0); +} + /* -------------------------------------------------------------------------- * mmap flags * -------------------------------------------------------------------------- */ @@ -157,6 +179,10 @@ csv_type_t csv_resolve_int_width(int64_t min, int64_t max, bool has_null) { return CSV_TYPE_I64; } +RAY_INLINE int32_t fast_date(const char* p, size_t len, bool* is_null); +RAY_INLINE int32_t fast_time(const char* p, size_t len, bool* is_null); +RAY_INLINE int64_t fast_timestamp(const char* p, size_t len, bool* is_null); + static csv_type_t detect_type(const char* f, size_t len) { if (len == 0) return CSV_TYPE_UNKNOWN; @@ -207,35 +233,20 @@ static csv_type_t detect_type(const char* f, size_t len) { return CSV_TYPE_F64; } - /* Date: YYYY-MM-DD (exactly 10 chars) or Timestamp: YYYY-MM-DD{T| }HH:MM:SS */ - if (len >= 10 && f[4] == '-' && f[7] == '-') { - bool is_date = true; - for (int i = 0; i < 10; i++) { - if (i == 4 || i == 7) continue; - if ((unsigned)(f[i] - '0') > 9) { is_date = false; break; } - } - if (is_date) { - if (len == 10) return CSV_TYPE_DATE; - if (len >= 19 && (f[10] == 'T' || f[10] == ' ') && - f[13] == ':' && f[16] == ':') { - const int tp[] = {11,12,14,15,17,18}; - bool is_ts = true; - for (int i = 0; i < 6; i++) { - if ((unsigned)(f[tp[i]] - '0') > 9) { is_ts = false; break; } - } - if (is_ts) return CSV_TYPE_TIMESTAMP; - } - } + /* Temporal inference must share the strict full-consumption grammar used + * by typed ingest. Prefix-only checks would infer TIME/TIMESTAMP for + * malformed cells like "12:34:56 EST" or "2024-01-02 01:02:03 UTC", then + * the strict row parser would silently null the entire inferred column. */ + bool temporal_null = true; + if (len >= 19) { + (void)fast_timestamp(f, len, &temporal_null); + if (!temporal_null) return CSV_TYPE_TIMESTAMP; } - - /* Time: HH:MM:SS[.ffffff] (at least 8 chars) */ - if (len >= 8 && f[2] == ':' && f[5] == ':') { - const int tp[] = {0,1,3,4,6,7}; - bool is_time = true; - for (int i = 0; i < 6; i++) { - if ((unsigned)(f[tp[i]] - '0') > 9) { is_time = false; break; } - } - if (is_time) return CSV_TYPE_TIME; + (void)fast_time(f, len, &temporal_null); + if (!temporal_null) return CSV_TYPE_TIME; + if (len == 10) { + (void)fast_date(f, len, &temporal_null); + if (!temporal_null) return CSV_TYPE_DATE; } return CSV_TYPE_STR; @@ -493,13 +504,35 @@ RAY_INLINE int32_t civil_to_days(int y, int m, int d) { return (int32_t)(era * 146097 + doe - 719468 - 10957); } +/* Strict YYYY-MM-DD: exactly 10 chars, '-' separators at offsets 4/7, and + * digits in every field. Mirrors detect_type() and csv_write_date() so that + * typed .csv.read [DATE] round-trips the writer's output while rejecting + * malformed separators or trailing garbage (e.g. "2024/01/02", "2024x01x02", + * "2024-01-02junk") as null instead of silently coercing them to a bogus + * date. fast_timestamp() reuses this on the leading date (passing len 10). */ RAY_INLINE int32_t fast_date(const char* p, size_t len, bool* is_null) { - if (RAY_UNLIKELY(len < 10)) { *is_null = true; return 0; } + if (RAY_UNLIKELY(len != 10 || p[4] != '-' || p[7] != '-')) { *is_null = true; return 0; } + if (RAY_UNLIKELY((unsigned)(p[0]-'0') > 9u || (unsigned)(p[1]-'0') > 9u || + (unsigned)(p[2]-'0') > 9u || (unsigned)(p[3]-'0') > 9u || + (unsigned)(p[5]-'0') > 9u || (unsigned)(p[6]-'0') > 9u || + (unsigned)(p[8]-'0') > 9u || (unsigned)(p[9]-'0') > 9u)) { + *is_null = true; return 0; + } *is_null = false; int y = (p[0]-'0')*1000 + (p[1]-'0')*100 + (p[2]-'0')*10 + (p[3]-'0'); int m = (p[5]-'0')*10 + (p[6]-'0'); int d = (p[8]-'0')*10 + (p[9]-'0'); - if (RAY_UNLIKELY(m < 1 || m > 12 || d < 1 || d > 31)) { *is_null = true; return 0; } + /* Reject impossible months (this also guards the md[] index below) and + * days. A blanket d<=31 check let calendar-impossible dates like + * "2024-02-31" or "2024-04-31" through; civil_to_days() then normalized + * them into a *different* real day (2024-02-31 -> 2024.03.02), silently + * corrupting the value instead of nulling it. Validate the day against + * the actual length of that (leap-aware) month, mirroring the strict DATE + * string cast in ray_cast_fn() (src/ops/builtins.c). */ + if (RAY_UNLIKELY(m < 1 || m > 12 || d < 1)) { *is_null = true; return 0; } + static const int 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 (RAY_UNLIKELY(d > md[m] + (m == 2 && leap ? 1 : 0))) { *is_null = true; return 0; } return civil_to_days(y, m, d); } @@ -509,11 +542,12 @@ RAY_INLINE int32_t fast_date(const char* p, size_t len, bool* is_null) { * or >=24h duration verbatim — a leading '-' plus an unbounded hour field * (e.g. "-00:00:01", "25:00:00") rather than wrapping modulo a day. Parse * that same shape back so .csv.write -> .csv.read [TIME] round-trips: an - * optional sign, a variable-width hour field (NOT capped at 23), then MM:SS - * with an optional fractional part. MM/SS stay at the fixed offsets after - * the hour field and the separator characters are not themselves validated, - * matching the historical lenient behaviour. A magnitude that overflows - * int32 milliseconds is rejected as null. */ + * optional sign, a variable-width hour field (NOT capped at 23), then ":MM:SS" + * with an optional fractional part. The ':' separators and the MM/SS/fraction + * digits ARE validated and the field must be fully consumed, so malformed + * separators or trailing garbage (e.g. "12-34-56", "12:34:56xyz") are rejected + * as null rather than silently coerced. A magnitude that overflows int32 + * milliseconds is likewise rejected as null. */ RAY_INLINE int32_t fast_time(const char* p, size_t len, bool* is_null) { *is_null = false; size_t o = 0; @@ -528,21 +562,30 @@ RAY_INLINE int32_t fast_time(const char* p, size_t len, bool* is_null) { if (RAY_UNLIKELY(++hd - o > 7)) { *is_null = true; return 0; } } size_t w = hd - o; /* hour digit count */ - /* Need the hour field plus ":MM:SS" (6 more chars). */ + /* Need the hour field plus ":MM:SS" (6 more chars), with ':' separators + * and digit MM/SS fields. */ if (RAY_UNLIKELY(w == 0 || o + w + 6 > len)) { *is_null = true; return 0; } + if (RAY_UNLIKELY(p[o+w] != ':' || p[o+w+3] != ':')) { *is_null = true; return 0; } + if (RAY_UNLIKELY((unsigned)(p[o+w+1]-'0') > 9u || (unsigned)(p[o+w+2]-'0') > 9u || + (unsigned)(p[o+w+4]-'0') > 9u || (unsigned)(p[o+w+5]-'0') > 9u)) { + *is_null = true; return 0; + } int mi = (p[o+w+1]-'0')*10 + (p[o+w+2]-'0'); int s = (p[o+w+4]-'0')*10 + (p[o+w+5]-'0'); if (RAY_UNLIKELY(mi > 59 || s > 59)) { *is_null = true; return 0; } int64_t ms = h * 3600000 + (int64_t)mi * 60000 + (int64_t)s * 1000; - /* Fractional seconds → milliseconds */ - size_t fi = o + w + 6; - if (fi < len && p[fi] == '.') { + /* Fractional seconds → milliseconds. '.' must be followed by >=1 digit; + * only the first 3 contribute, but any further digits are consumed so the + * full-consumption check below still rejects non-digit trailing garbage. */ + size_t i = o + w + 6; + if (i < len) { + if (RAY_UNLIKELY(p[i] != '.')) { *is_null = true; return 0; } + i++; int frac = 0, digits = 0; - for (size_t i = fi + 1; i < len && digits < 3; i++, digits++) { - unsigned di = (unsigned char)p[i] - '0'; - if (di > 9) break; - frac = frac * 10 + (int)di; + for (; i < len && (unsigned)(p[i]-'0') <= 9u; i++) { + if (digits < 3) { frac = frac * 10 + (p[i] - '0'); digits++; } } + if (RAY_UNLIKELY(digits == 0 || i != len)) { *is_null = true; return 0; } while (digits < 3) { frac *= 10; digits++; } ms += frac; } @@ -557,7 +600,12 @@ RAY_INLINE int32_t fast_time(const char* p, size_t len, bool* is_null) { * to 9 fractional digits; shorter fractions are right-padded with * zeros, longer ones are truncated. */ RAY_INLINE int64_t fast_time_ns(const char* p, size_t len, bool* is_null, size_t* consumed) { - if (RAY_UNLIKELY(len < 8)) { *is_null = true; return 0; } + if (RAY_UNLIKELY(len < 8 || p[2] != ':' || p[5] != ':')) { *is_null = true; return 0; } + if (RAY_UNLIKELY((unsigned)(p[0]-'0') > 9u || (unsigned)(p[1]-'0') > 9u || + (unsigned)(p[3]-'0') > 9u || (unsigned)(p[4]-'0') > 9u || + (unsigned)(p[6]-'0') > 9u || (unsigned)(p[7]-'0') > 9u)) { + *is_null = true; return 0; + } *is_null = false; int h = (p[0]-'0')*10 + (p[1]-'0'); int mi = (p[3]-'0')*10 + (p[4]-'0'); @@ -570,11 +618,12 @@ RAY_INLINE int64_t fast_time_ns(const char* p, size_t len, bool* is_null, size_t int64_t frac = 0; int digits = 0; size_t i = 9; - for (; i < len && digits < 9; i++, digits++) { - unsigned di = (unsigned char)p[i] - '0'; - if (di > 9) break; - frac = frac * 10 + (int64_t)di; + /* First 9 fractional digits contribute; consume any further digits so + * the caller's full-consumption check still rejects trailing garbage. */ + for (; i < len && (unsigned)(p[i]-'0') <= 9u; i++) { + if (digits < 9) { frac = frac * 10 + (int64_t)(p[i] - '0'); digits++; } } + if (RAY_UNLIKELY(digits == 0)) { *is_null = true; return 0; } while (digits < 9) { frac *= 10; digits++; } ns += frac; used = i; /* index of the first char past the fractional seconds */ @@ -586,12 +635,12 @@ RAY_INLINE int64_t fast_time_ns(const char* p, size_t len, bool* is_null, size_t /* Parse a trailing ISO-8601 UTC offset at p: 'Z'/'z' (== UTC) or * (+|-)HH[[:]MM]. On success sets *out_ns to the signed offset in * nanoseconds (to be SUBTRACTED from the local wall-clock value to get - * UTC) and returns true. Returns false if the suffix is not a - * recognized offset (caller then leaves the value unadjusted, preserving - * the prior behaviour of ignoring unrecognized trailing characters). */ -RAY_INLINE bool parse_tz_offset(const char* p, size_t len, int64_t* out_ns) { + * UTC), reports the number of bytes consumed in *consumed, and returns + * true. Returns false if the suffix is not a recognized offset; the + * caller treats that (and any unconsumed trailing bytes) as malformed. */ +RAY_INLINE bool parse_tz_offset(const char* p, size_t len, int64_t* out_ns, size_t* consumed) { if (len == 0) return false; - if (p[0] == 'Z' || p[0] == 'z') { *out_ns = 0; return true; } + if (p[0] == 'Z' || p[0] == 'z') { *out_ns = 0; if (consumed) *consumed = 1; return true; } int sign; if (p[0] == '+') sign = 1; else if (p[0] == '-') sign = -1; @@ -600,16 +649,23 @@ RAY_INLINE bool parse_tz_offset(const char* p, size_t len, int64_t* out_ns) { int hh = (p[1]-'0')*10 + (p[2]-'0'); int mm = 0; size_t i = 3; - if (len > i && p[i] == ':') i++; /* optional ':' separator */ - if (len >= i + 2 && p[i] >= '0' && p[i] <= '9' && p[i+1] >= '0' && p[i+1] <= '9') - mm = (p[i]-'0')*10 + (p[i+1]-'0'); + size_t msep = (len > 3 && p[3] == ':') ? 1 : 0; /* optional ':' separator */ + if (len >= 3 + msep + 2 && + p[3+msep] >= '0' && p[3+msep] <= '9' && p[4+msep] >= '0' && p[4+msep] <= '9') { + mm = (p[3+msep]-'0')*10 + (p[4+msep]-'0'); + i = 3 + msep + 2; /* consume ':' only with MM */ + } if (RAY_UNLIKELY(hh > 23 || mm > 59)) return false; *out_ns = (int64_t)sign * ((int64_t)hh * 3600 + (int64_t)mm * 60) * 1000000000LL; + if (consumed) *consumed = i; return true; } RAY_INLINE int64_t fast_timestamp(const char* p, size_t len, bool* is_null) { - if (RAY_UNLIKELY(len < 19)) { *is_null = true; return 0; } + /* Require "YYYY-MM-DD" + 'T'|'t'|' ' separator + "HH:MM:SS" (>=19 chars), + * matching detect_type() and csv_write_timestamp(). A malformed date/time + * separator (e.g. "2024x01x02D01:02:03") is rejected as null. */ + if (RAY_UNLIKELY(len < 19 || (p[10] != 'T' && p[10] != 't' && p[10] != ' '))) { *is_null = true; return 0; } *is_null = false; int32_t days = fast_date(p, 10, is_null); if (*is_null) return 0; @@ -620,12 +676,19 @@ RAY_INLINE int64_t fast_timestamp(const char* p, size_t len, bool* is_null) { const int64_t NS_PER_DAY = 86400000000000LL; int64_t result = (int64_t)days * NS_PER_DAY + time_ns; /* Optional trailing UTC offset (Z | ±HH:MM | ±HHMM | ±HH). The common - * no-offset case ends exactly at the time component (off == len), so - * the hot path pays only this single predicted-not-taken bounds check. */ + * no-offset case ends exactly at the time component (off == len), so the + * hot path pays only this single predicted-not-taken bounds check. Any + * other trailing bytes — or an offset that does not consume to the end + * (e.g. "2024-01-02T01:02:03junk") — are malformed and reject the cell. */ size_t off = 11 + time_used; if (RAY_UNLIKELY(off < len)) { int64_t adj; - if (parse_tz_offset(p + off, len - off, &adj)) result -= adj; + size_t tz_used = 0; + if (RAY_UNLIKELY(!parse_tz_offset(p + off, len - off, &adj, &tz_used) || + off + tz_used != len)) { + *is_null = true; return 0; + } + result -= adj; } return result; } @@ -688,9 +751,329 @@ RAY_INLINE void fast_guid(const char* p, size_t len, uint8_t* dst, bool* is_null * Allocates offsets via scratch_alloc. Caller frees with scratch_free. * -------------------------------------------------------------------------- */ -static int64_t build_row_offsets(const char* buf, size_t buf_size, - size_t data_offset, - int64_t** offsets_out, ray_t** hdr_out) { +/* -------------------------------------------------------------------------- + * Parallel row-offset scan. + * + * The serial scan below is a pure state machine over the byte stream, and its + * only cross-position state is the QUOTE PARITY (an odd number of '"' seen so + * far means "inside a quoted field", where newlines are data). Parity is an + * XOR-scan, so it can be reconciled: count the quotes in every chunk first, + * prefix-XOR the counts, and each chunk then starts its scan with exactly the + * parity the serial scanner would have had there. Escaped quotes need no + * special case — a doubled "" flips parity twice, which is what the serial + * loop does too. + * + * The one place a decision spans a chunk boundary is a "\r\n" pair split down + * the middle: the left chunk consumes both bytes and records the row start + * after them, so the right chunk must not treat the orphan '\n' as a fresh + * terminator. Boundaries are nudged one byte right in that case + * (csv_scan_split_at) so the pair always lands whole in the left chunk. The + * quote-free fast path has the mirror case ("\n\r"), handled the same way. + * + * Sizing: the counting pass also counts line-terminator bytes, which is an + * exact upper bound on the rows a chunk can emit. Each chunk therefore writes + * straight into a reserved slice of one array (no per-worker allocation, no + * locks) and a final compaction closes the gaps. + * -------------------------------------------------------------------------- */ + +/* Chunking is normally sized for throughput: a few chunks per worker, each at + * least CSV_SCAN_CHUNK_MIN bytes, and the parallel path is skipped entirely + * below CSV_SCAN_PAR_MIN_BYTES. That puts ~31 boundaries in a 6 MB file, + * which exercises almost none of the stitching this scan is built out of — + * the interesting states (a boundary inside a quoted field, between the two + * bytes of a "\r\n", in the middle of a "" run) only show up when boundaries + * are dense. A test build therefore shrinks all three so that even a small + * fixture is cut into RAY_POOL_INIT_TASKS chunks a few dozen bytes wide, and + * every CSV the suite reads becomes a boundary-stitching test. + * + * DENSER IS NOT STRICTLY BETTER, so do not "improve" the 64-byte floor + * downward. Sensitivity to the two bug classes runs in OPPOSITE directions: + * - boundary/stitching bugs (parity prefix, csv_scan_split_at) are most + * visible with tiny spans, since every byte becomes a boundary; + * - intra-chunk state-machine bugs are most visible with LARGER spans, + * because a chunk has to walk real distance under its own in_quote state + * to expose them. At span 1 the parity prefix does essentially all the + * work and the state machine is barely exercised — a review mutant that + * corrupted in_quote handling was INVISIBLE at span 1 and caught only at + * span >= 17. + * 64 bytes sits in the range that is sensitive to both. + * + * The chunk count is a constant, not a function of the core count, so a + * failure reproduces the same way on any machine. Gated exactly like + * group.c's GHT_LANES_WHOLE assertions — this is a test affordance, and + * deliberately NOT a runtime knob. */ +#if defined(DEBUG) || defined(RAY_HARDENED) +#define CSV_SCAN_PAR_MIN_BYTES (8u << 10) +#define CSV_SCAN_CHUNK_MIN 64u +#define CSV_SCAN_CHUNKS(pool) ((int64_t)RAY_POOL_INIT_TASKS) +#else +/* Minimum bytes before the parallel scan is worth its two passes. */ +#define CSV_SCAN_PAR_MIN_BYTES (4u << 20) +/* Minimum bytes per chunk — below this the per-task overhead dominates. */ +#define CSV_SCAN_CHUNK_MIN (256u << 10) +#define CSV_SCAN_CHUNKS(pool) ((int64_t)ray_pool_total_workers(pool) * 4) +#endif + +typedef struct { + const char* buf; + size_t file_size; + const size_t* bound; /* [n_chunks+1] chunk start byte offsets */ + uint64_t* quote_cnt; /* [n_chunks] '"' per chunk (pass 1 out) */ + uint64_t* term_cnt; /* [n_chunks] '\n'+'\r' per chunk (pass 1) */ + const uint8_t* start_quoted; /* [n_chunks] parity at chunk start */ + const int64_t* slot; /* [n_chunks] write base into offs */ + int64_t* n_out; /* [n_chunks] rows written (pass 2 out) */ + int64_t* offs; /* row-offset array being filled */ + bool has_quotes; /* pick the fast/slow state machine */ +} csv_scan_ctx_t; + +static void csv_scan_count_fn(void* arg, uint32_t worker_id, + int64_t start, int64_t end_i) { + (void)worker_id; + csv_scan_ctx_t* ctx = (csv_scan_ctx_t*)arg; + for (int64_t i = start; i < end_i; i++) { + const char* p = ctx->buf + ctx->bound[i]; + const char* e = ctx->buf + ctx->bound[i + 1]; + uint64_t q = 0, t = 0; + while (p < e) { + const char* stop = p + (1 << 20); + if (stop > e) stop = e; + for (; p < stop; p++) { + char c = *p; + q += (c == '"'); + t += (c == '\n' || c == '\r'); + } + if (RAY_UNLIKELY(ray_interrupted())) break; + } + ctx->quote_cnt[i] = q; + ctx->term_cnt[i] = t; + } +} + +static void csv_scan_rows_fn(void* arg, uint32_t worker_id, + int64_t start, int64_t end_i) { + (void)worker_id; + csv_scan_ctx_t* ctx = (csv_scan_ctx_t*)arg; + const char* buf = ctx->buf; + const char* end = buf + ctx->file_size; + + for (int64_t i = start; i < end_i; i++) { + const char* p = buf + ctx->bound[i]; + const char* cend = buf + ctx->bound[i + 1]; + int64_t* out = ctx->offs + ctx->slot[i]; + int64_t n = 0; + + if (RAY_LIKELY(!ctx->has_quotes)) { + /* Mirrors the serial fast path exactly: only '\n' terminates a + * row, and an optional '\r' immediately after it is absorbed. */ + size_t checked = 0; + while (p < cend) { + if (RAY_UNLIKELY((++checked & 0xFFFF) == 0 && ray_interrupted())) break; + const char* nl = (const char*)memchr(p, '\n', (size_t)(cend - p)); + if (!nl) break; + p = nl + 1; + if (p < end && *p == '\r') p++; + if (p >= end) break; + out[n++] = (int64_t)(p - buf); + } + } else { + /* Mirrors the serial slow path exactly: quote parity gates the + * terminators, '\r' alone ends a row, "\r\n" ends exactly one. + * + * One shortcut, provably equivalent: INSIDE a quoted field the + * serial loop's only reachable action is "p++" until it meets the + * closing '"' (the newline arm is gated on !in_quote), so memchr + * can jump straight to that quote. Worth doing because a quoted + * field is where the byte-at-a-time loop spends its time — long + * URL/title columns are exactly the quoted ones. */ + bool in_quote = ctx->start_quoted[i] != 0; + size_t checked = 0; + while (p < cend) { + if (in_quote) { + if (RAY_UNLIKELY((++checked & 0xFFF) == 0 && ray_interrupted())) break; + /* Bounding the search at cend is defensive, not required: + * the `p < cend` guard above already stops the loop after + * an overshoot, so searching to the file end would find + * the same offsets (it would just do the next chunk's + * work). Bounded because a chunk has no business reading + * past its own slice. */ + const char* q = (const char*)memchr(p, '"', (size_t)(cend - p)); + if (!q) { p = cend; break; } + p = q + 1; + in_quote = false; + continue; + } + /* Outside a quoted field (in_quote is false for the rest of + * this iteration by construction). */ + if (RAY_UNLIKELY((++checked & 0xFFFF) == 0 && ray_interrupted())) break; + char c = *p; + if (c == '"') { + in_quote = true; + p++; + } else if (c == '\n' || c == '\r') { + if (c == '\r' && p + 1 < end && *(p + 1) == '\n') p++; + p++; + if (p < end) out[n++] = (int64_t)(p - buf); + } else { + p++; + } + } + } + ctx->n_out[i] = n; + } +} + +/* Nudge a chunk boundary right so a two-byte line terminator is never split. + * Quoted or not, the left chunk's state machine consumes both bytes of the + * pair, so the byte after it must belong to the left chunk as well. */ +static size_t csv_scan_split_at(const char* buf, size_t file_size, size_t s, + bool has_quotes) { + if (s == 0 || s >= file_size) return s; + char prev = buf[s - 1], cur = buf[s]; + if (has_quotes) { if (prev == '\r' && cur == '\n') s++; } + else { if (prev == '\n' && cur == '\r') s++; } + return s; +} + +/* Returns the row count (>=0), -1 if interrupted, or -2 when the parallel + * path does not apply and the caller should run the serial scan. */ +static int64_t build_row_offsets_par(const char* buf, size_t buf_size, + size_t data_offset, + uint64_t prog_base, uint64_t prog_len, + int64_t** offsets_out, ray_t** hdr_out) { + *offsets_out = NULL; + *hdr_out = NULL; + + size_t remaining = buf_size - data_offset; + ray_pool_t* pool = ray_pool_get(); + if (!ray_pool_par_dispatch_ok(pool, (int64_t)remaining, + (int64_t)CSV_SCAN_PAR_MIN_BYTES)) + return -2; + + int64_t n_chunks = CSV_SCAN_CHUNKS(pool); + /* Never exceed the task ring's initial capacity: growth failure inside + * ray_pool_dispatch_n silently DROPS tasks, which here would silently + * drop rows. The span floor below can only lower n_chunks (it triggers + * exactly when remaining < n_chunks * CHUNK_MIN), so the cap holds. */ + if (n_chunks > (int64_t)RAY_POOL_INIT_TASKS) n_chunks = RAY_POOL_INIT_TASKS; + size_t span = remaining / (size_t)n_chunks; + if (span < CSV_SCAN_CHUNK_MIN) { + span = CSV_SCAN_CHUNK_MIN; + n_chunks = (int64_t)((remaining + span - 1) / span); + } + if (n_chunks < 2) return -2; + + /* One block for every per-chunk array: bounds, counts, parity, slots. */ + size_t hdr_bytes = (size_t)(n_chunks + 1) * sizeof(size_t) + + (size_t)n_chunks * (2 * sizeof(uint64_t) + + 2 * sizeof(int64_t) + + sizeof(uint8_t)); + void* blk = ray_sys_alloc(hdr_bytes); + if (!blk) return -2; + size_t* bound = (size_t*)blk; + uint64_t* quote_cnt = (uint64_t*)(bound + n_chunks + 1); + uint64_t* term_cnt = quote_cnt + n_chunks; + int64_t* slot = (int64_t*)(term_cnt + n_chunks); + int64_t* n_out = slot + n_chunks; + uint8_t* start_q = (uint8_t*)(n_out + n_chunks); + + csv_scan_ctx_t ctx = { + .buf = buf, .file_size = buf_size, .bound = bound, + .quote_cnt = quote_cnt, .term_cnt = term_cnt, + .start_quoted = start_q, .slot = slot, .n_out = n_out, + .offs = NULL, .has_quotes = false, + }; + + /* Pass-1 boundaries are the raw even split: counting is boundary-shape + * agnostic, and the quote-aware nudge below needs has_quotes, which only + * pass 1 can establish. */ + bound[0] = data_offset; + for (int64_t i = 1; i < n_chunks; i++) { + size_t s = data_offset + (size_t)i * span; + if (s > buf_size) s = buf_size; + if (s < bound[i - 1]) s = bound[i - 1]; + bound[i] = s; + } + bound[n_chunks] = buf_size; + + /* Pass 1 is the bandwidth-bound count; pass 2 is the byte-at-a-time state + * machine. Measured 0.90 s / 3.42 s of the scan on the 8 GB file. */ + ray_progress_span_phase("scan: quotes", prog_base, prog_len / 5); + ray_pool_dispatch_n(pool, csv_scan_count_fn, &ctx, (uint32_t)n_chunks); + if (ray_interrupted()) { ray_sys_free(blk); return -1; } + + uint64_t total_q = 0, total_term = 0; + for (int64_t i = 0; i < n_chunks; i++) { + start_q[i] = (uint8_t)(total_q & 1u); + total_q += quote_cnt[i]; + total_term += term_cnt[i]; + } + ctx.has_quotes = total_q != 0; + + /* Now nudge the boundaries for the state machine pass 1 just chose. The + * byte skipped is always '\n' or '\r', never '"', so the parities + * computed above stay exact. */ + for (int64_t i = 1; i < n_chunks; i++) { + size_t s = csv_scan_split_at(buf, buf_size, bound[i], ctx.has_quotes); + if (s < bound[i - 1]) s = bound[i - 1]; + bound[i] = s; + } + + /* Slice sizing: a chunk emits at most one row start per line-terminator + * byte it walks over. The nudge can hand a chunk one terminator from its + * right neighbour, and the last row of a chunk can be recorded from a + * terminator one byte past cend, so reserve term_cnt + 2. Slot 0 is + * reserved for the first row — the data section always starts one. */ + uint64_t slack = 2u * (uint64_t)n_chunks + 1u; + if (total_term > (uint64_t)INT64_MAX / (uint64_t)sizeof(int64_t) - slack) { + ray_sys_free(blk); + return -2; + } + int64_t cap = (int64_t)(total_term + slack); + { + int64_t base = 1; + for (int64_t i = 0; i < n_chunks; i++) { + slot[i] = base; + base += (int64_t)term_cnt[i] + 2; + } + } + + ray_t* hdr = NULL; + int64_t* offs = (int64_t*)scratch_alloc(&hdr, (size_t)cap * sizeof(int64_t)); + if (!offs) { ray_sys_free(blk); return -2; } + offs[0] = (int64_t)data_offset; + ctx.offs = offs; + + ray_progress_span_phase("scan: rows", prog_base + prog_len / 5, + prog_len - prog_len / 5); + ray_pool_dispatch_n(pool, csv_scan_rows_fn, &ctx, (uint32_t)n_chunks); + if (ray_interrupted()) { + scratch_free(hdr); + ray_sys_free(blk); + return -1; + } + + /* Compact the per-chunk slices into one dense, ascending array. */ + int64_t n = 1; + for (int64_t i = 0; i < n_chunks; i++) { + int64_t cnt = n_out[i]; + if (cnt <= 0) continue; + if (n != slot[i]) + memmove(offs + n, offs + slot[i], (size_t)cnt * sizeof(int64_t)); + n += cnt; + } + + ray_sys_free(blk); + *offsets_out = offs; + *hdr_out = hdr; + return n; +} + +/* Serial scan — the reference semantics the parallel scan above mirrors. */ +static int64_t build_row_offsets_serial(const char* buf, size_t buf_size, + size_t data_offset, + uint64_t prog_base, uint64_t prog_len, + int64_t** offsets_out, ray_t** hdr_out) { const char* p = buf + data_offset; const char* end = buf + buf_size; @@ -720,11 +1103,16 @@ 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; + if (RAY_UNLIKELY((n & 0xFFFF) == 0)) { + if (ray_interrupted()) { + scratch_free(hdr); + *offsets_out = NULL; + *hdr_out = NULL; + return -1; + } + ray_progress_span_set(prog_base + + (uint64_t)((double)prog_len * (double)(size_t)(p - buf - (ptrdiff_t)data_offset) + / (double)remaining)); } const char* nl = (const char*)memchr(p, '\n', (size_t)(end - p)); if (!nl) break; @@ -756,6 +1144,9 @@ static int64_t build_row_offsets(const char* buf, size_t buf_size, *hdr_out = NULL; return -1; } + ray_progress_span_set(prog_base + + (uint64_t)((double)prog_len * (double)(size_t)(p - buf - (ptrdiff_t)data_offset) + / (double)remaining)); } char c = *p; if (c == '"') { @@ -785,6 +1176,26 @@ static int64_t build_row_offsets(const char* buf, size_t buf_size, return n; } +static int64_t build_row_offsets(const char* buf, size_t buf_size, + size_t data_offset, + uint64_t prog_base, uint64_t prog_len, + int64_t** offsets_out, ray_t** hdr_out) { + if (data_offset >= buf_size) { *offsets_out = NULL; *hdr_out = NULL; return 0; } + + /* Large files: chunked parallel scan with quote-parity reconciliation. + * -2 means "not applicable" (small file, no pool, allocation refused) and + * falls back to the serial scan, which defines the semantics. */ + int64_t par = build_row_offsets_par(buf, buf_size, data_offset, + prog_base, prog_len, + offsets_out, hdr_out); + if (par != -2) return par; + + ray_progress_span_phase("scan", prog_base, prog_len); + return build_row_offsets_serial(buf, buf_size, data_offset, + prog_base, prog_len, + offsets_out, hdr_out); +} + static int64_t build_row_offsets_limited(const char* buf, size_t buf_size, size_t data_offset, int64_t max_rows, bool data_has_quotes, @@ -885,62 +1296,307 @@ static int64_t build_row_offsets_limited(const char* buf, size_t buf_size, } /* -------------------------------------------------------------------------- - * Batch-intern string columns after parse. - * Single-threaded — walks each string column, interns into global sym table, - * writes sym IDs into the final uint32_t column. + * Per-column local dedupe — the parallel front half of the sym intern. + * + * The serial intern below walks every SYM column row by row and calls + * ray_sym_intern_no_split_unlocked once per row. That is n_rows probes into + * the process-global dictionary per column and it cannot be threaded: the + * "unlocked" contract assumes no concurrent writers, and a symbol's id IS its + * first-encounter order, so racing threads would hand out different ids. + * + * It splits, though, because interning is idempotent: only the FIRST + * occurrence of a string allocates an id, every later one is a lookup. So: + * + * A) in parallel, one task per column, dedupe locally — build a dictionary + * of the column's distinct strings IN FIRST-OCCURRENCE ORDER and write a + * dense local code per row (code 0 reserved for empty/missing); + * B) serially, columns in ascending index order, intern each dictionary's + * entries in insertion order and record the global id each one got; + * C) in parallel, one task per column, map local codes to global ids. + * + * ID-ORDER PRESERVATION (why ids come out bit-identical to the serial walk): + * the sequence of intern calls that ALLOCATE an id is what fixes the id + * assignment, and step B reproduces that sequence exactly. The serial walk + * allocates in the order (column ascending, then row ascending, first + * occurrence only); step A records precisely the first occurrences of one + * column in row order, step B replays columns in ascending order, so the + * concatenation is the same sequence of first occurrences in the same order. + * Every other call in the serial walk is a repeat that returns an existing id + * and allocates nothing, so dropping them changes no assignment. The + * empty-symbol intern stays the first call of step B, as it was the first call + * of the serial walk. This is verified empirically, not just argued: see + * .superpowers/csv-load-report.md for the per-column raw-id comparison + * against the pre-change build. + * + * A column whose distinct set exceeds CSV_DEDUP_MAX_ENTS gives up its local + * dictionary (the dedupe stops paying for itself once the local table is as + * cache-hostile as the global one) and is interned the old row-by-row way in + * step B — at its own position in column order, so the id sequence is still + * the same one. * -------------------------------------------------------------------------- */ -static bool csv_intern_strings(csv_strref_t** str_refs, int n_cols, - const csv_type_t* col_types, - const int8_t* resolved_types, - void** col_data, int64_t n_rows, - int64_t* col_max_ids) { +/* Distinct-strings ceiling per column. Past this the local table no longer + * fits a private cache, so it buys nothing over probing the global dictionary + * — the fallback in csv_intern_dicts costs speed, never correctness. + * + * It bounds the PER-COLUMN scratch only, and that is the honest limit: a + * dictionary at the ceiling is 1M entries (24 B each) plus a 2M-slot u32 + * array, ~32 MB, and every SYM column's dictionary is live simultaneously + * from dispatch 1 until step C releases them. So the aggregate bound is + * ~32 MB x live SYM columns — ~700 MB for the 22 SYM columns of the + * ClickBench hits file if each were at the ceiling (they are nowhere near + * it), and ~8 GB in the worst case allowed by CSV_MAX_COLS=256. Transient, + * and it takes a file with hundreds of million-distinct SYM columns to get + * there, but it is not bounded by a constant. + * + * A test build lowers it far enough that a few-thousand-distinct fixture + * crosses it, so the overflow fallback in csv_intern_dicts is exercised by + * the suite instead of only by 1M-distinct columns nobody puts in a test. + * Same gate and same reasoning as CSV_SCAN_CHUNKS above: compile-time, never + * a runtime knob. */ +#if defined(DEBUG) || defined(RAY_HARDENED) +#define CSV_DEDUP_MAX_ENTS 8192u +#else +#define CSV_DEDUP_MAX_ENTS (1u << 20) +#endif +#define CSV_DEDUP_MIN_SLOTS 64u + +typedef struct { + uint32_t hash; + uint32_t len; + const char* ptr; + int64_t gid; /* global sym id, filled in step B */ +} csv_dedup_ent_t; + +typedef struct { + uint32_t* slots; /* [n_slots] 0 = empty, else entry index + 1 */ + uint32_t n_slots; /* power of two */ + csv_dedup_ent_t* ents; /* [n_ents] distinct strings, insertion order */ + uint32_t n_ents; + uint32_t ents_cap; + bool done; /* task ran to completion */ + bool overflow; /* too many distinct — intern this column serially */ +} csv_dedup_t; + +static void csv_dedup_release(csv_dedup_t* d) { + if (d->slots) { ray_sys_free(d->slots); d->slots = NULL; } + if (d->ents) { ray_sys_free(d->ents); d->ents = NULL; } + d->n_slots = 0; d->n_ents = 0; d->ents_cap = 0; +} + +/* Grow slots to 2x and reinsert. Entry order is untouched — rehashing moves + * slot positions, never the insertion-ordered ents array the ids come from. */ +static bool csv_dedup_grow(csv_dedup_t* d) { + uint32_t new_slots = d->n_slots ? d->n_slots * 2 : CSV_DEDUP_MIN_SLOTS; + uint32_t* s = (uint32_t*)ray_sys_alloc((size_t)new_slots * sizeof(uint32_t)); + if (!s) return false; + memset(s, 0, (size_t)new_slots * sizeof(uint32_t)); + uint32_t mask = new_slots - 1; + for (uint32_t i = 0; i < d->n_ents; i++) { + uint32_t j = d->ents[i].hash & mask; + while (s[j]) j = (j + 1) & mask; + s[j] = i + 1; + } + if (d->slots) ray_sys_free(d->slots); + d->slots = s; + d->n_slots = new_slots; + return true; +} + +static bool csv_dedup_grow_ents(csv_dedup_t* d) { + uint32_t cap = d->ents_cap ? d->ents_cap * 2 : CSV_DEDUP_MIN_SLOTS; + csv_dedup_ent_t* e = (csv_dedup_ent_t*)ray_sys_realloc( + d->ents, (size_t)cap * sizeof(csv_dedup_ent_t)); + if (!e) return false; + d->ents = e; + d->ents_cap = cap; + return true; +} + +typedef struct { + csv_strref_t** str_refs; + void** col_data; + const int* cols; /* [n] SYM column indices, ascending */ + csv_dedup_t* dicts; /* [n] */ + int64_t n_rows; + int64_t empty_gid; /* global id of "" — step B fills it in */ + /* [n_cols] "this column wrote a canonical null", recorded where the value + * is written. See csv_note_empty. */ + bool* empties; +} csv_dedup_ctx_t; + +/* HAS_NULLS accounting for SYM/STR columns (step 9c). + * + * bfb5b380 made an empty SYM/STR cell a canonical null and, where the parse + * had not already flagged the column, fell back to a per-row ray_vec_is_null + * scan to find out. Every writer of those cells already has the value in a + * register, so the same predicate is evaluated there instead — SYM null is + * id == 0, STR null is len == 0, exactly what ray_vec_is_null tests. Same + * semantics, same flag, no extra pass: the fallback scan cost 0.207 s on the + * 8 GB file walking 5 columns to find nothing (it cannot find anything the + * parse missed, but this way that is a property of the code rather than of + * an argument about the parser). */ +static inline void csv_note_empty(bool* empties, int col, bool is_null) { + if (is_null && empties) empties[col] = true; +} + +static void csv_dedup_task(void* arg, uint32_t worker_id, + int64_t start, int64_t end_i) { + (void)worker_id; (void)end_i; + csv_dedup_ctx_t* ctx = (csv_dedup_ctx_t*)arg; + csv_dedup_t* d = &ctx->dicts[start]; + const csv_strref_t* refs = ctx->str_refs[ctx->cols[start]]; + /* Local codes land in the destination id array and are replaced in place + * by step C, so the dedupe needs no per-row scratch of its own. */ + uint32_t* codes = (uint32_t*)ctx->col_data[ctx->cols[start]]; + int64_t n_rows = ctx->n_rows; + + if (!csv_dedup_grow(d) || !csv_dedup_grow_ents(d)) { + d->overflow = true; + d->done = true; + csv_dedup_release(d); + return; + } + + for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) return; + if (refs[r].ptr == NULL) { codes[r] = 0; continue; } + uint32_t h = (uint32_t)ray_hash_bytes(refs[r].ptr, refs[r].len); + uint32_t mask = d->n_slots - 1; + uint32_t j = h & mask; + uint32_t found = 0; + for (;;) { + uint32_t slot = d->slots[j]; + if (!slot) break; + const csv_dedup_ent_t* e = &d->ents[slot - 1]; + if (e->hash == h && e->len == refs[r].len && + memcmp(e->ptr, refs[r].ptr, refs[r].len) == 0) { + found = slot; + break; + } + j = (j + 1) & mask; + } + if (found) { codes[r] = found; continue; } + + if (d->n_ents >= CSV_DEDUP_MAX_ENTS) { + d->overflow = true; + d->done = true; + csv_dedup_release(d); + return; + } + if (d->n_ents == d->ents_cap && !csv_dedup_grow_ents(d)) { + d->overflow = true; d->done = true; csv_dedup_release(d); return; + } + csv_dedup_ent_t* e = &d->ents[d->n_ents]; + e->hash = h; + e->len = refs[r].len; + e->ptr = refs[r].ptr; + e->gid = 0; + d->n_ents++; + codes[r] = d->n_ents; /* code = entry index + 1 */ + d->slots[j] = d->n_ents; + /* Keep the load factor under 3/4. */ + if (d->n_ents * 4u >= d->n_slots * 3u && !csv_dedup_grow(d)) { + d->overflow = true; d->done = true; csv_dedup_release(d); return; + } + } + d->done = true; +} + +/* Step C: local code -> global sym id, in place. */ +static void csv_dedup_map_task(void* arg, uint32_t worker_id, + int64_t start, int64_t end_i) { + (void)worker_id; (void)end_i; + csv_dedup_ctx_t* ctx = (csv_dedup_ctx_t*)arg; + const csv_dedup_t* d = &ctx->dicts[start]; + if (d->overflow) return; /* step B already wrote real ids */ + uint32_t* ids = (uint32_t*)ctx->col_data[ctx->cols[start]]; + int64_t n_rows = ctx->n_rows; + uint32_t empty = (uint32_t)ctx->empty_gid; + bool saw_null = false; + for (int64_t r = 0; r < n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) return; + uint32_t code = ids[r]; + uint32_t id = code ? (uint32_t)d->ents[code - 1].gid : empty; + ids[r] = id; + saw_null |= (id == 0); + } + csv_note_empty(ctx->empties, ctx->cols[start], saw_null); +} + +/* Step B — the only serial part left: intern each column's distinct strings, + * columns in ascending order, entries in first-occurrence order. See the + * ID-ORDER PRESERVATION note above for why this reproduces the serial walk's + * id assignment exactly. + * + * CSV/TSV import policy for SYM columns, unchanged: an empty field writes the + * canonical empty-symbol id (always 0, reserved by ray_sym_init). SYM columns + * carry no null bitmap by design — sym 0 is "missing", "empty" and "absent" + * all at once. The CSV format cannot distinguish a missing field from an + * empty string anyway, so collapsing them is the only deterministic answer the + * parser can give. Empty fields are local code 0 out of the dedupe and are + * mapped to that id by step C. */ +static bool csv_intern_dicts(csv_dedup_ctx_t* dd, int n_sym, + int64_t* col_max_ids, + uint64_t prog_base, uint64_t prog_len) { bool ok = true; - /* CSV/TSV import policy for SYM columns: empty fields write the - * canonical empty-symbol ID (always 0, reserved by ray_sym_init). - * SYM columns carry no null bitmap by design — sym 0 is the - * representation of "missing", "empty", and "absent" all at once. - * The CSV format can't distinguish "missing field" from "empty - * string" anyway, so collapsing them is the only deterministic - * answer the parser can give. - * - * Sym 0 is guaranteed to exist by ray_sym_init; the intern call - * here is a fast-path lookup that returns it without growing the - * dictionary. */ + /* Same first call, same reason, as the serial walk: sym 0 is reserved by + * ray_sym_init, so this is a lookup that allocates nothing — but it must + * stay FIRST for the id sequence to match on a table where it somehow + * would allocate. */ int64_t empty_sym_id = ray_sym_intern_prehashed( (uint32_t)ray_hash_bytes("", 0), "", 0); - if (empty_sym_id < 0) empty_sym_id = 0; /* shouldn't happen — sym 0 is reserved */ + if (empty_sym_id < 0) empty_sym_id = 0; + dd->empty_gid = empty_sym_id; - for (int c = 0; c < n_cols; c++) { - if (col_types[c] != CSV_TYPE_STR) continue; - /* RAY_STR columns are materialized directly; skip sym interning. */ - if (resolved_types[c] == RAY_STR) continue; - csv_strref_t* refs = str_refs[c]; - if (!refs) continue; - uint32_t* ids = (uint32_t*)col_data[c]; + for (int i = 0; i < n_sym; i++) { + int c = dd->cols[i]; + csv_dedup_t* d = &dd->dicts[i]; int64_t max_id = empty_sym_id; - /* Pre-grow: upper bound is n_rows unique strings */ + /* Pre-grow: upper bound is n_rows unique strings (unchanged). */ uint32_t current = ray_sym_count(); - if (!ray_sym_ensure_cap(current + (uint32_t)(n_rows < UINT32_MAX ? n_rows : UINT32_MAX))) - return false; /* OOM: cannot grow sym table */ + if (!ray_sym_ensure_cap(current + + (uint32_t)(dd->n_rows < UINT32_MAX ? dd->n_rows : UINT32_MAX))) + return false; - 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. */ - ids[r] = (uint32_t)empty_sym_id; - continue; + if (d->done && !d->overflow) { + for (uint32_t e = 0; e < d->n_ents; e++) { + if (RAY_UNLIKELY((e & 1023) == 0 && ray_interrupted())) return false; + int64_t id = ray_sym_intern_no_split_unlocked(d->ents[e].ptr, + d->ents[e].len); + if (id < 0) { ok = false; id = 0; } + d->ents[e].gid = id; + if (id > max_id) max_id = id; + } + } else { + /* No usable dictionary (distinct set over the ceiling, or the task + * never ran). Intern row by row exactly where the serial walk + * would have, so the id sequence is still the same one. */ + const csv_strref_t* refs = dd->str_refs[c]; + uint32_t* ids = (uint32_t*)dd->col_data[c]; + bool saw_null = false; + for (int64_t r = 0; r < dd->n_rows; r++) { + if (RAY_UNLIKELY((r & 1023) == 0 && ray_interrupted())) return false; + if (refs[r].ptr == NULL) { + /* Empty/missing field → canonical sym-0 null. */ + ids[r] = (uint32_t)empty_sym_id; + saw_null |= (empty_sym_id == 0); + continue; + } + int64_t id = ray_sym_intern_no_split_unlocked(refs[r].ptr, refs[r].len); + if (id < 0) { ok = false; id = 0; } + ids[r] = (uint32_t)id; + saw_null |= (id == 0); + if (id > max_id) max_id = id; } - int64_t id = ray_sym_intern_no_split_unlocked(refs[r].ptr, refs[r].len); - if (id < 0) { ok = false; id = 0; } - ids[r] = (uint32_t)id; - if (id > max_id) max_id = id; + csv_note_empty(dd->empties, c, saw_null); } if (col_max_ids) col_max_ids[c] = max_id; + if (prog_len) + ray_progress_span_set(prog_base + (uint64_t)((double)prog_len * + (double)(i + 1) / (double)n_sym)); } return ok; } @@ -967,16 +1623,14 @@ static void csv_free_escaped_strrefs(csv_strref_t** str_refs, int n_cols, } } -/* Materialize RAY_STR columns from parsed strrefs. Two-pass so the per-column - * string pool is sized exactly once — avoids the repeated realloc/COW path - * that ray_str_vec_set would take for a freshly-owned vector. */ -static bool csv_fill_str_cols(csv_strref_t** str_refs, int n_cols, - const int8_t* resolved_types, - ray_t** col_vecs, int64_t n_rows) { - for (int c = 0; c < n_cols; c++) { - if (resolved_types[c] != RAY_STR) continue; - csv_strref_t* refs = str_refs[c]; - ray_t* vec = col_vecs[c]; +/* Materialize ONE RAY_STR column from its parsed strrefs. Two-pass so the + * per-column string pool is sized exactly once — avoids the repeated + * realloc/COW path that ray_str_vec_set would take for a freshly-owned + * vector. Columns are independent (own vector, own pool), which is what + * lets the finalizer run one task per column. */ +static bool csv_fill_str_col(csv_strref_t* refs, ray_t* vec, int64_t n_rows, + bool* saw_null_out) { + { ray_str_t* dst = (ray_str_t*)ray_data(vec); /* ray_str_t.pool_off is u32 — the per-column pool is capped at 4 GiB. @@ -1002,11 +1656,14 @@ static bool csv_fill_str_cols(csv_strref_t** str_refs, int n_cols, char* pool_base = vec->str_pool ? (char*)ray_data(vec->str_pool) : NULL; uint32_t pool_off = 0; + bool saw_null = false; 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)); + /* len 0 is what ray_vec_is_null tests for a STR cell. */ + if (refs[r].ptr == NULL || refs[r].len == 0) { saw_null = true; } if (refs[r].ptr == NULL) continue; const char* p = refs[r].ptr; uint32_t l = refs[r].len; @@ -1022,16 +1679,33 @@ static bool csv_fill_str_cols(csv_strref_t** str_refs, int n_cols, } } if (vec->str_pool) vec->str_pool->len = (int64_t)pool_off; + if (saw_null_out) *saw_null_out = saw_null; } return true; } /* -------------------------------------------------------------------------- - * Stage 9b helper: dispatch csv_fill_str_cols and csv_intern_strings on - * separate threads when a pool is available. They write to disjoint - * column data, and intern_strings is the only one that touches the - * global sym table (so it stays single-threaded; we just run it in - * parallel with fill_str_cols). + * Stage 9b: finalize the text columns. + * + * Three steps, laid out so only the middle one is serial: + * + * dispatch 1 one task per RAY_STR column (materialize its vector + string + * pool) AND one task per SYM column (local dedupe, above). + * Everything here is column-private. + * serial intern each SYM column's distinct strings into the global + * symbol table, columns in ascending order (csv_intern_dicts). + * Bounded by DISTINCT strings, not rows. + * dispatch 2 one task per SYM column, mapping local codes to global ids. + * + * This started as exactly two tasks -- "all the fills" and "the whole intern" + * -- which on a 105-column file left 8 cores running 2 threads for ~5 s, and + * then as per-column fills plus one monolithic intern, where the intern was + * the critical path at 3.9 s. Only the distinct-string interning is + * genuinely serial, and that is all that is left of it. + * + * Fills are dispatched before dedupes because they are the longer tasks + * (whole-column copies vs. one hash probe per row), and longest-first is what + * balances a fixed task list. * -------------------------------------------------------------------------- */ typedef struct { @@ -1043,22 +1717,111 @@ typedef struct { ray_t** col_vecs; int64_t n_rows; int64_t* sym_max_ids; - bool fill_ok; + const int* fill_cols; /* [n_fill] RAY_STR column indices */ + int n_fill; + bool* fill_ok; /* [n_fill] per-task result */ + csv_dedup_ctx_t dd; /* SYM columns: cols[], dicts[] */ + int n_sym; + bool* empties; /* [n_cols] SYM/STR column wrote a null */ bool intern_ok; } csv_finalize_ctx_t; +/* dispatch 1: [0, n_fill) fill a RAY_STR column, [n_fill, n_fill+n_sym) dedupe + * a SYM column. */ static void csv_finalize_task(void* arg, uint32_t worker_id, int64_t start, int64_t end_idx) { - (void)worker_id; (void)end_idx; csv_finalize_ctx_t* ctx = (csv_finalize_ctx_t*)arg; - if (start == 0) { - ctx->fill_ok = csv_fill_str_cols(ctx->str_refs, ctx->n_cols, - ctx->resolved_types, ctx->col_vecs, ctx->n_rows); + if (start < (int64_t)ctx->n_fill) { + int c = ctx->fill_cols[start]; + bool saw_null = false; + ctx->fill_ok[start] = csv_fill_str_col(ctx->str_refs[c], + ctx->col_vecs[c], ctx->n_rows, + &saw_null); + csv_note_empty(ctx->empties, c, saw_null); } else { - ctx->intern_ok = csv_intern_strings(ctx->str_refs, ctx->n_cols, - ctx->parse_types, ctx->resolved_types, ctx->col_data, - ctx->n_rows, ctx->sym_max_ids); + csv_dedup_task(&ctx->dd, worker_id, start - (int64_t)ctx->n_fill, end_idx); + } +} + +/* Run the finalize steps, in parallel when the pool allows. Returns false if + * any step failed or the load was cancelled. fill_cols/fill_ok/sym_cols/dicts + * are caller-owned scratch of at least n_cols entries, uninitialised — this + * function zeroes the dictionaries itself before dispatching (a task the pool + * skips on cancellation must read as "not done"), and releases every one of + * them before it returns, on every path. + * + * prog_base/prog_len describe this phase's slice of the load's byte axis; pass + * len 0 when no progress span is active (the streaming conversion path). */ +static bool csv_finalize_run(csv_finalize_ctx_t* ctx, int* fill_cols, + bool* fill_ok, int* sym_cols, csv_dedup_t* dicts, + bool* empties, + uint64_t prog_base, uint64_t prog_len) { + int n_fill = 0, n_sym = 0; + for (int c = 0; c < ctx->n_cols; c++) { + if (ctx->parse_types[c] != CSV_TYPE_STR || !ctx->str_refs[c]) continue; + if (ctx->resolved_types[c] == RAY_STR) fill_cols[n_fill++] = c; + else sym_cols[n_sym++] = c; + } + for (int i = 0; i < n_fill; i++) fill_ok[i] = true; + memset(dicts, 0, (size_t)n_sym * sizeof(csv_dedup_t)); + + ctx->fill_cols = fill_cols; + ctx->n_fill = n_fill; + ctx->fill_ok = fill_ok; + ctx->n_sym = n_sym; + ctx->empties = empties; + ctx->intern_ok = true; + ctx->dd.str_refs = ctx->str_refs; + ctx->dd.col_data = ctx->col_data; + ctx->dd.cols = sym_cols; + ctx->dd.dicts = dicts; + ctx->dd.n_rows = ctx->n_rows; + ctx->dd.empty_gid = 0; + ctx->dd.empties = ctx->empties; + + /* Slice the phase: dedupe+fill is the bulk, the serial intern touches only + * distinct strings, the remap is one linear pass per SYM column. Measured + * roughly 60 / 10 / 30 on the 8 GB file. */ + uint64_t w1 = prog_len * 6 / 10; + uint64_t w2 = prog_len / 10; + + int64_t n_tasks = (int64_t)n_fill + (int64_t)n_sym; + ray_pool_t* pool = ray_pool_get(); + bool par = pool && ray_pool_total_workers(pool) >= 2 && + n_tasks > 0 && n_tasks <= (int64_t)RAY_POOL_INIT_TASKS; + + if (prog_len) ray_progress_span_phase("finalize", prog_base, w1); + if (par) ray_pool_dispatch_n(pool, csv_finalize_task, ctx, (uint32_t)n_tasks); + else for (int64_t i = 0; i < n_tasks; i++) csv_finalize_task(ctx, 0, i, i + 1); + /* Cancellation drains the ticket queue WITHOUT running fn, so a skipped + * dedupe leaves dicts[i].done == false and codes unwritten. Bail here + * rather than letting step B fall back on 105 columns' worth of scratch we + * are about to throw away. */ + if (ray_interrupted()) goto fail; + + if (prog_len) ray_progress_span_phase("intern", prog_base + w1, w2); + ctx->intern_ok = csv_intern_dicts(&ctx->dd, n_sym, ctx->sym_max_ids, + prog_base + w1, w2); + if (!ctx->intern_ok || ray_interrupted()) goto fail; + + if (n_sym > 0) { + if (prog_len) + ray_progress_span_phase("sym ids", prog_base + w1 + w2, + prog_len - w1 - w2); + if (par) ray_pool_dispatch_n(pool, csv_dedup_map_task, &ctx->dd, + (uint32_t)n_sym); + else for (int64_t i = 0; i < n_sym; i++) + csv_dedup_map_task(&ctx->dd, 0, i, i + 1); + if (ray_interrupted()) goto fail; } + + for (int i = 0; i < n_sym; i++) csv_dedup_release(&dicts[i]); + for (int i = 0; i < n_fill; i++) if (!fill_ok[i]) return false; + return true; + +fail: + for (int i = 0; i < n_sym; i++) csv_dedup_release(&dicts[i]); + return false; } /* -------------------------------------------------------------------------- @@ -1466,10 +2229,14 @@ static int csv_hash_elem_size(int8_t t) { * BOOL/U8/I16 where the index would dwarf the column. * * Returns 1 to attach, 0 to skip. */ -/* Payload-level core of the hash-upgrade decision, shared with the - * .csv.splayed index builder (ray_splay_build_indexes) so the on-disk - * store makes the SAME hash-vs-zone decision the in-memory load does -- - * a reloaded store must not query slower than a fresh .csv.read. */ +/* Payload-level core of the hash-upgrade decision. Its only caller is the + * .csv.splayed index builder (ray_splay_build_indexes): indexing is a + * CONVERSION-time decision, made once and persisted with the column files. + * A `.csv.read` into memory attaches nothing (it used to run this same + * heuristic over every column and throw the result away — 19.7 s of a 46 s + * 8 GB load), so there is no in-memory decision left for the on-disk one to + * match. It lives here because the heuristic is written against the + * chunk-zone payload the CSV type machinery defines. */ int ray_csv_hash_upgrade_check(int8_t type, int64_t len, const void* index_payload) { const ray_index_t* ix = (const ray_index_t*)index_payload; @@ -1550,13 +2317,6 @@ int ray_csv_hash_upgrade_check(int8_t type, int64_t len, return 1; } -static int csv_should_attach_hash(ray_t* v) { - if (!v || RAY_IS_ERR(v)) return 0; - if (!(v->attrs & RAY_ATTR_HAS_INDEX) || !v->index) return 0; - return ray_csv_hash_upgrade_check(v->type, v->len, - ray_index_payload(v->index)); -} - /* -------------------------------------------------------------------------- * `INT` schema columns — auto narrowest integer width. * @@ -1736,6 +2496,10 @@ 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)); + /* Set by the finalizer for any SYM/STR column that WROTE a canonical null + * (sym id 0 / zero-length descriptor) — see csv_note_empty. */ + bool col_wrote_null[CSV_MAX_COLS]; + if (ncols > 0) memset(col_wrote_null, 0, (size_t)ncols * sizeof(bool)); bool col_had_escaped[CSV_MAX_COLS]; memset(col_had_escaped, 0, sizeof(col_had_escaped)); @@ -1866,20 +2630,15 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, .col_vecs = col_vecs, .n_rows = n_rows, .sym_max_ids = sym_max_ids, - .fill_ok = true, - .intern_ok = true, }; - 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 || ray_interrupted()) { + int fill_cols[CSV_MAX_COLS]; + int sym_cols[CSV_MAX_COLS]; + bool fill_ok[CSV_MAX_COLS]; + csv_dedup_t dicts[CSV_MAX_COLS]; + /* No progress span on the conversion path — pass a zero-length slice. */ + bool fin_ok = csv_finalize_run(&fctx, fill_cols, fill_ok, + sym_cols, dicts, col_wrote_null, 0, 0); + if (!fin_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]); @@ -1889,15 +2648,6 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, } } - for (int c = 0; c < ncols; c++) { - 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++) - if ((int64_t)ids[r] > max_id) max_id = ids[r]; - sym_max_ids[c] = max_id; - } - 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]); @@ -1907,12 +2657,16 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, return ray_error("cancel", "interrupted"); } + /* HAS_NULLS, same rule as the in-memory read path (step 9c there). + * SYM/STR use sym 0 / a zero-length descriptor as their canonical null + * (bfb5b380), and this path had been left behind on the pre-bfb5b380 rule + * that cleared the bit for those two types — so a converted store and a + * fresh .csv.read of the same file disagreed about the same empty cells + * (issue #416). The SYM/STR answer comes from col_wrote_null[], recorded + * by the finalizer at each write site, so it costs no extra pass. */ for (int c = 0; c < ncols; c++) { ray_t* vec = col_vecs[c]; - /* SYM and STR both represent a blank cell as the empty string ("" / - * sym 0) — there is no null distinct from empty, so neither type - * carries HAS_NULLS (a per-row null check on them is pure waste). */ - if (col_had_null[c] && vec->type != RAY_SYM && vec->type != RAY_STR) + if (col_had_null[c] || col_wrote_null[c]) vec->attrs |= RAY_ATTR_HAS_NULLS; else vec->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; @@ -1954,65 +2708,12 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, col_data[c] = dst; } - /* Per-chunk min/max + null bit on every column big enough to be worth - * indexing — gives the reduce min/max and the filter chunk-skip paths - * an O(n_chunks) scan instead of O(n_rows). Attach is best-effort: - * unsupported types (RAY_STR/RAY_SYM/RAY_GUID in v1) just stay - * unindexed and the consumer falls back to a row scan. - * - * After the chunk_zone attaches we re-walk the same columns and - * upgrade the high-entropy ones to a hash index (the chunk_zone - * stays as well — it's the entropy signal we just measured). See - * csv_should_attach_hash for the selectivity + memory cap. - * - * Progress: same treatment as the finalize dispatch above — the - * per-column index builds run their own pool dispatches whose row - * totals are not n_rows, so letting them drive the progress pump - * resets a completed parse to arbitrary fractions (visibly - * 100% -> 50% -> ...). Suppress progress for the whole index - * phase; the parse's completed row count stays on screen. */ - uint32_t idx_qmode = ray_qstats_mode(); - ray_qstats_set_mode(idx_qmode & ~RAY_QS_PROGRESS); - for (int c = 0; c < ncols; c++) { - if (ray_interrupted()) { - ray_qstats_set_mode(idx_qmode); - 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()) { - ray_qstats_set_mode(idx_qmode); - 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()) { - ray_qstats_set_mode(idx_qmode); - 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 - * column first; the chunk_zone we just built is sacrificed - * for the hash. That's the right trade — once the column - * 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()) { - ray_qstats_set_mode(idx_qmode); - 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; - } - ray_qstats_set_mode(idx_qmode); + /* No index attach here. This function feeds the streaming csv→splayed / + * →parted writers: every column it produces is immediately serialised to + * disk and thrown away, and store/splay.c decides and persists the real + * index (chunk-zone / dict, upgraded to hash by + * ray_csv_hash_upgrade_check) at conversion time. Building an in-memory + * index per 1M-row chunk here was pure waste. */ ray_t* tbl = ray_table_new(ncols); if (!tbl || RAY_IS_ERR(tbl)) { @@ -2060,9 +2761,12 @@ static const char* csv_skip_matching_header(const char* p, const char* buf_end, * ray_read_csv_opts — main CSV parser * -------------------------------------------------------------------------- */ -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) { +/* Body of ray_read_csv_named_opts. Split out so the byte-metered progress + * span is closed on exactly one path, whichever of the dozen returns below + * fires. */ +static ray_t* csv_read_named_opts_inner(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 ---- */ @@ -2088,6 +2792,11 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, const char* buf_end = buf + file_size; ray_t* result = NULL; + /* One monotone bar for the whole load, metered in bytes of input. Every + * return path below runs through ray_progress_span_end (the executor's + * ray_progress_end also clears it, so an early error cannot strand it). */ + ray_progress_span_begin(NULL, (uint64_t)file_size); + /* ---- 3. Detect delimiter ---- */ /* Delimiter auto-detected from header row only. Files where the header * has a different delimiter distribution than data rows may be misdetected; @@ -2171,7 +2880,11 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, /* ---- 6. Build row offsets (memchr-accelerated) ---- */ ray_t* row_offsets_hdr = NULL; int64_t* row_offsets = NULL; + uint64_t prog_scan_end = csv_prog_at(file_size, CSV_PROG_PCT_SCAN); + uint64_t prog_parse_end = csv_prog_at(file_size, + CSV_PROG_PCT_SCAN + CSV_PROG_PCT_PARSE); int64_t n_rows = build_row_offsets(buf, file_size, data_offset, + 0, prog_scan_end, &row_offsets, &row_offsets_hdr); if (n_rows < 0) { @@ -2248,6 +2961,11 @@ 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)); + /* Set by the finalizer for any SYM/STR column that WROTE a canonical null + * (sym id 0 / zero-length descriptor). Feeds step 9c below. */ + bool col_wrote_null[CSV_MAX_COLS]; + if (ncols > 0) memset(col_wrote_null, 0, (size_t)ncols * sizeof(bool)); + bool col_had_escaped[CSV_MAX_COLS]; memset(col_had_escaped, 0, sizeof(col_had_escaped)); @@ -2308,6 +3026,7 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, } } + ray_progress_span_phase("parse", prog_scan_end, prog_parse_end - prog_scan_end); { ray_pool_t* pool = ray_pool_get(); bool use_parallel = pool && n_rows > 8192; @@ -2380,24 +3099,21 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, .col_vecs = col_vecs, .n_rows = n_rows, .sym_max_ids = sym_max_ids, - .fill_ok = true, - .intern_ok = true, }; - 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 || ray_interrupted()) { + /* Finalization used to be hidden from the progress pump entirely (its + * 0/2 would have reset a completed n_rows parse to 50%), which left + * the terminal frozen for the rest of the load. On the byte axis it + * is simply the last slice, and csv_finalize_run subdivides it across + * its three steps. */ + int fill_cols[CSV_MAX_COLS]; + int sym_cols[CSV_MAX_COLS]; + bool fill_ok[CSV_MAX_COLS]; + csv_dedup_t dicts[CSV_MAX_COLS]; + bool fin_ok = csv_finalize_run(&fctx, fill_cols, fill_ok, + sym_cols, dicts, col_wrote_null, + prog_parse_end, + (uint64_t)file_size - prog_parse_end); + if (!fin_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); @@ -2408,41 +3124,37 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, } } - for (int c = 0; c < ncols; c++) { - 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++) { - 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, 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 ---- + /* ---- 9c. Set HAS_NULLS for columns that saw a canonical null ---- * * Sentinels in the payload carry the null state; HAS_NULLS is the - * vec-level fast-path bit. SYM columns are no-null by design — - * empty fields were already remapped to sym 0 in step 9b. */ + * vec-level fast-path bit. SYM/STR use sym 0 / empty descriptors as + * canonical nulls, including explicitly quoted empty CSV fields. + * + * For SYM/STR the answer comes from col_wrote_null[], which the finalizer + * records at the point it writes each cell using ray_vec_is_null's own + * predicate (id == 0 / len == 0). That replaced a per-row + * ray_vec_is_null fallback scan over any SYM/STR column the parse had not + * already flagged — same semantics, but free instead of 0.207 s of + * whole-column passes on the 8 GB file. */ for (int c = 0; c < ncols; c++) { ray_t* vec = col_vecs[c]; - /* SYM and STR both represent a blank cell as the empty string ("" / - * sym 0) — there is no null distinct from empty, so neither type - * carries HAS_NULLS (a per-row null check on them is pure waste). */ - if (col_had_null[c] && vec->type != RAY_SYM && vec->type != RAY_STR) + bool has_null = col_had_null[c] || col_wrote_null[c]; + if (has_null) vec->attrs |= RAY_ATTR_HAS_NULLS; else vec->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; } - /* ---- 10. Narrow sym columns to optimal width ---- */ + /* ---- 10. Narrow sym columns to optimal width ---- + * sym_max_ids[] comes from csv_intern_dicts, which already saw every id it + * handed out; the full 10M-row rescan that used to recompute it here was + * pure duplication (0.26 s on the 8 GB file). */ for (int c = 0; c < ncols; c++) { if (resolved_types[c] != RAY_SYM) continue; uint8_t new_w = ray_sym_dict_width(sym_max_ids[c]); @@ -2479,34 +3191,13 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, /* ---- 11. Build table ---- */ { - /* Best-effort per-chunk zone index attach (see comment on the - * matching loop in build_table_from_cols) — unsupported types - * fall through to the unindexed path inside the consumer. - * Second pass upgrades high-entropy columns to a hash index; - * see csv_should_attach_hash. - * Progress suppressed for the whole phase (same rationale as the - * finalize dispatch): the index builds' pool dispatches would - * reset the completed parse progress to arbitrary fractions. */ - uint32_t idx_qmode = ray_qstats_mode(); - ray_qstats_set_mode(idx_qmode & ~RAY_QS_PROGRESS); - for (int c = 0; c < ncols; c++) { - if (ray_interrupted()) { ray_qstats_set_mode(idx_qmode); 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()) { ray_qstats_set_mode(idx_qmode); goto fail_cols_cancel; } - if (r && !RAY_IS_ERR(r)) col_vecs[c] = v; - } - for (int c = 0; c < ncols; c++) { - if (ray_interrupted()) { ray_qstats_set_mode(idx_qmode); 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()) { ray_qstats_set_mode(idx_qmode); goto fail_cols_cancel; } - if (r && !RAY_IS_ERR(r)) col_vecs[c] = v; - } - ray_qstats_set_mode(idx_qmode); + /* No index attach at load time. Index policy lives at csv→splayed + * CONVERSION (store/splay.c: chunk-zone / dict, upgraded to a hash + * index by ray_csv_hash_upgrade_check) where the decision is made + * once and persisted. A `.csv.read` into memory used to pay for a + * chunk-zone AND a hash index on all 105 columns of an 8 GB file — + * 3.6 s + 16.1 s of a 46 s load — for indexes most in-memory reads + * never probe. Columns that need one can be indexed explicitly. */ ray_t* tbl = ray_table_new(ncols); if (!tbl || RAY_IS_ERR(tbl)) { @@ -2546,6 +3237,16 @@ ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header, return ray_error("oom", NULL); } +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) { + ray_t* r = csv_read_named_opts_inner(path, delimiter, header, + col_types_in, n_types, + col_names_in, n_names); + ray_progress_span_end(); + return r; +} + ray_t* ray_read_csv_opts(const char* path, char delimiter, bool header, const int8_t* col_types_in, int32_t n_types) { return ray_read_csv_named_opts(path, delimiter, header, @@ -2625,6 +3326,14 @@ static ray_err_t csv_splayed_writer_append(csv_splayed_col_writer_t* w, ray_str_len(s)); if (pos < 0) return RAY_ERR_OOM; buf[i] = (uint32_t)pos; + /* Position 0 of any symfile is the empty string (domain.c + * enforces that reservation on open), so a re-encoded cell is + * the canonical SYM null exactly when its position is 0. + * Testing the value WRITTEN keeps the on-disk HAS_NULLS honest + * without trusting the chunk vec's attrs — and this arm is why + * streamed SYM columns used to lose the bit entirely: only the + * non-SYM arm below propagated it (issue #416). */ + if (pos == 0) w->had_nulls = true; } if (fwrite(buf, sizeof(uint32_t), (size_t)cnt, w->fp) != (size_t)cnt) return RAY_ERR_IO; diff --git a/src/lang/eval.c b/src/lang/eval.c index 72f8196c0..29369e1cf 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -266,7 +266,7 @@ static ray_t* try_sum_affine_expr(ray_t* expr, int* handled) { double out = base + as_f64(c_expr) * (double)n; return make_f64(out); } - int64_t out = ce.sum_i + numeric_atom_i64(c_expr) * n; + int64_t out = wrap_add_i64(ce.sum_i, wrap_mul_i64(numeric_atom_i64(c_expr), n)); return make_i64(out); } @@ -610,7 +610,8 @@ static void strvec_cmp_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { /* Pool worker for the R7/R8 SYM compare fast paths. rd == NULL means the * right side is a scalar target id (R7); otherwise element-wise vec-vec * (R8), optionally translating left ids through a vocabulary LUT when the - * domains differ. SYM has no null: pure value compares. */ + * domains differ. Canonical SYM null is raw id 0, so the same value compare + * handles it without a separate bitmap. */ typedef struct { const void* ld; const void* rd; /* NULL for the vec-vs-atom shape */ @@ -906,9 +907,8 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, * thrash dominates: `(!= URL nu)` standalone takes 113 ms when the * raw work is one i64 lookup + N width-truncated cmpneq. * - * Handles either operand order; output is RAY_BOOL. SYM has no - * null (ray_vec_is_null / RAY_ATOM_IS_NULL are both false for SYM), - * so this is a pure value compare — no per-element null rules. */ + * Handles either operand order; output is RAY_BOOL. Canonical empty SYM + * uses id 0, so value comparison also preserves empty/null equality. */ if (!force_boxed && (dag_opcode == OP_EQ || dag_opcode == OP_NE) && out_type == RAY_BOOL) { int l_is_sym_vec = left_coll && ray_is_vec(left) && left->type == RAY_SYM; @@ -934,9 +934,8 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, * atom carries a runtime id — re-express it in the * column's domain once before the loops. Runtime-domain * columns keep the raw id (byte-identical fast path). - * Literal absent from the domain ⇒ equals no cell (SYM has - * no null, so there is no null row either): == all-false, - * != all-true. */ + * Literal absent from the domain ⇒ equals no cell: == + * all-false, != all-true. */ int target_absent = 0; struct ray_sym_domain_s* dom = ray_sym_vec_domain(vv); if (dom != ray_sym_runtime_domain()) { @@ -953,8 +952,8 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, bool fill = invert; /* != absent → true; == absent → false */ for (int64_t i = 0; i < n; i++) obuf[i] = fill; } else { - /* SYM has no null: the compare reduces to a tight - * per-width raw-id loop, pool-parallel above the + /* Canonical null is raw id 0, so the compare remains a + * tight per-width raw-id loop, pool-parallel above the * shared morsel threshold (symcmp_eq_fn). */ symcmp_ctx_t sctx = { .ld = src, .rd = NULL, .lattrs = va, .rattrs = 0, @@ -980,7 +979,7 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, * compare raw cell ids width-aware. Cross-domain pairs translate the * LEFT vocabulary into the RIGHT domain once — positions, not rows — * then compare in the right id space; an untranslatable left id - * matches nothing. SYM has no null: pure value compare. */ + * matches nothing. Canonical null is raw id 0 and needs no side bitmap. */ if (!force_boxed && (dag_opcode == OP_EQ || dag_opcode == OP_NE) && out_type == RAY_BOOL && left_coll && right_coll && ray_is_vec(left) && ray_is_vec(right) && @@ -1036,7 +1035,7 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, * comparator) is precomputed once over the domain VOCABULARY — a rank * LUT for vec-vec (union-ranked across two domains so equal strings * rank equal), a three-way verdict LUT for vec-vs-atom — then the row - * loop is pure integer reads, pool-parallel. SYM has no null. */ + * loop is pure integer reads, pool-parallel; canonical null is id 0. */ if (!force_boxed && out_type == RAY_BOOL && (dag_opcode == OP_LT || dag_opcode == OP_LE || dag_opcode == OP_GT || dag_opcode == OP_GE)) { @@ -3408,6 +3407,10 @@ static void ray_register_builtins(void) { * src/app/repl_remote.c for the state model. */ register_unary(".repl.connect", RAY_FN_RESTRICTED, ray_repl_connect_fn); register_vary( ".repl.disconnect", RAY_FN_RESTRICTED, ray_repl_disconnect_fn); + /* Read-only namespace completion (issue #441): builtins + keywords + + * user bindings whose name begins with the given prefix. RAY_FN_NONE + * so remote editor clients can query it over IPC. */ + register_unary(".repl.complete", RAY_FN_NONE, ray_repl_complete_fn); /* Transaction-log journaling under `.log.*` — the -l/-L feature. * The CLI flags -l / -L call ray_journal_open() at diff --git a/src/lang/format.c b/src/lang/format.c index 2dfd96db5..dd56ce50b 100644 --- a/src/lang/format.c +++ b/src/lang/format.c @@ -42,10 +42,30 @@ typedef struct { int32_t len; int32_t cap; ray_t* block; /* ray_alloc'd backing block */ + bool err; /* sticky: set on the 2GiB cap or a failed ray_alloc. + * Once set, every append is a no-op and fmt_to_str + * returns an error instead of a string. */ + const char* err_msg;/* why err was set, surfaced by fmt_to_str */ } fmt_buf_t; +/* The fmt_* append helpers are all void and have no caller to return an error + * to, so a growth failure (the 2GiB int32 buffer ceiling, or a ray_alloc that + * fails under memory pressure) sets the sticky `err` flag instead of writing + * out of bounds. Every append checks it and becomes a no-op, and fmt_to_str + * turns it into a RAY_IS_ERR result. This must NOT abort(): ray_fmt runs on + * IPC-server threads formatting client-supplied values (e.g. a client + * (println ) or query-log of the raw payload), so a process-fatal + * path here is remotely triggerable — a recoverable error keeps the server up + * and every ray_fmt caller already checks RAY_IS_ERR. */ static void fmt_init(fmt_buf_t* b) { - b->block = ray_alloc(256); + b->err = false; + b->err_msg = NULL; + b->block = ray_alloc(256); + if (!b->block) { /* ray_alloc returns NULL (never an error object) on failure */ + b->err = true; b->err_msg = "cannot allocate the initial output buffer"; + b->buf = NULL; b->len = 0; b->cap = 0; + return; + } b->buf = (char*)ray_data(b->block); b->len = 0; b->cap = 256; @@ -61,33 +81,57 @@ static void fmt_destroy(fmt_buf_t* b) { } } -static void fmt_ensure(fmt_buf_t* b, int32_t extra) { - if (b->len + extra <= b->cap) return; - int32_t new_cap = b->cap; - while (new_cap < b->len + extra) +/* extra is int64 so a >2GiB length from a call site reaches the ceiling check + * intact instead of wrapping int32 first (a length in [2^31,2^32) used to wrap + * negative and, via the fast path below, sneak past as a no-grow "fit"). */ +static void fmt_ensure(fmt_buf_t* b, int64_t extra) { + if (b->err) return; + /* Guard a negative/oversize request BEFORE the fast-path return: for a + * negative extra, need = len + extra < len <= cap, so the fast path would + * otherwise return first and leave the bad length to a wild memcpy. */ + if (extra < 0) { b->err = true; b->err_msg = "invalid negative format length"; return; } + int64_t need = (int64_t)b->len + extra; + if (need <= (int64_t)b->cap) return; + if (need > (int64_t)INT32_MAX) { + /* int32 buffer ceiling: the doubling loop and cap field are int32, so + * 2GiB is the hard limit. Fail loud but recoverable, not abort(). */ + b->err = true; b->err_msg = "formatted output exceeds the 2GiB buffer limit"; + return; + } + int64_t new_cap = b->cap; + while (new_cap < need) new_cap *= 2; + if (new_cap > (int64_t)INT32_MAX) + new_cap = INT32_MAX; ray_t* new_block = ray_alloc((size_t)new_cap); + if (!new_block) { /* ray_alloc returns NULL on failure, never an error object */ + b->err = true; b->err_msg = "out of memory growing the output buffer"; + return; + } char* new_buf = (char*)ray_data(new_block); memcpy(new_buf, b->buf, (size_t)b->len); ray_free(b->block); b->block = new_block; b->buf = new_buf; - b->cap = new_cap; + b->cap = (int32_t)new_cap; /* new_cap <= INT32_MAX by the clamp above */ } static void fmt_putc(fmt_buf_t* b, char c) { fmt_ensure(b, 1); + if (b->err) return; b->buf[b->len++] = c; } static void fmt_puts(fmt_buf_t* b, const char* s) { - int32_t slen = (int32_t)strlen(s); + int64_t slen = (int64_t)strlen(s); fmt_ensure(b, slen); + if (b->err) return; memcpy(b->buf + b->len, s, (size_t)slen); - b->len += slen; + b->len += (int32_t)slen; /* safe: fmt_ensure enforced need <= INT32_MAX */ } static void fmt_printf(fmt_buf_t* b, const char* fmt, ...) { + if (b->err) return; va_list ap; /* Try to fit in remaining space first */ @@ -104,20 +148,27 @@ static void fmt_printf(fmt_buf_t* b, const char* fmt, ...) { } /* Need more space — grow and retry */ - fmt_ensure(b, n + 1); + fmt_ensure(b, (int64_t)n + 1); + if (b->err) return; va_start(ap, fmt); vsnprintf(b->buf + b->len, (size_t)(b->cap - b->len), fmt, ap); va_end(ap); b->len += n; } -static void fmt_putn(fmt_buf_t* b, const char* s, int32_t n) { +static void fmt_putn(fmt_buf_t* b, const char* s, int64_t n) { fmt_ensure(b, n); + if (b->err) return; memcpy(b->buf + b->len, s, (size_t)n); - b->len += n; + b->len += (int32_t)n; /* safe: fmt_ensure enforced need <= INT32_MAX */ } static ray_t* fmt_to_str(fmt_buf_t* b) { + if (b->err) { + ray_t* e = ray_error("format", "%s", b->err_msg ? b->err_msg : "output buffer error"); + fmt_destroy(b); + return e; + } ray_t* result = ray_str(b->buf, (size_t)b->len); fmt_destroy(b); return result; @@ -252,11 +303,10 @@ static void fmt_guid(fmt_buf_t* b, const uint8_t* bytes) { * owned by their table/domain; never released here). */ static void fmt_sym_atom(fmt_buf_t* b, ray_t* s) { if (s && !RAY_IS_ERR(s) && ray_str_len(s) > 0) { - fmt_putn(b, ray_str_ptr(s), (int32_t)ray_str_len(s)); + fmt_putn(b, ray_str_ptr(s), (int64_t)ray_str_len(s)); } else { - /* sym 0 (the empty symbol, resolves to "") and any unresolvable - * id render as the bare quote literal `'` — the canonical spelling - * of the empty symbol. SYM has no null, so there is no `0Ns`. */ + /* sym 0 (the canonical empty/null symbol) and any unresolvable id + * render as the bare quote literal `'`; there is no separate `0Ns`. */ fmt_putc(b, '\''); } } @@ -330,7 +380,7 @@ static void fmt_str_atom(fmt_buf_t* b, ray_t* obj, int full) { const char* p = ray_str_ptr(obj); size_t n = ray_str_len(obj); fmt_putc(b, '"'); - fmt_putn(b, p, (int32_t)n); + fmt_putn(b, p, (int64_t)n); fmt_putc(b, '"'); } @@ -352,10 +402,8 @@ static const char* null_literal(int8_t type) { case RAY_DATE: return "0Nd"; case RAY_TIME: return "0Nt"; case RAY_TIMESTAMP: return "0Np"; - /* SYM has no null literal: the empty symbol is a value (renders as ') - * and never reaches this table — callers gate on null, false for SYM. - * RAY_STR likewise has no null literal: empty and null strings both - * render as "" (handled directly by the STR paths, never via this table). */ + /* SYM/STR have no separate null literal: their canonical empty/null values + * render as ' / "" on their ordinary formatting paths. */ case RAY_GUID: return "0Ng"; default: return "null"; } @@ -392,7 +440,7 @@ static void fmt_raw_elem(fmt_buf_t* b, ray_t* vec, int64_t idx) { size_t slen = 0; const char* p = ray_str_vec_get(vec, idx, &slen); fmt_putc(b, '"'); - if (p) fmt_putn(b, p, (int32_t)slen); + if (p) fmt_putn(b, p, (int64_t)slen); fmt_putc(b, '"'); break; } @@ -404,7 +452,7 @@ static void fmt_raw_elem(fmt_buf_t* b, ray_t* vec, int64_t idx) { if (child) { ray_t* s = ray_fmt(child, 1); if (s && !RAY_IS_ERR(s)) { - fmt_putn(b, ray_str_ptr(s), (int32_t)ray_str_len(s)); + fmt_putn(b, ray_str_ptr(s), (int64_t)ray_str_len(s)); ray_release(s); } else { fmt_puts(b, "?"); @@ -663,9 +711,72 @@ static void fmt_dict(fmt_buf_t* b, ray_t* dict, int mode) { /* ===== Table formatter helpers ===== */ +/* Terminal display width of a UTF-8 string. Byte length overstates the + * width of any multi-byte cell (a 3-byte CJK char renders as 2 columns, + * not 3), which skewed every pad computed from it and tore the table + * borders. Coarse East-Asian-Width classification: wide/fullwidth CJK, + * Hangul, fullwidth forms and emoji count 2; zero-width marks count 0; + * everything else, malformed bytes included, counts 1 — so a bad + * sequence can never desync more than its own cell. */ +static int32_t fmt_utf8_width(const char* s, int32_t slen) { + int32_t w = 0; + for (int32_t i = 0; i < slen;) { + uint8_t c = (uint8_t)s[i]; + if (c < 0x80) { w += 1; i += 1; continue; } + uint32_t cp; + int32_t cont; + if ((c & 0xE0) == 0xC0) { cp = c & 0x1Fu; cont = 1; } + else if ((c & 0xF0) == 0xE0) { cp = c & 0x0Fu; cont = 2; } + else if ((c & 0xF8) == 0xF0) { cp = c & 0x07u; cont = 3; } + else { w += 1; i += 1; continue; } + if (i + cont >= slen) { w += 1; i += 1; continue; } + bool ok = true; + for (int32_t k = 1; k <= cont; k++) { + uint8_t cc = (uint8_t)s[i + k]; + if ((cc & 0xC0) != 0x80) { ok = false; break; } + cp = (cp << 6) | (cc & 0x3Fu); + } + if (!ok) { w += 1; i += 1; continue; } + i += cont + 1; + if ((cp >= 0x0300 && cp <= 0x036F) || /* Latin combining marks */ + (cp >= 0x0483 && cp <= 0x0489) || /* Cyrillic combining */ + (cp >= 0x0591 && cp <= 0x05BD) || /* Hebrew points (niqqud) */ + cp == 0x05BF || cp == 0x05C1 || cp == 0x05C2 || + cp == 0x05C4 || cp == 0x05C5 || cp == 0x05C7 || + (cp >= 0x0610 && cp <= 0x061A) || /* Arabic marks */ + (cp >= 0x064B && cp <= 0x065F) || /* Arabic harakat */ + cp == 0x0670 || + (cp >= 0x06D6 && cp <= 0x06DC) || + (cp >= 0x0E31 && cp <= 0x0E3A) || /* Thai vowels above/below */ + (cp >= 0x0E47 && cp <= 0x0E4E) || + (cp >= 0x200B && cp <= 0x200F) || /* zero-width spaces */ + (cp >= 0x202A && cp <= 0x202E) || /* bidi embedding/override */ + (cp >= 0x2060 && cp <= 0x2064) || /* word joiner, invisibles */ + (cp >= 0x2066 && cp <= 0x2069) || /* bidi isolates */ + (cp >= 0xFE00 && cp <= 0xFE0F) || /* variation selectors */ + (cp >= 0xFE20 && cp <= 0xFE2F) || /* combining half marks */ + cp == 0xFEFF) /* BOM / zero-width nbsp */ + continue; /* width 0 */ + if ((cp >= 0x1100 && cp <= 0x115F) || /* Hangul jamo */ + (cp >= 0x2E80 && cp <= 0xA4CF) || /* CJK radicals..Yi */ + (cp >= 0xAC00 && cp <= 0xD7A3) || /* Hangul syllables */ + (cp >= 0xF900 && cp <= 0xFAFF) || /* CJK compat ideographs */ + (cp >= 0xFE30 && cp <= 0xFE4F) || /* CJK compat forms */ + (cp >= 0xFF00 && cp <= 0xFF60) || /* fullwidth forms */ + (cp >= 0xFFE0 && cp <= 0xFFE6) || /* fullwidth signs */ + (cp >= 0x1F300 && cp <= 0x1FAFF) || /* emoji */ + (cp >= 0x20000 && cp <= 0x3FFFD)) /* CJK ext B+ */ + w += 2; + else + w += 1; + } + return w; +} + static void fmt_centered(fmt_buf_t* b, const char* s, int32_t slen, int32_t width) { - int32_t left = (width - slen) / 2; - int32_t right = width - slen - left; + int32_t dlen = fmt_utf8_width(s, slen); + int32_t left = (width - dlen) / 2; + int32_t right = width - dlen - left; for (int32_t i = 0; i < left; i++) fmt_putc(b, ' '); fmt_putn(b, s, slen); for (int32_t i = 0; i < right; i++) fmt_putc(b, ' '); @@ -691,7 +802,7 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { int64_t name_id = ray_table_col_name(tbl, i); ray_t* name_str = ray_sym_str(name_id); if (name_str && !RAY_IS_ERR(name_str)) { - fmt_putn(b, ray_str_ptr(name_str), (int32_t)ray_str_len(name_str)); + fmt_putn(b, ray_str_ptr(name_str), (int64_t)ray_str_len(name_str)); ray_release(name_str); } } @@ -803,8 +914,9 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { col_types[ci] = tname; col_type_lens[ci] = (int32_t)strlen(tname); - /* Start with max of name and type lengths */ - int32_t max_w = col_name_lens[ci]; + /* Start with max of name and type DISPLAY widths (a multi-byte + * name still writes its full byte length, padded to this). */ + int32_t max_w = fmt_utf8_width(col_names[ci], col_name_lens[ci]); if (col_type_lens[ci] > max_w) max_w = col_type_lens[ci]; int64_t col_len = col_vec ? ray_len(col_vec) : 0; @@ -818,7 +930,7 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { fmt_init(&tmp); fmt_raw_elem(&tmp, col_vec, ri); int32_t clen = tmp.len < FMT_CELL_BUF_SIZE - 1 ? tmp.len : FMT_CELL_BUF_SIZE - 1; - memcpy(cell->str, tmp.buf, (size_t)clen); + if (clen > 0) memcpy(cell->str, tmp.buf, (size_t)clen); cell->str[clen] = '\0'; cell->len = clen; fmt_destroy(&tmp); @@ -826,7 +938,8 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { memcpy(cell->str, "NA", 3); cell->len = 2; } - if (cell->len > max_w) max_w = cell->len; + int32_t cell_dw = fmt_utf8_width(cell->str, cell->len); + if (cell_dw > max_w) max_w = cell_dw; } /* Format second half (tail rows) */ @@ -843,7 +956,7 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { fmt_init(&tmp); fmt_raw_elem(&tmp, col_vec, src_idx); int32_t clen = tmp.len < FMT_CELL_BUF_SIZE - 1 ? tmp.len : FMT_CELL_BUF_SIZE - 1; - memcpy(cell->str, tmp.buf, (size_t)clen); + if (clen > 0) memcpy(cell->str, tmp.buf, (size_t)clen); cell->str[clen] = '\0'; cell->len = clen; fmt_destroy(&tmp); @@ -851,7 +964,8 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { memcpy(cell->str, "NA", 3); cell->len = 2; } - if (cell->len > max_w) max_w = cell->len; + int32_t cell_dw = fmt_utf8_width(cell->str, cell->len); + if (cell_dw > max_w) max_w = cell_dw; } col_widths[ci] = max_w + 2; /* +2 for padding (1 space each side) */ @@ -960,7 +1074,7 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { fmt_cell_t* cell = &cells[ci * table_height + ri]; fmt_putc(b, ' '); fmt_putn(b, cell->str, cell->len); - int32_t pad = col_widths[ci] - cell->len - 1; + int32_t pad = col_widths[ci] - fmt_utf8_width(cell->str, cell->len) - 1; for (int32_t p = 0; p < pad; p++) fmt_putc(b, ' '); fmt_puts(b, G_V); @@ -1031,11 +1145,9 @@ static void fmt_obj(fmt_buf_t* b, ray_t* obj, int mode) { int8_t type = obj->type; if (type < 0) { - /* Typed null atom: null bit set → display as 0Nx. STR is the - * exception — it has no distinct null (empty and null are the - * same value), so it always falls through to fmt_str_atom and - * renders as "", never 0Nc (which the parser cannot read back). */ - if (-type != RAY_STR && RAY_ATOM_IS_NULL(obj)) { + /* STR/SYM use their empty literals as canonical null spellings, so + * retain those parseable representations instead of inventing 0Nc/0Ns. */ + if (-type != RAY_STR && -type != RAY_SYM && RAY_ATOM_IS_NULL(obj)) { fmt_puts(b, null_literal(-type)); return; } diff --git a/src/lang/syscmd.c b/src/lang/syscmd.c index 6e8d97b5a..a02c07c29 100644 --- a/src/lang/syscmd.c +++ b/src/lang/syscmd.c @@ -130,19 +130,53 @@ static ray_t* h_listen(ray_t* arg, ray_syscmd_ctx_t* ctx) { (void)arg; return ray_error("restricted", "listen disabled under fuzzing"); #endif - int err = 0; - int64_t port = arg_as_i64(arg, &err); - if (err) return ray_error("type", "listen expects a port number"); + /* Two forms: a port number binds INADDR_ANY (unchanged), and a + * "HOST:PORT" string confines the listener to one IPv4 address + * (#427) — e.g. (.sys.listen "127.0.0.1:7701") for loopback-only. */ + char host[64]; + const char* bind_host = NULL; + int64_t port; + const char* s = (arg && arg->type == -RAY_STR) ? ray_str_ptr(arg) : NULL; + size_t slen = s ? ray_str_len(arg) : 0; + const char* colon = s ? memchr(s, ':', slen) : NULL; + if (colon) { + if (colon == s || (size_t)(colon - s) >= sizeof(host)) + return ray_error("type", "listen expects a port number or \"HOST:PORT\""); + memcpy(host, s, (size_t)(colon - s)); + host[colon - s] = '\0'; + bind_host = host; + /* Strict digits-only port, the .ipc.open rule: "1abc" is a + * malformed port, not port 1. */ + char pbuf[16]; + size_t plen = slen - (size_t)(colon - s) - 1; + if (plen == 0 || plen >= sizeof(pbuf)) + return ray_error("domain", "listen: port out of range (1..65535)"); + memcpy(pbuf, colon + 1, plen); + pbuf[plen] = '\0'; + char* endp; + errno = 0; + long pv = strtol(pbuf, &endp, 10); + if (endp == pbuf || *endp != '\0' || errno == ERANGE) + return ray_error("domain", "listen: port must be numeric 1..65535, got \"%s\"", pbuf); + port = (int64_t)pv; + } else { + /* Port-only form: an i64/int atom, or (via the .sys.cmd string + * dispatcher) a numeric string — arg_as_i64 handles both. */ + int err = 0; + port = arg_as_i64(arg, &err); + if (err) return ray_error("type", "listen expects a port number or \"HOST:PORT\""); + } if (port <= 0 || port > 65535) return ray_error("domain", "listen: port out of range (1..65535)"); ray_poll_t* poll = (ray_poll_t*)ray_runtime_get_poll(); if (!poll) return ray_error("nyi", "listen: no main event loop attached"); - int64_t id = ray_ipc_listen(poll, (uint16_t)port); + int64_t id = ray_ipc_listen_at(poll, bind_host, (uint16_t)port); if (id < 0) { int e = errno; - return ray_error("io", "listen: bind to port %lld failed: %s", - (long long)port, strerror(e ? e : EADDRINUSE)); + return ray_error("io", "listen: bind to %s port %lld failed: %s", + bind_host ? bind_host : "*", (long long)port, + strerror(e ? e : EADDRINUSE)); } return ray_i64(id); } @@ -241,7 +275,7 @@ static const ray_syscmd_t TABLE[] = { { "timeit", "t", h_timeit, 0, "Toggle profiling on/off (or :t 0|1)." }, { "env", NULL, h_env, 0, "List defined globals." }, { "clear", NULL, h_clear, RAY_SYSCMD_REPL_ONLY, "Clear the screen." }, - { "listen", NULL, h_listen, RAY_SYSCMD_RESTRICTED, "Start IPC listener on PORT." }, + { "listen", NULL, h_listen, RAY_SYSCMD_RESTRICTED, "Start IPC listener on PORT or \"HOST:PORT\"." }, { "q", NULL, h_quit, RAY_SYSCMD_REPL_ONLY, "Exit the REPL." }, { "quit", NULL, h_quit, RAY_SYSCMD_REPL_ONLY, "Exit the REPL." }, }; diff --git a/src/mem/heap.c b/src/mem/heap.c index 8c9fe9a34..6260ff7be 100644 --- a/src/mem/heap.c +++ b/src/mem/heap.c @@ -31,6 +31,7 @@ #include "cow.h" #include "sys.h" #include "core/platform.h" +#include "core/timer.h" /* ray_time_now_ms — idle-decay clock */ #include "table/sym.h" #include "table/domain.h" #include "lang/eval.h" @@ -371,15 +372,15 @@ void ray_heap_set_anon_watermark(int64_t bytes) { ray_heap_t* ray_heap_registry[RAY_HEAP_REGISTRY_SIZE]; -/* Serializes the registry slot writes (register/unregister) and the - * cross-heap foreign-list purges that walk EVERY other heap's ->foreign - * during teardown. ray_pool_free() joins workers one at a time, but all - * workers wake on the shutdown signal together and run ray_heap_destroy() - * CONCURRENTLY — two destroyers splicing the same neighbour's singly-linked - * ->foreign list (or one walking a slot another is NULLing) tears the list - * and SEGVs on the next ->fl_next deref. Spinlock matches the dfd_lock - * pattern above; held only across the short registry/foreign critical - * sections, never across munmap or syscalls. */ +/* Serializes registry slot writes (register / unregister) and the + * abandoned-heap LIFO. Workers wake on the shutdown signal together and + * leave their heaps CONCURRENTLY, so those two structures need one owner at + * a time. Spinlock matches the dfd_lock pattern above; held only across the + * short critical sections, never across munmap or syscalls. + * + * The free path deliberately does NOT take this lock: it only READS a + * registry slot, and a heap in the registry is never freed while a thread + * could still be freeing into it (see ray_heap_abandon). */ static atomic_flag ray_registry_lock_flag = ATOMIC_FLAG_INIT; static void ray_registry_lock(void) { while (atomic_flag_test_and_set_explicit(&ray_registry_lock_flag, memory_order_acquire)) {} } static void ray_registry_unlock(void) { atomic_flag_clear_explicit(&ray_registry_lock_flag, memory_order_release); } @@ -656,6 +657,16 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { * uncounted. Freed via ray_vm_free (which subtracts) at pool teardown. */ ray_sys_track_add((int64_t)pool_size); mem = (void*)aligned; + + /* Unlink now that the mapping holds the inode: the file keeps its + * blocks until the last mapping goes away, and the kernel reclaims + * them on munmap or on process exit, whichever comes first. Doing + * it here rather than at teardown means no path out of this heap + * can strand the file — a worker that abandons its heap for reuse + * never runs a teardown at all. */ + unlink(swap_path); + ray_sys_free(swap_path); + swap_path = NULL; } /* Enable transparent huge pages on anon pools (Linux). Self-aligned @@ -733,67 +744,53 @@ static void heap_flush_slabs(ray_heap_t* h) { } /* -------------------------------------------------------------------------- - * Foreign blocks flush + * Foreign-list drain (owner side) * - * When return_to_owner is true, returns each foreign block to its owning - * heap (via pool header heap_id → global registry). This ensures workers - * can reuse their pools across queries instead of allocating new ones. + * Every block on h->foreign is OWNED BY h: a cross-thread free routes the + * block to its owner rather than parking it on the freeing heap (see the + * foreign path in ray_free). So the drain needs no pool-header lookup for + * ownership, no registry access, and no "are the workers idle?" gate — it + * takes the whole list with one exchange and coalesces into its own + * freelists, which no other thread touches. * - * return_to_owner must only be true when workers are idle (on semaphore), - * i.e. ray_parallel_flag == 0. Otherwise coalesce into current heap. + * The acquire on the exchange pairs with the release on the pusher's CAS, + * so the block contents written before the push are visible here. * -------------------------------------------------------------------------- */ -static void heap_flush_foreign(ray_heap_t* h, bool return_to_owner) { - /* When workers are active (return_to_owner=false), skip entirely. - * Foreign blocks stay queued until the proper GC flush after workers - * finish. Absorbing foreign blocks locally would let them be re- - * allocated under a different heap while pool ownership stays with - * the original heap, corrupting bytes_allocated accounting. */ - if (!return_to_owner) return; - - ray_t* blk = h->foreign; +static void heap_drain_foreign(ray_heap_t* h) { + ray_t* blk = atomic_exchange_explicit(&h->foreign, NULL, + memory_order_acquire); while (blk) { ray_t* next = blk->fl_next; - ray_pool_hdr_t* phdr = ray_pool_of(blk); - if (!phdr) { blk = next; continue; } - uint16_t owner_id = phdr->heap_id; - ray_heap_t* owner = ray_heap_registry[owner_id % RAY_HEAP_REGISTRY_SIZE]; - if (owner && owner->id == owner_id && owner != h) { - /* Return to owner and decrement owner's bytes_allocated. - * Safe: workers are idle (return_to_owner=true implies - * ray_parallel_flag==0). */ - int pidx = heap_find_pool(owner, blk); - uintptr_t pb; - uint8_t po; - if (pidx >= 0) { - pb = (uintptr_t)owner->pools[pidx].base; - po = owner->pools[pidx].pool_order; - } else { - pb = (uintptr_t)phdr; - po = phdr->pool_order; - } - RAY_STAT(owner->stats.bytes_allocated -= BSIZEOF(blk->order)); - heap_coalesce(owner, blk, pb, po); + int pidx = heap_find_pool(h, blk); + uintptr_t pb; + uint8_t po; + if (pidx >= 0) { + pb = (uintptr_t)h->pools[pidx].base; + po = h->pools[pidx].pool_order; } else { - /* Owner gone (destroyed/unregistered) — coalesce locally. - * No stats adjustment: the owner's stats were destroyed - * with the heap, and h never charged the alloc. */ - int pidx = heap_find_pool(h, blk); - uintptr_t pb; - uint8_t po; - if (pidx >= 0) { - pb = (uintptr_t)h->pools[pidx].base; - po = h->pools[pidx].pool_order; - } else { - if (!phdr) { blk = next; continue; } - pb = (uintptr_t)phdr; - po = phdr->pool_order; + /* h owns the block but does not track its pool — only reachable + * through ray_heap_merge's RAY_MAX_POOLS overflow, which rewrites + * the header's heap_id without room for the pool entry. */ + ray_pool_hdr_t* phdr = ray_pool_of(blk); + if (!phdr) { blk = next; continue; } + pb = (uintptr_t)phdr; + po = phdr->pool_order; + /* Adopted from a heap that left the registry while its pools + * were still mapped (ray_heap_push_pending). We never charged + * the allocation, so there is nothing to take off our books — + * unlike the merge-overflow case above, where the header was + * rewritten to name us. */ + if (phdr->heap_id != h->id) { + heap_coalesce(h, blk, pb, po); + blk = next; + continue; } - heap_coalesce(h, blk, pb, po); } + RAY_STAT(h->stats.bytes_allocated -= BSIZEOF(blk->order)); + heap_coalesce(h, blk, pb, po); blk = next; } - h->foreign = NULL; } /* -------------------------------------------------------------------------- @@ -879,10 +876,13 @@ static void ray_release_owned_refs(ray_t* v) { return; } - /* Vector with attached index: aux[0..7] holds an owning ref to - * the index ray_t. The index owns the displaced str_pool, - * so we must NOT also try to release those off the parent — they - * aren't there anymore. Skip the STR_pool branch. */ + /* Vector with attached index: aux[0..7] holds an owning ref to the + * index ray_t. Bytes 8-15 are NOT displaced into the index for a + * STR or SYM parent — attach_finalize leaves the pool or domain + * pointer in place there (ops/idxop.c, and the layout note in + * rayforce.h), and ray_index_release_saved is a no-op. So the ref + * taken when that pool or domain was attached is still this + * vector's to drop, exactly as for an unindexed one. */ if (v->attrs & RAY_ATTR_HAS_INDEX) { /* A mmap-resident index (mmod==1) is a PASSENGER in this column's file * mapping — the column's single munmap frees it. Releasing it here @@ -890,11 +890,20 @@ static void ray_release_owned_refs(ray_t* v) { * heap-built index (mmod==0) is released by pointer. */ if (v->index && !RAY_IS_ERR(v->index) && v->index->mmod != 1) ray_release(v->index); - return; + /* Fall through to the STR / SYM arms below rather than repeating + * them: the pool or domain is still at bytes 8-15 either way, and a + * second copy of this dispatch is the drift this whole change is + * about. */ } - if (v->type == RAY_STR && v->str_pool && !RAY_IS_ERR(v->str_pool)) + if (v->type == RAY_STR && v->str_pool && !RAY_IS_ERR(v->str_pool)) { + /* Return rather than fall through, the way the SYM arm below does: + * a mapped column's pool owns the region they share, so this + * release can be the one that unmaps the page `v` sits on. None + * of the checks after this one apply to a STR vec anyway. */ ray_release(v->str_pool); + return; + } /* RAY_SYM vec: drop the resolution-domain ref (aux bytes 8-15). * No-op for the immortal runtime singleton — the common case. */ @@ -1002,10 +1011,14 @@ bool ray_retain_owned_refs(ray_t* v) { if (v->attrs & RAY_ATTR_HAS_INDEX) { /* Mirror ray_release_owned_refs: a mmap-resident passenger index - * (mmod==1) is owned by the column's mapping, not refcounted here. */ + * (mmod==1) is owned by the column's mapping, not refcounted here, + * and the pool or domain at bytes 8-15 is this copy's to take a + * ref on — skipping it is what let a copy that later sheds its + * index release a reference it never held. */ if (v->index && !RAY_IS_ERR(v->index) && v->index->mmod != 1) ray_retain(v->index); - return true; + /* Falls through to the STR / SYM arms below — see the mirror of + * this comment in ray_release_owned_refs. */ } if (v->type == RAY_STR && v->str_pool && !RAY_IS_ERR(v->str_pool)) @@ -1440,25 +1453,23 @@ ray_t* ray_alloc(size_t data_size) { * to find a genuinely non-empty freelist. */ uint64_t candidates = h->avail & (UINT64_MAX << order); - if (RAY_UNLIKELY(candidates == 0)) { - heap_flush_foreign(h, false); /* always local in ray_alloc */ - - candidates = h->avail & (UINT64_MAX << order); - - if (candidates == 0) { - if (!heap_add_pool(h, order)) return NULL; - candidates = h->avail & (UINT64_MAX << order); - if (candidates == 0) return NULL; - } - } - /* Scan past stale avail bits (cross-heap fl_remove may have emptied lists) */ uint8_t found_order; for (;;) { - if (candidates == 0) { - if (!heap_add_pool(h, order)) return NULL; + if (RAY_UNLIKELY(candidates == 0)) { + /* Out of blocks at this order. Take back everything other + * threads have freed to us BEFORE asking the OS for another + * pool: those blocks are already ours, and mapping fresh memory + * while our own sits on the list is how a repeated query grew a + * server by a pool per execution (issue #439). This ordering is + * the invariant — no pool is ever added without a drain first. */ + heap_drain_foreign(h); candidates = h->avail & (UINT64_MAX << order); - if (candidates == 0) return NULL; + if (candidates == 0) { + if (!heap_add_pool(h, order)) return NULL; + candidates = h->avail & (UINT64_MAX << order); + if (candidates == 0) return NULL; + } } found_order = (uint8_t)__builtin_ctzll(candidates); if (!fl_empty(&h->freelist[found_order])) break; @@ -1501,6 +1512,77 @@ ray_t* ray_alloc(size_t data_size) { * ray_free * -------------------------------------------------------------------------- */ +/* Drop one reference to a shared file mapping; the last one unmaps it. + * + * Not atomic: every reference is taken and dropped while building or + * freeing a block, both of which already run under the owning heap's + * single-threaded discipline. If a mapped column ever becomes shareable + * across heaps this needs the same treatment as ray_t's own rc. */ +/* Live shared mappings, keyed by base address. + * + * A block inside the region has to reach its own reference without going + * through a pointer somebody may swap: the pool keeps the descriptor in its + * header, but the column's only link to it would be str_pool, and that is + * exactly what str_pool_cow replaces when a mapped column is mutated. What + * never changes is the column's address, and the column header IS the start + * of the mapping — so the column looks its reference up by that. + * + * Touched once when a column is mapped and once when it is freed, never per + * query, so a spin lock over a small bucket array is enough. The + * descriptors are their own chain nodes. */ +#define RAY_FMAP_BUCKETS 256 +static ray_file_map_t* g_fmap[RAY_FMAP_BUCKETS]; +static _Atomic(int) g_fmap_lock = 0; + +static inline void fmap_lock(void) { + while (atomic_exchange_explicit(&g_fmap_lock, 1, memory_order_acquire)) + RAY_CPU_RELAX(); +} +static inline void fmap_unlock(void) { + atomic_store_explicit(&g_fmap_lock, 0, memory_order_release); +} +/* Bucket by the LOW bits of the page number, deliberately. The kernel + * hands out consecutive file mappings a few pages apart, so those bits are + * what actually varies between columns — measured over forty mapped string + * columns, forty distinct buckets and no chain longer than one. Hashing + * the high bits instead would put every column of a table in one chain. */ +static inline size_t fmap_bucket(const void* base) { + return ((uintptr_t)base >> 12) & (RAY_FMAP_BUCKETS - 1); +} + +void ray_file_map_register(const void* base, ray_file_map_t* m) { + if (!m) return; + size_t b = fmap_bucket(base); + fmap_lock(); + m->next = g_fmap[b]; + g_fmap[b] = m; + fmap_unlock(); +} + +ray_file_map_t* ray_file_map_lookup(const void* base) { + size_t b = fmap_bucket(base); + fmap_lock(); + ray_file_map_t* m = g_fmap[b]; + while (m && m->base != base) m = m->next; + fmap_unlock(); + return m; +} + +void ray_file_map_release(ray_file_map_t* m) { + if (!m) return; + if (ray_atomic_dec(&m->rc) > 1) return; /* returns the value BEFORE */ + /* Unlink if it was ever registered; a mapping nobody mutated never + * entered the table and the walk simply finds nothing. */ + size_t b = fmap_bucket(m->base); + fmap_lock(); + ray_file_map_t** pp = &g_fmap[b]; + while (*pp && *pp != m) pp = &(*pp)->next; + if (*pp) *pp = m->next; + fmap_unlock(); + ray_vm_unmap_file(m->base, m->len); + ray_sys_free(m); +} + void ray_free(ray_t* v) { if (!v || RAY_IS_ERR(v)) return; if (v->attrs & RAY_ATTR_ARENA) return; /* arena-owned, bulk-freed */ @@ -1512,13 +1594,52 @@ void ray_free(ray_t* v) { * won't merge this block prematurely (it checks buddy_rc==0). */ ray_atomic_store(&v->rc, 1); + /* A mapped block owning a shared region takes its descriptor now: aux + * lives inside the region it describes. */ + ray_file_map_t* owned_map = (v->mmod == 3) ? v->file_map : NULL; + + /* A mapped string column reaches its own reference through its pool, + * which is the cheap path and needs no lock — but only while that + * pointer still leads to the mapped pool. Read it before the children + * go, since releasing the pool may be what drops it. */ + ray_file_map_t* col_map = NULL; + if (v->mmod == 1 && v->type == RAY_STR && + v->str_pool && !RAY_IS_ERR(v->str_pool) && v->str_pool->mmod == 3) + col_map = v->str_pool->file_map; + ray_release_owned_refs(v); ray_heap_t* h = ray_tl_heap; + if (owned_map) { + ray_file_map_release(owned_map); + if (h) RAY_STAT(h->stats.free_count++); + return; + } + /* File-mapped: munmap */ if (v->mmod == 1) { if (v->type == RAY_TABLE || v->type == RAY_DICT || v->type == RAY_LIST) return; + /* A column mapped by the store registered its region and holds one + * of its references. Looking that up by address rather than through + * str_pool is the point: a mutated column's pool pointer no longer + * leads anywhere useful, while its address is what the region was + * registered under. The descriptor also carries the true mapped + * length, so nothing has to re-derive it from a header that the + * children release may already have taken away. */ + /* col_map is the answer whenever the pool pointer still led to the + * region, which is every column that was not mutated. Only one + * that had its pool swapped — str_pool_cow deep-copies a mapped + * pool before appending — has to ask the registry, and only a + * string column was ever registered. So the lock stays off the + * ordinary free entirely, and a mutated column pays it once. */ + ray_file_map_t* m = col_map; + if (!m && v->type == RAY_STR) m = ray_file_map_lookup(v); + if (m) { + ray_file_map_release(m); + if (h) RAY_STAT(h->stats.free_count++); + return; + } if (v->type > 0 && v->type < RAY_TYPE_COUNT) { uint8_t esz = ray_sym_elem_size(v->type, v->attrs); size_t data_size = 32 + (size_t)v->len * esz; @@ -1640,12 +1761,41 @@ void ray_free(ray_t* v) { return; } - /* Foreign: not in any of our pools. Enqueue to the foreign list for - * return to the owner during GC. Do NOT adjust bytes_allocated: the - * block stays counted on the owning heap until returned and coalesced. */ + /* Foreign: not in any of our pools. Push it onto the OWNER's list, not + * ours. A block parked here is memory only the owner can reuse, and + * until this changed nothing but an explicit ray_heap_gc() ever moved it + * — so a server that never called one had every worker start each query + * short by the volume the consuming thread was sitting on, and map a + * fresh pool to make up the difference, forever (issue #439). Handing + * the block back at free time makes the growth impossible instead of + * merely collectable. + * + * The registry lookup is unlocked, which is sound because a registered + * heap outlives every block it owns: threads abandon their heaps rather + * than destroying them (ray_heap_abandon). + * + * Do NOT adjust bytes_allocated: the block stays counted on the owning + * heap until IT drains and coalesces. */ + ray_pool_hdr_t* phdr = ray_pool_of(v); + if (RAY_UNLIKELY(!phdr)) return; /* not inside any live pool */ + uint16_t owner_id = phdr->heap_id; + ray_heap_t* owner = ray_heap_registry[owner_id % RAY_HEAP_REGISTRY_SIZE]; + /* Not in the registry. Either the owner was destroyed — its pools went + * with it and the mapping is gone — or it is merely waiting to be merged + * (ray_heap_push_pending unregisters first, while the pools stay mapped). + * The two are indistinguishable from here, so keep the block on our own + * list: the drain coalesces it against its own pool header and adopts it. + * Dropping it instead would strand the block and pin its pool against + * reclamation for the life of the process. */ + if (RAY_UNLIKELY(!owner || owner->id != owner_id)) owner = h; + dfd_add(v); - v->fl_next = h->foreign; - h->foreign = v; + ray_t* head = atomic_load_explicit(&owner->foreign, memory_order_relaxed); + do { + v->fl_next = head; + } while (!atomic_compare_exchange_weak_explicit( + &owner->foreign, &head, v, + memory_order_release, memory_order_relaxed)); RAY_STAT(h->stats.free_count++); } @@ -1837,9 +1987,28 @@ void ray_mem_stats(ray_mem_stats_t* out) { * -------------------------------------------------------------------------- */ +/* Heaps whose thread exited: still registered, pools intact, waiting for the + * next thread to adopt them. Guarded by the registry lock — pushed and + * popped once per thread lifetime, never on an allocation path. */ +static ray_heap_t* g_heap_idle = NULL; + void ray_heap_init(void) { if (ray_tl_heap) return; + /* Adopt an abandoned heap before mapping a new one. Its pools are + * already faulted in and its slab caches are warm, and — the reason this + * exists at all — a heap that is never destroyed can be looked up on the + * lock-free cross-thread free path without racing a munmap. */ + ray_registry_lock(); + ray_heap_t* reuse = g_heap_idle; + if (reuse) g_heap_idle = reuse->idle_next; + ray_registry_unlock(); + if (reuse) { + reuse->idle_next = NULL; + ray_tl_heap = reuse; + return; + } + size_t heap_sz = (sizeof(ray_heap_t) + 4095) & ~(size_t)4095; ray_heap_t* h = (ray_heap_t*)ray_vm_alloc(heap_sz); /* A silent return here leaves ray_tl_heap NULL, so every later @@ -1864,8 +2033,8 @@ void ray_heap_init(void) { } h->id = (uint16_t)id; - /* Register in global heap registry (lock: a concurrent destroyer may be - * walking the array in its foreign-purge loop). */ + /* Register in global heap registry (lock: serialize the slot write + * against a concurrent register / unregister). */ ray_registry_lock(); ray_heap_registry[h->id % RAY_HEAP_REGISTRY_SIZE] = h; ray_registry_unlock(); @@ -1922,6 +2091,34 @@ void ray_heap_init(void) { * heap takes over. Lives in src/lang/eval.c. */ extern void ray_clear_error_trace(void); +void ray_heap_abandon(void) { + ray_heap_t* h = ray_tl_heap; + if (!h) return; + + /* Thread-local refs into this heap must go before another thread owns + * it, or the next ray_eval_str on the adopting thread would release a + * trace this thread already handed on. */ + ray_clear_error_trace(); + + /* Take back whatever was freed to us while we ran, so the heap is + * handed on with its memory on its freelists rather than on a list the + * adopter has to notice. */ + heap_drain_foreign(h); + + ray_registry_lock(); + h->idle_next = g_heap_idle; + g_heap_idle = h; + ray_registry_unlock(); + + ray_tl_heap = NULL; +} + +/* Real teardown: unregisters the heap and munmaps its pools. + * + * ONLY valid when no other thread can still be freeing blocks that belong to + * this heap — process shutdown after the worker pool is joined, or a + * single-threaded test. A thread that merely exits must call + * ray_heap_abandon instead; see the comment on that function. */ void ray_heap_destroy(void) { ray_heap_t* h = ray_tl_heap; if (!h) return; @@ -1940,51 +2137,24 @@ void ray_heap_destroy(void) { uint16_t saved_id = h->id; - /* Workers tear down CONCURRENTLY during ray_pool_free() (all woken by the - * same shutdown signal), so the unregister + the cross-heap foreign-list - * purge below must be serialized: otherwise two destroyers splice the same - * neighbour's ->foreign list at once and the ->fl_next walk SEGVs. Held - * only across the registry critical section, released before munmap. */ + /* Unregister first so a free that is still to resolve an owner cannot + * pick this heap up. The lock serializes the slot write against + * ray_heap_init / ray_heap_abandon. + * + * The cross-heap foreign-list purge that used to live here is gone with + * the design it belonged to: a block of h's can no longer be sitting on + * some OTHER heap's foreign list, because a cross-thread free routes the + * block to its owner. With it goes the tearing hazard of walking a + * neighbour's singly-linked list while its owner mutates it. */ ray_registry_lock(); - - /* Unregister from global heap registry */ ray_heap_registry[h->id % RAY_HEAP_REGISTRY_SIZE] = NULL; + ray_registry_unlock(); - /* Skip flush_slabs and flush_foreign — all pools are about to be - * munmap'd. Flushing would coalesce blocks and fl_remove buddies - * from other heaps' freelists, which races with concurrent worker - * destruction during ray_pool_free(). */ - - /* Purge any of h's blocks from every other heap's foreign list - * BEFORE we munmap. Without this, foreign lists outlive h with - * dangling pointers into unmapped memory and crash on the next - * ray_heap_gc has_foreign walk or heap_flush_foreign. */ - for (int fh_id = 0; fh_id < RAY_HEAP_REGISTRY_SIZE; fh_id++) { - ray_heap_t* fh_heap = ray_heap_registry[fh_id]; - if (!fh_heap || fh_heap == h) continue; - ray_t** pp = &fh_heap->foreign; - ray_t* curr = *pp; - while (curr) { - ray_t* next = curr->fl_next; - bool in_h = false; - for (uint32_t i = 0; i < h->pool_count; i++) { - uintptr_t pb = (uintptr_t)h->pools[i].base; - uintptr_t pe = pb + BSIZEOF(h->pools[i].pool_order); - if ((uintptr_t)curr >= pb && (uintptr_t)curr < pe) { - in_h = true; - break; - } - } - if (in_h) { - *pp = next; - } else { - pp = &curr->fl_next; - } - curr = next; - } - } + /* Anything queued for us dies with the pools it lives in — the blocks are + * free memory inside mappings we are about to drop. */ + atomic_store_explicit(&h->foreign, NULL, memory_order_relaxed); - ray_registry_unlock(); + /* Skip flush_slabs — all pools are about to be munmap'd. */ /* Munmap all tracked pools. File-backed pools also need their fd * closed and their tempfile unlinked so the swap directory doesn't @@ -2014,58 +2184,11 @@ void ray_heap_destroy(void) { heap_id_release(saved_id); } -/* -------------------------------------------------------------------------- - * Return worker-pool blocks from this heap's freelists to their owners. - * - * After ray_alloc flushes foreign blocks locally (coalesce + madvise), - * worker-pool blocks sit on main's freelists with released physical pages. - * This function walks the freelists, finds blocks whose pool header - * heap_id != ours, removes them, and inserts into the owning worker heap. - * Workers can then reuse their pools without allocating new ones. - * - * ONLY safe when workers are idle (on semaphore, ray_parallel_flag == 0). - * -------------------------------------------------------------------------- */ - -static void heap_return_foreign_freelist(ray_heap_t* h) { - /* avail bit (set on insert, cleared on remove) tells us which - * freelist orders have any blocks at all — skip the empty ones. */ - if (!h->avail) return; - for (int order = RAY_ORDER_MIN; order < RAY_HEAP_FL_SIZE; order++) { - if (!(h->avail & (1ULL << order))) continue; - ray_fl_head_t* head = &h->freelist[order]; - ray_t* blk = head->fl_next; - while (blk != (ray_t*)head) { - ray_t* next = blk->fl_next; - /* Use heap_find_pool on h first — if found, block is local */ - int pidx = heap_find_pool(h, blk); - if (pidx < 0) { - /* Foreign block — find owner via pool header (GC path) */ - ray_pool_hdr_t* phdr = ray_pool_of(blk); - if (!phdr) { blk = next; continue; } - ray_heap_t* owner = ray_heap_registry[phdr->heap_id % RAY_HEAP_REGISTRY_SIZE]; - if (owner && owner->id == phdr->heap_id) { - fl_remove(blk); - dfd_remove(blk); - if (fl_empty(head)) - h->avail &= ~(1ULL << order); - /* Coalesce on owner for defragmentation */ - int opidx = heap_find_pool(owner, blk); - uintptr_t pb; - uint8_t po; - if (opidx >= 0) { - pb = (uintptr_t)owner->pools[opidx].base; - po = owner->pools[opidx].pool_order; - } else { - pb = (uintptr_t)phdr; - po = phdr->pool_order; - } - heap_coalesce(owner, blk, pb, po); - } - } - blk = next; - } - } -} +/* heap_return_foreign_freelist used to walk this heap's freelists looking for + * blocks that belong to somebody else and hand them back. Nothing can put + * such a block there any more — a cross-thread free goes straight to the + * owner's list, and a drain only ever coalesces the draining heap's own + * blocks — so the whole pass is gone. */ #ifdef DEBUG static void dfd_validate_freelists(void) { @@ -2095,6 +2218,16 @@ static void dfd_validate_freelists(void) { } #endif +/* Number of maintenance visits a free block must survive on a freelist + * before pass 5 hands its pages back; a block whose attrs exceed it has + * already been released and must not be released again. File scope + * because the idle decay below shares the marker. */ +#define RAY_FREE_AGE_RELEASE 3 +/* Below this order a block has no whole page to give back once its first + * page — which carries the freelist links — is kept, so every release walk + * starts here. */ +#define RAY_RELEASE_MIN_ORDER 13 + void ray_heap_gc(void) { ray_heap_t* h = ray_tl_heap; if (!h) return; @@ -2104,24 +2237,24 @@ void ray_heap_gc(void) { bool safe = (atomic_load_explicit(&ray_parallel_flag, memory_order_relaxed) == 0); - /* Pass 1: Flush main heap's foreign blocks and slab caches. - * When safe (workers idle), return foreign blocks to their owners - * so worker pools become reusable. */ - heap_flush_foreign(h, safe); + /* Pass 1: take back whatever other threads freed to us, and fold the + * slab caches back into the freelists. The drain needs no idle-worker + * gate: the list holds only our own blocks. */ + heap_drain_foreign(h); heap_flush_slabs(h); if (safe) { - /* Pass 2: Return foreign blocks absorbed onto our freelists - * back to their owning worker heaps. */ - heap_return_foreign_freelist(h); - - /* Pass 3: Skip worker heaps — we cannot safely touch their - * foreign lists or slab caches because workers may still be - * between pending-- and sem_wait, calling ray_free which - * modifies wh->foreign and wh->slabs. Workers flush their - * own foreign/slabs on their next dispatch entry. - * TODO: full cross-heap reclamation requires a worker - * quiescence barrier. */ + /* Pass 2 (return foreign blocks absorbed onto our freelists) is gone + * — nothing absorbs a foreign block locally any more. + * + * Pass 3: Skip worker heaps. Not for safety — ray_parallel_end + * drains `pending` with acquire before clearing the flag, and a + * worker allocates nothing between its last pending-- and sem_wait, + * which is what lets the decay sweep below walk those very heaps. + * It is a policy choice: folding a worker's slab cache back costs + * it a freelist pop and a split on its next allocation of that + * order, and the collection runs far more often than the caches + * are worth reclaiming. */ /* Pass 4: Reclaim OVERSIZED empty pools. * Standard pools (pool_order == RAY_HEAP_POOL_ORDER) are never @@ -2138,17 +2271,14 @@ void ray_heap_gc(void) { * live_count operations on the alloc/free hot path. */ /* Pass 4: Reclaim oversized empty pools. * - * For each candidate pool (owned by heap gh), count free bytes from: - * (a) gh's own freelist + slab cache — safe, only gh modifies these - * (b) ALL heaps' foreign lists (read-only) — foreign lists are - * prepend-only during the race window, so a read-only walk - * sees a consistent suffix. A concurrent prepend may be - * missed, making us undercount — which is conservative. - * - * On removal, only unlink from gh's freelist/slabs. Blocks still - * in other heaps' foreign lists will be discovered as dangling on - * their next flush (foreign block with unmapped pool → ray_pool_of - * returns NULL → skipped by the NULL guard). */ + * Emptiness is "every byte of the pool is on gh's own freelist or in + * its slab cache". That single sum is now the whole test: a block of + * gh's that is live, or queued on gh->foreign, or queued anywhere + * else, is by construction NOT on those two structures, so it shows + * up as a shortfall. The registry-wide foreign scan (and the + * destructive purge that had to follow it, because the scan raced) + * existed only because a free used to leave the block on whichever + * heap did the freeing. */ for (int hid = 0; hid < RAY_HEAP_REGISTRY_SIZE; hid++) { ray_heap_t* gh = ray_heap_registry[hid]; if (!gh) continue; @@ -2187,38 +2317,13 @@ void ray_heap_gc(void) { } } - /* (b) Check if ANY blocks from this pool are still in other - * heaps' foreign lists. If so, we cannot munmap — - * those blocks are threaded into the foreign list and - * dereferencing them after munmap would crash. - * They'll be flushed to the owner on the next GC. */ - /* Lock the foreign-list scan + purge: keeps the registry-wide - * foreign-splice invariant uniform with ray_heap_destroy. - * Workers are idle here (ray_parallel_flag == 0), so this is - * defensive — never contended in the live GC path. */ - ray_registry_lock(); - bool has_foreign = false; - for (int fh_id = 0; fh_id < RAY_HEAP_REGISTRY_SIZE && !has_foreign; fh_id++) { - ray_heap_t* fh_heap = ray_heap_registry[fh_id]; - if (!fh_heap || fh_heap == gh) continue; - ray_t* fb = fh_heap->foreign; - while (fb) { - if ((uintptr_t)fb >= pb && (uintptr_t)fb < pe) { - has_foreign = true; - break; - } - fb = fb->fl_next; - } - } - - if (free_bytes < pool_capacity || has_foreign) { - ray_registry_unlock(); + if (free_bytes < pool_capacity) { p++; - continue; /* pool has live allocations or dangling foreign refs */ + continue; /* pool still has live or queued blocks */ } - /* Pool is empty and no foreign-list refs — safe to munmap. - * Remove blocks from owning heap's freelists and slab caches. */ + /* Pool is entirely free — safe to munmap. Remove its blocks + * from the owning heap's freelists and slab caches. */ for (int ord = RAY_ORDER_MIN; ord < RAY_HEAP_FL_SIZE; ord++) { ray_fl_head_t* fh = &gh->freelist[ord]; ray_t* blk = fh->fl_next; @@ -2246,29 +2351,6 @@ void ray_heap_gc(void) { gh->slabs[si].count = dst; } - /* Purge any [pb, pe) blocks from every other heap's foreign - * list BEFORE munmap. The has_foreign check above is racy - * vs concurrent ray_free, and any block left here becomes - * a dangling pointer that crashes subsequent Pass 4 walks - * at fb->fl_next. Reading fl_next is safe here because - * the pool is still mapped. */ - for (int fh_id = 0; fh_id < RAY_HEAP_REGISTRY_SIZE; fh_id++) { - ray_heap_t* fh_heap = ray_heap_registry[fh_id]; - if (!fh_heap || fh_heap == gh) continue; - ray_t** pp = &fh_heap->foreign; - ray_t* curr = *pp; - while (curr) { - ray_t* next = curr->fl_next; - if ((uintptr_t)curr >= pb && (uintptr_t)curr < pe) { - *pp = next; - } else { - pp = &curr->fl_next; - } - curr = next; - } - } - ray_registry_unlock(); - dfd_purge_range(pb, pe); ray_vm_free(phdr->vm_base, BSIZEOF(po)); /* File-backed pools also need their fd closed and tempfile @@ -2321,11 +2403,10 @@ void ray_heap_gc(void) { * full cycle instead of being double-aged; the cursor never * stores a block pointer — blocks may be reallocated, split or * coalesced between passes, only (heap, order) is stable. */ - #define RAY_FREE_AGE_RELEASE 3 #define RAY_P5_VISIT_BUDGET 2048 #define RAY_P5_RELEASE_BUDGET 64 static int s_p5_hid = 0; - static int s_p5_ord = 13; + static int s_p5_ord = RAY_RELEASE_MIN_ORDER; uint64_t large_orders_mask = ~((1ULL << 13) - 1); int64_t p5_visited = 0, p5_released = 0; int p5_slots = RAY_HEAP_REGISTRY_SIZE * (RAY_HEAP_FL_SIZE - 13); @@ -2335,7 +2416,7 @@ void ray_heap_gc(void) { int hid = s_p5_hid; int ord = s_p5_ord; if (++s_p5_ord >= RAY_HEAP_FL_SIZE) { - s_p5_ord = 13; + s_p5_ord = RAY_RELEASE_MIN_ORDER; s_p5_hid = (s_p5_hid + 1) % RAY_HEAP_REGISTRY_SIZE; } ray_heap_t* gh = ray_heap_registry[hid]; @@ -2362,25 +2443,162 @@ void ray_heap_gc(void) { } +/* Hand back the pages of every free block of `h` at or above the release + * floor that has not already been released, and report how many. The three + * callers differ only in which heaps they visit and what they do first; + * the walk itself is this. */ +static int64_t heap_release_free_pages(ray_heap_t* h) { + int64_t released = 0; + for (int ord = RAY_RELEASE_MIN_ORDER; ord < RAY_HEAP_FL_SIZE; ord++) { + if (!(h->avail & (1ULL << ord))) continue; + ray_fl_head_t* head = &h->freelist[ord]; + for (ray_t* blk = head->fl_next; blk != (ray_t*)head; + blk = blk->fl_next) { + if (blk->attrs > RAY_FREE_AGE_RELEASE) continue; /* released */ + int pidx = heap_find_pool(h, blk); + bool hp = (pidx >= 0) ? (h->pools[pidx].hugepage != 0) : false; + ray_vm_release_block(blk, BSIZEOF(ord), hp); + blk->attrs = RAY_FREE_AGE_RELEASE + 1; + released++; + } + } + return released; +} + void ray_heap_release_pages(void) { /* Explicit release: callers asking for pages back get them NOW — * no aging — but still skip blocks already released. */ ray_heap_t* h = ray_tl_heap; if (!h) return; - for (int i = 13; i < RAY_HEAP_FL_SIZE; i++) { - ray_fl_head_t* head = &h->freelist[i]; - ray_t* blk = head->fl_next; - while (blk != (ray_t*)head) { - if (blk->attrs <= RAY_FREE_AGE_RELEASE) { - size_t bsize = BSIZEOF(i); - int rpidx = heap_find_pool(h, blk); - bool hp = (rpidx >= 0) ? (h->pools[rpidx].hugepage != 0) : false; - ray_vm_release_block(blk, bsize, hp); - blk->attrs = RAY_FREE_AGE_RELEASE + 1; - } - blk = blk->fl_next; - } + (void)heap_release_free_pages(h); +} + +/* -------------------------------------------------------------------------- + * Idle decay + * + * A free block keeps its physical pages so the next allocation of that size + * reuses them without faulting; that is why pass 5 ages a block before + * releasing it, and why a repeated query never pays to refault its own + * temporaries. The price of the policy is that a process which ran one + * heavy query holds its peak footprint for the rest of its life even while + * it does nothing. The memory is free and reusable — it is simply not + * available to anything else on the machine. + * + * The decay closes that gap with no background thread, no queue and no task + * object. Work stamps a coarse timestamp when it STARTS, and the two points + * that already exist at the end of a unit of work — the statement boundary + * and the event loop between wakeups — compare that stamp against a + * threshold. If the process has been quiet longer than the threshold, one + * un-aged sweep releases the pages of every free block in every heap; + * otherwise the check is a relaxed load and a subtraction. + * + * The threshold is the whole point: it is what separates "the workload has + * stopped" from "we are between two iterations of a hot loop". Releasing in + * the second case drops exactly the pages the next iteration refaults, which + * is why pass 5 ages blocks in the first place. + * + * The stamp is taken at the END of a unit of work, and the boundary check + * reads the clock BEFORE the new stamp. What it measures is therefore the + * gap between one unit finishing and the next — the time the process + * actually sat idle. Stamping at the start would measure the unit's own + * duration instead, so a loop of units longer than the threshold would + * sweep after every one of them, discarding the working set the next is + * about to fault back in. + * + * The sweep works on EVERY registered heap, not just the caller's, and it + * drains each one's foreign list and slab cache before walking its + * freelists. That is not incidental: in a server the main thread frees the + * results of a parallel query, so the blocks land on the owning WORKER's + * foreign list, and a worker only drains its own list when it next needs + * memory — which a warm heap never does. Freelist-only, the sweep sees a + * small fraction of the free bytes; with the drain it sees nearly all of + * them. Draining also coalesces, so the pages come back in large runs + * instead of scattered blocks below the order-13 floor. + * + * That is sound only because the sweep runs when ray_parallel_flag is 0. + * The dispatcher clears the flag only after every worker's `pending--` is + * visible, and a worker between `pending--` and sem_wait claims tasks and + * waits — it neither allocates nor frees — so no other thread is touching + * a worker heap's freelists or slab stack. A concurrent cross-thread free + * can still PUSH onto a foreign list at any moment, and that is safe on its + * own terms: the drain takes the whole list with one atomic exchange, and + * whatever arrives afterwards is simply left for the next sweep. + * + * Unlike ray_heap_gc's pass 5 this walk has no visit or release budget. + * The budget exists there because gc runs inside a workload and must never + * become an unpredictable pause; the decay by construction only runs when + * there is no workload to pause. + * + * The armed flag makes this once per idle period. After a sweep there is + * nothing further to give back until new work dirties memory again, so a + * long-idle process stops checking altogether and its event loop returns to + * blocking indefinitely instead of waking on a timer. + * -------------------------------------------------------------------------- */ + +#define RAY_HEAP_DECAY_MS_DEFAULT 10000 +#define RAY_HEAP_DECAY_MS_MAX ((int64_t)7 * 24 * 3600 * 1000) + +static _Atomic int64_t g_heap_activity_ms; +static _Atomic bool g_heap_decay_armed; + +/* Read per check rather than cached at first use. This is policy, not a + * hot-path constant — it is consulted once per statement and once per event + * loop wakeup — and caching it would make the value depend on which code + * path happened to run first in the process. */ +/* The policy, not a knob: there is no environment override. Negative + * disables the decay; the clamp keeps `activity + threshold` from wrapping, + * and a week is already "never". The setter exists so a test can drive the + * policy — an operator-facing override, if one is ever wanted, belongs on an + * existing surface rather than here. */ +static int64_t g_heap_decay_ms = RAY_HEAP_DECAY_MS_DEFAULT; + +void ray_heap_set_decay_ms(int64_t ms) { + if (ms > RAY_HEAP_DECAY_MS_MAX) ms = RAY_HEAP_DECAY_MS_MAX; + g_heap_decay_ms = (ms < 0) ? -1 : ms; +} + +static int64_t heap_decay_threshold_ms(void) { + return g_heap_decay_ms; +} + +void ray_heap_note_activity(void) { + atomic_store_explicit(&g_heap_activity_ms, ray_time_now_ms(), + memory_order_relaxed); + atomic_store_explicit(&g_heap_decay_armed, true, memory_order_relaxed); +} + +int64_t ray_heap_decay_due_ms(void) { + if (!atomic_load_explicit(&g_heap_decay_armed, memory_order_relaxed)) + return -1; + int64_t threshold = heap_decay_threshold_ms(); + if (threshold < 0) return -1; /* decay disabled */ + int64_t due = atomic_load_explicit(&g_heap_activity_ms, + memory_order_relaxed) + + threshold - ray_time_now_ms(); + return due > 0 ? due : 0; +} + +int64_t ray_heap_decay(void) { + if (ray_heap_decay_due_ms() != 0) return -1; + if (atomic_load_explicit(&ray_parallel_flag, memory_order_relaxed) != 0) + return -1; + + /* Disarm before sweeping: what follows is everything this idle period + * can return, so repeating it before work resumes finds nothing. */ + atomic_store_explicit(&g_heap_decay_armed, false, memory_order_relaxed); + + int64_t released = 0; + for (int hid = 0; hid < RAY_HEAP_REGISTRY_SIZE; hid++) { + ray_heap_t* gh = ray_heap_registry[hid]; + if (!gh) continue; + /* Blocks freed to gh by another thread, and gh's own slab cache, + * are not on a freelist and would be invisible to the walk below — + * in a server that is where most of the free bytes are. */ + heap_drain_foreign(gh); + heap_flush_slabs(gh); + released += heap_release_free_pages(gh); } + return released; } void ray_heap_merge(ray_heap_t* src) { @@ -2421,8 +2639,10 @@ void ray_heap_merge(ray_heap_t* src) { } } - /* Free foreign blocks via coalescing */ - ray_t* fblk = src->foreign; + /* Blocks other threads freed back to src, taken over by dst along with + * src's pools. */ + ray_t* fblk = atomic_exchange_explicit(&src->foreign, NULL, + memory_order_acquire); while (fblk) { ray_t* next = fblk->fl_next; int pidx = heap_find_pool(dst, fblk); @@ -2437,10 +2657,14 @@ void ray_heap_merge(ray_heap_t* src) { pb = (uintptr_t)phdr; po = phdr->pool_order; } + /* dst inherited src's bytes_allocated above, and these blocks are + * still charged in it — they were freed to their owner but never + * drained. Coalescing them without this leaves the charge standing + * for good, so .sys.mem drifts up by every merged pending block. */ + RAY_STAT(dst->stats.bytes_allocated -= BSIZEOF(fblk->order)); heap_coalesce(dst, fblk, pb, po); fblk = next; } - src->foreign = NULL; /* Merge freelists: circular list splice (src chain into dst chain) */ for (int i = RAY_ORDER_MIN; i < RAY_HEAP_FL_SIZE; i++) { @@ -2496,9 +2720,9 @@ void ray_heap_merge(ray_heap_t* src) { void ray_heap_flush_foreign(void) { ray_heap_t* h = ray_tl_heap; if (!h) return; - bool safe = (atomic_load_explicit(&ray_parallel_flag, - memory_order_relaxed) == 0); - heap_flush_foreign(h, safe); + /* No ray_parallel_flag gate: the list holds only this heap's own blocks, + * and only this thread coalesces into its own freelists. */ + heap_drain_foreign(h); } /* -------------------------------------------------------------------------- @@ -2563,7 +2787,15 @@ void* ray_scratch_arena_push(ray_scratch_arena_t* a, size_t nbytes) { if (!blk) return NULL; a->backing[a->n_backing++] = blk; a->ptr = (char*)ray_data(blk); - a->end = (char*)blk + BSIZEOF(blk->order); + /* The window ends at the block's real capacity. `order` describes the + * block size only for buddy blocks: a request at or above + * RAY_HEAP_POOL_ORDER comes back as a DIRECT block, mapped at its exact + * page-rounded size and tagged with the RAY_ORDER_DIRECT sentinel. + * Reading that sentinel as an order claims a 2^39-byte block, and every + * push after the one that triggered it is then bump-allocated past the + * end of the mapping — a write straight into unmapped address space. + * ray_block_data_bytes covers both block kinds. */ + a->end = a->ptr + ray_block_data_bytes(blk); bump:; void* ret = a->ptr; diff --git a/src/mem/heap.h b/src/mem/heap.h index 0e82b4026..26a88d3f4 100644 --- a/src/mem/heap.h +++ b/src/mem/heap.h @@ -91,6 +91,15 @@ * Checked by HNSW builtins before dereferencing. User must (hnsw-free h). */ #define RAY_ATTR_HNSW 0x04 +/* I64 atom carries an owning dl_program_t* (a Datalog program) in its .i64 + * slot. Checked by the dl-* builtins before dereferencing, so a forged/plain + * integer or an arithmetic copy (which drops attrs) is rejected with a type + * error instead of being reinterpreted as a pointer — see dl_unwrap_program. + * Reuses 0x20 (RAY_ATTR_SORTED on vectors / ATTR_QUOTED on -RAY_SYM); the + * -RAY_I64 type tag disambiguates, and no free-path or generic check reads + * 0x20 on a -RAY_I64 atom. User must (dl-free h). */ +#define RAY_ATTR_DLPROG 0x20 + /* Vector is a linked column. The 8 bytes of the aux union at offset * 8 (i.e. parent->_idx_pad / parent->slice_offset / parent->str_pool * slot, depending on which arm is in use) hold an int64 @@ -156,6 +165,41 @@ typedef struct { uint64_t peak_live_bytes; } ray_mem_trace_t; +/* One file mapping that more than one block lives in. + * + * A splayed string column and its pool are written contiguously and mapped + * together, so the region cannot end when either one of them does: a + * selection may hold the pool after the column it was gathered from is + * gone. The descriptor lives on the heap rather than inside the mapping — + * it has to outlive it to unmap it — and the pool holds it (mmod 3) while + * the column merely references the pool. + * + * Kept off the buddy heap (ray_sys_alloc) so a block being freed can drop + * the last reference without re-entering the allocator it is inside. */ +typedef struct ray_file_map_s { + void* base; /* what to hand back to ray_vm_unmap_file */ + size_t len; + /* Blocks still living in the region. Both of them take one at map + * time — the column as well as the pool — so a path that swaps the + * column's pool pointer (str_pool_cow deep-copies a mapped pool + * before mutating it) drops the pool's reference without pulling the + * region out from under the column that is mid-mutation. + * + * Atomic because a column and a result sharing its pool can be freed + * on different threads. */ + uint32_t rc; + struct ray_file_map_s* next; /* chain within its registry bucket */ +} ray_file_map_t; + +/* Make a mapping findable by the address it was mapped at. Only needed + * once a block inside it loses its own route to the descriptor — see + * str_pool_cow — so the table holds mutated mapped columns only. */ +void ray_file_map_register(const void* base, ray_file_map_t* m); +/* The mapping that starts at `base`, or NULL. A mapped column's header is + * the start of its region, so a column passes itself. */ +ray_file_map_t* ray_file_map_lookup(const void* base); +void ray_file_map_release(ray_file_map_t* m); + /* ===== Forward Declarations (internal types) ===== */ typedef struct ray_heap ray_heap_t; @@ -168,6 +212,17 @@ typedef struct ray_dispatch ray_dispatch_t; void ray_heap_init(void); void ray_heap_destroy(void); +/* Detach the calling thread from its heap WITHOUT tearing the heap down: + * the heap stays registered with its pools intact and is handed to the next + * thread that calls ray_heap_init(). + * + * This is what a thread that exits must use. A cross-thread free resolves + * the owning heap through ray_heap_registry and pushes the block onto it + * without taking a lock — that lookup is only sound while every registered + * heap outlives the blocks it owns, so a thread may never unregister and + * munmap a heap that another thread might still be freeing into. + * ray_heap_destroy remains the real teardown, for process shutdown. */ +void ray_heap_abandon(void); void ray_heap_merge(ray_heap_t* src); void ray_heap_flush_foreign(void); void ray_heap_push_pending(ray_heap_t* heap); @@ -180,6 +235,37 @@ void ray_mem_trace_end(ray_mem_trace_t* out); void ray_heap_gc(void); void ray_heap_release_pages(void); +/* ===== Idle decay ===== + * + * Free blocks keep their pages so the next query reuses them without + * faulting. That makes a process hold its peak footprint forever, which + * costs nothing to the process and everything to whatever shares the + * machine with it. The decay gives those pages back once the process has + * been quiet for longer than a threshold, without a background thread: + * work stamps a timestamp, maintenance points compare it. + * + * ray_heap_note_activity — stamp; call at the START of a unit of work (a + * statement, an IPC request). A stamp at the end would zero the elapsed + * time seen by the boundary check that immediately follows it. + * ray_heap_decay_due_ms — ms until a sweep is due, 0 if due now, -1 if + * none is pending (nothing to release, or decay disabled). An event loop + * uses it to bound a wait it would otherwise make indefinite. + * ray_heap_decay — sweep if due and if the worker pool is + * quiescent; returns the number of blocks released, or -1 if it did + * nothing. Safe to call from any maintenance point. + * + * The threshold is fixed policy, reachable only through + * ray_heap_set_decay_ms: negative disables the decay, 0 releases at the + * next maintenance point after any work. */ +void ray_heap_note_activity(void); +int64_t ray_heap_decay_due_ms(void); +int64_t ray_heap_decay(void); + +/* Set the threshold directly; negative disables. The environment is read + * once on first use, so this exists to let a test drive the policy without + * re-exec — not as a runtime knob. */ +void ray_heap_set_decay_ms(int64_t ms); + /* -------------------------------------------------------------------------- * Constants * -------------------------------------------------------------------------- */ @@ -425,7 +511,17 @@ typedef struct { typedef struct ray_heap { uint64_t avail; /* bitmask: bit N set = freelist[N] non-empty */ uint16_t id; /* heap identity (for cross-thread free) */ - ray_t* foreign; /* cross-heap freed blocks (lock-free LIFO via fl_next) */ + /* Blocks of THIS heap freed by another thread, waiting to be taken back. + * A cross-thread free pushes onto the OWNER's list (CAS), and the owner + * drains it with one atomic_exchange on its allocation slow path — so a + * block always returns to the heap that has to reuse it, with no + * collector in the loop. Atomic because any thread may push while the + * owner drains. */ + /* Remote CAS target: every cross-thread free of a block this heap owns + * writes it. On its own line so those writes do not bounce the line + * carrying `avail` and the slab heads, which the owner touches on every + * allocation. */ + _Alignas(64) _Atomic(ray_t*) foreign; ray_slab_t slabs[RAY_SLAB_ORDERS]; /* small-block slab caches */ uint32_t slab_cap[RAY_SLAB_ORDERS]; /* runtime push cap per slab order (byte-budgeted) */ ray_fl_head_t freelist[RAY_HEAP_FL_SIZE]; /* circular sentinel per order */ @@ -434,6 +530,7 @@ typedef struct ray_heap { uint32_t last_pool_idx; /* MRU pool index for warm-first ray_free */ ray_pool_entry_t pools[RAY_MAX_POOLS]; /* pool tracking for destroy/merge */ struct ray_heap* pending_next; /* link for pending-merge LIFO queue */ + struct ray_heap* idle_next; /* link for the abandoned-heap LIFO */ char swap_path[256]; /* dir for file-backed pool fallback (RAY_HEAP_SWAP env, default "./") */ } ray_heap_t; diff --git a/src/ops/agg.c b/src/ops/agg.c index 6c42d299e..ab342bf8d 100644 --- a/src/ops/agg.c +++ b/src/ops/agg.c @@ -127,7 +127,15 @@ static ray_t* agg_atom_i64_for_type(int8_t t, int64_t v) { static ray_t* agg_parted_sum(ray_t* x) { int8_t base = (int8_t)RAY_PARTED_BASETYPE(x->type); - if (!agg_parted_numeric_base(base) || base == RAY_DATE) + /* Explicit runtime whitelist: numeric + duration-like TIME. NOT + * agg_type_admitted() — that is a permissive *plan-time* guard which only + * rejects the types it KNOWS are bad and admits unknown wrappers (incl. + * RAY_LIST); as the final runtime gate it would let a parted LIST column + * fall into the integer loop and silently sum to 0. DATE/TIMESTAMP are + * absolute points and are rejected here too, matching flat sum (which + * rejects them via agg_type_admitted); the parted path previously summed a + * TIMESTAMP column instead. */ + if (!agg_parted_numeric_base(base) || base == RAY_DATE || base == RAY_TIMESTAMP) return ray_error("type", "sum expects a numeric or time-duration parted column, got %s", ray_type_name(base)); ray_t** segs = (ray_t**)ray_data(x); if (base == RAY_F64 || base == RAY_F32) { @@ -150,10 +158,9 @@ static ray_t* agg_parted_sum(ray_t* x) { if (!seg) continue; int has_nulls = (seg->attrs & RAY_ATTR_HAS_NULLS) != 0; for (int64_t i = 0; i < seg->len; i++) - if (!has_nulls || !ray_vec_is_null(seg, i)) sum += agg_read_i64(seg, i); + if (!has_nulls || !ray_vec_is_null(seg, i)) sum = wrap_add_i64(sum, agg_read_i64(seg, i)); } if (base == RAY_TIME) return ray_time(sum); - if (base == RAY_TIMESTAMP) return ray_timestamp(sum); return make_i64(sum); } @@ -214,7 +221,7 @@ static ray_t* agg_parted_prod(ray_t* x) { int has_nulls = (seg->attrs & RAY_ATTR_HAS_NULLS) != 0; for (int64_t i = 0; i < seg->len; i++) { if (has_nulls && ray_vec_is_null(seg, i)) continue; - prod = (int64_t)((uint64_t)prod * (uint64_t)agg_read_i64(seg, i)); + prod = wrap_mul_i64(prod, agg_read_i64(seg, i)); } } return make_i64(prod); @@ -411,37 +418,36 @@ ray_t* ray_sum_fn(ray_t* x) { * absolute points and SYM/STR/GUID are non-numeric → type error. */ if (!agg_type_admitted(OP_SUM, x->type)) return ray_error("type", "sum expects a numeric or time-duration vector, got %s", ray_type_name(x->type)); /* Narrow/temporal types need specific return constructors that the - * DAG executor doesn't provide — use scalar path for these. */ + * DAG executor doesn't provide — use scalar path for these. TIMESTAMP + * is rejected by agg_type_admitted() above, so only the duration-like + * TIME and the narrow integer widths reach here. Accumulation wraps + * via wrap_add_i64 to stay UB-free (overflow needs a multi-GiB column + * for the narrow types, but the wrap keeps the whole family uniform). */ if (x->type == RAY_I32 || x->type == RAY_I16 || x->type == RAY_U8 || - x->type == RAY_TIME || x->type == RAY_TIMESTAMP) { + x->type == RAY_TIME) { int64_t n = x->len; bool has_nulls = (x->attrs & RAY_ATTR_HAS_NULLS) != 0; int64_t sum = 0; if (x->type == RAY_I32) { int32_t* d = (int32_t*)ray_data(x); - if (has_nulls) { for (int64_t i = 0; i < n; i++) if (!ray_vec_is_null(x, i)) sum += d[i]; } - else { for (int64_t i = 0; i < n; i++) sum += d[i]; } + if (has_nulls) { for (int64_t i = 0; i < n; i++) if (!ray_vec_is_null(x, i)) sum = wrap_add_i64(sum, d[i]); } + else { for (int64_t i = 0; i < n; i++) sum = wrap_add_i64(sum, d[i]); } return make_i64(sum); } else if (x->type == RAY_I16) { int16_t* d = (int16_t*)ray_data(x); - if (has_nulls) { for (int64_t i = 0; i < n; i++) if (!ray_vec_is_null(x, i)) sum += d[i]; } - else { for (int64_t i = 0; i < n; i++) sum += d[i]; } + if (has_nulls) { for (int64_t i = 0; i < n; i++) if (!ray_vec_is_null(x, i)) sum = wrap_add_i64(sum, d[i]); } + else { for (int64_t i = 0; i < n; i++) sum = wrap_add_i64(sum, d[i]); } return make_i64(sum); } else if (x->type == RAY_U8) { uint8_t* d = (uint8_t*)ray_data(x); - if (has_nulls) { for (int64_t i = 0; i < n; i++) if (!ray_vec_is_null(x, i)) sum += d[i]; } - else { for (int64_t i = 0; i < n; i++) sum += d[i]; } + if (has_nulls) { for (int64_t i = 0; i < n; i++) if (!ray_vec_is_null(x, i)) sum = wrap_add_i64(sum, d[i]); } + else { for (int64_t i = 0; i < n; i++) sum = wrap_add_i64(sum, d[i]); } return make_i64(sum); - } else if (x->type == RAY_TIME) { + } else { int32_t* d = (int32_t*)ray_data(x); - if (has_nulls) { for (int64_t i = 0; i < n; i++) if (!ray_vec_is_null(x, i)) sum += d[i]; } - else { for (int64_t i = 0; i < n; i++) sum += d[i]; } + if (has_nulls) { for (int64_t i = 0; i < n; i++) if (!ray_vec_is_null(x, i)) sum = wrap_add_i64(sum, d[i]); } + else { for (int64_t i = 0; i < n; i++) sum = wrap_add_i64(sum, d[i]); } return ray_time(sum); - } else { - int64_t* d = (int64_t*)ray_data(x); - if (has_nulls) { for (int64_t i = 0; i < n; i++) if (!ray_vec_is_null(x, i)) sum += d[i]; } - else { for (int64_t i = 0; i < n; i++) sum += d[i]; } - return ray_timestamp(sum); } } /* I64/F64: parallel morsel-driven reduction via DAG executor */ @@ -461,8 +467,14 @@ ray_t* ray_sum_fn(ray_t* x) { continue; } if (elems[i]->type == -RAY_F64 || elems[i]->type == -RAY_F32) { has_float = 1; fsum += elems[i]->f64; } - else if (elems[i]->type == -RAY_I64) { isum += elems[i]->i64; fsum += (double)elems[i]->i64; } - else { int64_t v = (int64_t)as_f64(elems[i]); isum += v; fsum += (double)v; } + else { + /* i64 atoms are read directly (exact above 2^53); other integer / + * temporal atoms via as_f64. Wrap-accumulate: signed overflow is + * UB, and the typed-vector path already wraps. */ + int64_t v = (elems[i]->type == -RAY_I64) ? elems[i]->i64 : (int64_t)as_f64(elems[i]); + isum = wrap_add_i64(isum, v); + fsum += (double)v; + } } return has_float ? make_f64(fsum) : make_i64(isum); } @@ -494,8 +506,11 @@ ray_t* ray_prod_fn(ray_t* x) { has_float = 1; fprod *= elems[i]->f64; } else { - int64_t v = (int64_t)as_f64(elems[i]); - iprod = (int64_t)((uint64_t)iprod * (uint64_t)v); + /* Read i64 directly: (int64_t)as_f64(atom) both loses precision + * above 2^53 and is UB when the value rounds to >= 2^63. Wrap- + * multiply keeps overflow well-defined. */ + int64_t v = (elems[i]->type == -RAY_I64) ? elems[i]->i64 : (int64_t)as_f64(elems[i]); + iprod = wrap_mul_i64(iprod, v); fprod *= (double)v; } } diff --git a/src/ops/builtins.c b/src/ops/builtins.c index c2d4f82d2..8fba4b22a 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -25,6 +25,7 @@ */ #include +#include #include "lang/eval.h" #include "lang/internal.h" #include "lang/env.h" @@ -79,8 +80,8 @@ static const char* null_literal_str(int8_t type) { case RAY_DATE: return "0Nd"; case RAY_TIME: return "0Nt"; case RAY_TIMESTAMP: return "0Np"; - /* SYM has no null literal: empty symbol is a value, never reaches - * here — callers gate on RAY_ATOM_IS_NULL, always false for SYM. */ + /* SYM/STR use their empty literal as the canonical null spelling; + * callers keep them on their ordinary formatting paths. */ default: return "null"; } } @@ -100,10 +101,9 @@ void ray_lang_print(FILE* fp, ray_t* val) { return; } if (!val || RAY_IS_ERR(val)) { fprintf(fp, "error"); return; } - /* STR has no distinct null — empty and null strings are the same - * value and print as empty content (handled by the -RAY_STR case), - * not a null literal. */ - if (val->type != -RAY_STR && RAY_ATOM_IS_NULL(val)) { + /* STR/SYM use their empty literals as canonical null spellings. */ + if (val->type != -RAY_STR && val->type != -RAY_SYM && + RAY_ATOM_IS_NULL(val)) { fprintf(fp, "%s", null_literal_str(val->type)); return; } @@ -198,7 +198,8 @@ static char* fmt_interpolate(const char* fmt, size_t flen, ray_t** args, int64_t int tlen = 0; if (!a || RAY_IS_ERR(a)) { tlen = snprintf(tmp, sizeof(tmp), "error"); - } else if (a->type != -RAY_STR && RAY_ATOM_IS_NULL(a)) { + } else if (a->type != -RAY_STR && a->type != -RAY_SYM && + RAY_ATOM_IS_NULL(a)) { tlen = snprintf(tmp, sizeof(tmp), "%s", null_literal_str(a->type)); } else if (a->type == -RAY_I64) { tlen = snprintf(tmp, sizeof(tmp), "%ld", (long)a->i64); @@ -684,8 +685,10 @@ ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n) { /* The streaming writer emits raw columns; append chunk-zone indexes to the * just-written files, then reload so the returned table carries them - * (mmap'd in place). Without this, an on-disk column would lack the - * block-skip an in-memory .csv.read column has. */ + * (mmap'd in place). Conversion is the ONLY place a CSV load decides an + * index: `.csv.read` returns an index-free in-memory table, and callers + * that want one on it ask explicitly (.idx.hash / the attrs verbs). + * Without this pass, a converted store would have no block-skip at all. */ ray_t* tbl = ray_read_splayed(dir, sym); if (tbl && !RAY_IS_ERR(tbl) && tbl->type == RAY_TABLE) { ray_splay_build_indexes(dir, tbl); @@ -1200,6 +1203,14 @@ static void cast_mark_output_sentinels(ray_t* vec, int8_t out_type, int64_t n) { if (d[i] == NULL_I64) { vec->attrs |= RAY_ATTR_HAS_NULLS; return; } return; } + case RAY_SYM: + for (int64_t i = 0; i < n; i++) { + if (ray_read_sym(out, i, RAY_SYM, vec->attrs) == 0) { + vec->attrs |= RAY_ATTR_HAS_NULLS; + return; + } + } + return; default: return; } } @@ -1350,6 +1361,13 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { return ray_error("domain", "as: cannot parse str as i64, unexpected trailing characters"); if (errno == ERANGE) return ray_error("domain", "as: cannot parse str as i64, value out of int64 range"); + /* INT64_MIN is NULL_I64: a non-null i64 cannot hold it, so reject + * rather than silently returning 0Nl. The string->vector cast + * (cast_vec_numeric) routes each element through here too, so + * vectors reject it consistently — string ingest is loud, unlike + * numeric narrowing which nulls the sentinel (see as.rfl). */ + if (v == NULL_I64) + return ray_error("domain", "as: cannot parse str as i64, value is the i64 null sentinel"); return make_i64(v); } /* Vector/list cast */ @@ -1371,12 +1389,21 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_STR) { const char* sp = ray_str_ptr(val); char* end; errno = 0; - long v = strtol(sp, &end, 10); + int64_t v = strtoll(sp, &end, 10); if (end == sp) return ray_error("domain", "as: cannot parse str as i32"); if (*end != '\0') return ray_error("domain", "as: cannot parse str as i32, unexpected trailing characters"); if (errno == ERANGE) return ray_error("domain", "as: cannot parse str as i32, value out of int64 range"); + if (v < INT32_MIN || v > INT32_MAX) + return ray_error("domain", "as: cannot parse str as i32, value out of i32 range"); + /* INT32_MIN is NULL_I32: a non-null i32 cannot hold it, so reject + * rather than silently returning 0Ni. The string->vector cast + * (cast_vec_numeric) routes each element through here too, so + * vectors reject it consistently — string ingest is loud, unlike + * numeric narrowing which nulls the sentinel (see as.rfl). */ + if ((int32_t)v == NULL_I32) + return ray_error("domain", "as: cannot parse str as i32, value is the i32 null sentinel"); return ray_i32((int32_t)v); } /* Vector cast */ @@ -1398,12 +1425,21 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_STR) { const char* sp = ray_str_ptr(val); char* end; errno = 0; - long v = strtol(sp, &end, 10); + int64_t v = strtoll(sp, &end, 10); if (end == sp) return ray_error("domain", "as: cannot parse str as i16"); if (*end != '\0') return ray_error("domain", "as: cannot parse str as i16, unexpected trailing characters"); if (errno == ERANGE) return ray_error("domain", "as: cannot parse str as i16, value out of int64 range"); + if (v < INT16_MIN || v > INT16_MAX) + return ray_error("domain", "as: cannot parse str as i16, value out of i16 range"); + /* INT16_MIN is NULL_I16: a non-null i16 cannot hold it, so reject + * rather than silently returning 0Nh. The string->vector cast + * (cast_vec_numeric) routes each element through here too, so + * vectors reject it consistently — string ingest is loud, unlike + * numeric narrowing which nulls the sentinel (see as.rfl). */ + if ((int16_t)v == NULL_I16) + return ray_error("domain", "as: cannot parse str as i16, value is the i16 null sentinel"); return ray_i16((int16_t)v); } /* Vector cast */ @@ -1920,12 +1956,14 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_STR) { const char* sp = ray_str_ptr(val); char* end; errno = 0; - long v = strtol(sp, &end, 10); + int64_t v = strtoll(sp, &end, 10); if (end == sp) return ray_error("domain", "as: cannot parse str as u8"); if (*end != '\0') return ray_error("domain", "as: cannot parse str as u8, unexpected trailing characters"); if (errno == ERANGE) return ray_error("domain", "as: cannot parse str as u8, value out of int64 range"); + if (v < 0 || v > UINT8_MAX) + return ray_error("domain", "as: cannot parse str as u8, value out of u8 range"); return ray_u8((uint8_t)v); } /* Vector cast */ diff --git a/src/ops/collection.c b/src/ops/collection.c index c25c45f96..c7248a21e 100644 --- a/src/ops/collection.c +++ b/src/ops/collection.c @@ -1224,6 +1224,30 @@ ray_t* ray_distinct_fn(ray_t* x) { ray_t* ray_in_fn(ray_t* val, ray_t* vec) { if (ray_is_lazy(val)) val = ray_lazy_materialize(val); if (ray_is_lazy(vec)) vec = ray_lazy_materialize(vec); + /* Parted columns store segment pointers where vector paths expect flat + * cells. Flatten both operands before membership; distinct uses the same + * helper, while except/sect still reject parted input. */ + ray_t* flat_val = NULL; + ray_t* flat_vec = NULL; + if (val && RAY_IS_PARTED(val->type)) { + flat_val = parted_to_flat_vec(val); + if (!flat_val || RAY_IS_ERR(flat_val)) return flat_val ? flat_val : ray_error("oom", NULL); + val = flat_val; + } + if (vec && RAY_IS_PARTED(vec->type)) { + flat_vec = parted_to_flat_vec(vec); + if (!flat_vec || RAY_IS_ERR(flat_vec)) { + if (flat_val) ray_release(flat_val); + return flat_vec ? flat_vec : ray_error("oom", NULL); + } + vec = flat_vec; + } + if (flat_val || flat_vec) { + ray_t* r = ray_in_fn(val, vec); + if (flat_val) ray_release(flat_val); + if (flat_vec) ray_release(flat_vec); + return r; + } /* STR in STR: for each char of val, check membership in vec string */ if (ray_is_atom(val) && (-val->type) == RAY_STR && ray_is_atom(vec) && (-vec->type) == RAY_STR) { const char* vp = ray_str_ptr(val); @@ -1629,7 +1653,7 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { * floats up front: as_i64(f64) reads the bit pattern and would cause * e.g. (take 1.0 2.0) to attempt a 4.6-quintillion-element allocation * and surface as "oom" — misleading for what is really a type error. */ - if (ray_is_atom(n_obj) && n_obj->type == -RAY_F64) + if (ray_is_atom(n_obj) && (n_obj->type == -RAY_F64 || n_obj->type == -RAY_F32)) return ray_error("type", "take: count must be an integer, got %s", ray_type_name(n_obj->type)); /* Range take: (take collection [start amount]) — slice from start for amount elements */ if (ray_is_vec(n_obj) && n_obj->type == RAY_I64 && ray_len(n_obj) == 2) { @@ -1662,8 +1686,9 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { if (start < 0) start = slen + start; if (start < 0) start = 0; if (start >= slen) return ray_str("", 0); - int64_t end = start + amount; - if (end > slen) end = slen; + /* amount can be up to INT64_MAX, so `start + amount` overflows; + * take min(amount, slen - start) instead (0 <= start < slen). */ + int64_t end = (amount < slen - start) ? start + amount : slen; return ray_str(s + start, (size_t)(end - start)); } @@ -1680,8 +1705,9 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { col_propagate_str_pool(empty, vec); return empty; } - int64_t end = start + amount; - if (end > len) end = len; + /* Overflow-safe clamp: amount may be up to INT64_MAX, so avoid + * computing start+amount unless it is known to fit (0 <= start < len). */ + int64_t end = (amount < len - start) ? start + amount : len; int64_t count = end - start; int8_t vtype = vec->type; int esz = ray_sym_elem_size(vtype, vec->attrs); @@ -1716,8 +1742,9 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { int64_t len = keys ? keys->len : 0; if (start < 0) start = len + start; if (start < 0) start = 0; - int64_t end = start + amount; - if (end > len) end = len; + /* Overflow-safe clamp (amount up to INT64_MAX); keep the end=len. */ + int64_t end = (amount < len - start) ? start + amount : len; if (end < start) end = start; int64_t count = end - start; @@ -1754,8 +1781,7 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { result->len = 0; return result; } - int64_t end = start + amount; - if (end > len) end = len; + int64_t end = (amount < len - start) ? start + amount : len; int64_t count = end - start; ray_t** elems = (ray_t**)ray_data(vec); ray_t* result = ray_alloc(count * sizeof(ray_t*)); @@ -1773,11 +1799,13 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { return ray_error("type", "take: range take unsupported for %s", ray_type_name(vec->type)); } /* Every scalar-count branch below turns the count into a magnitude with - * `n < 0 ? -n : n`; `-INT64_MIN` is signed-overflow UB and |INT64_MIN| is - * unallocatable anyway, so reject an INT64_MIN count (also the i64 null - * sentinel) once here, up front, for all of them. */ - if (ray_is_atom(n_obj) && is_numeric(n_obj) && as_i64(n_obj) == INT64_MIN) - return ray_error("range", "take: count magnitude out of range"); + * `n < 0 ? -n : n`, and `-INT64_MIN` is signed-overflow UB. INT64_MIN is + * also the i64 null sentinel (0N), so reject it once here as a type error + * — symmetric with drop and the window verbs — rather than letting a null + * count through. Float counts are already rejected above, so is_numeric + * here only admits integer atoms (and implies ray_is_atom). */ + if (is_numeric(n_obj) && as_i64(n_obj) == INT64_MIN) + return ray_error("type", "take: count is null or out of range"); /* Char take: (take 'a' n) → string of n copies of char */ if (ray_is_atom(vec) && vec->type == -RAY_STR && ray_str_len(vec) == 1 && ray_is_atom(n_obj) && is_numeric(n_obj)) { int64_t n = as_i64(n_obj); @@ -2015,16 +2043,18 @@ ray_t* ray_drop_fn(ray_t* vec, ray_t* n_obj) { return ray_error("type", "drop: expected a collection, got %s", vec ? ray_type_name(vec->type) : "null"); int64_t n = as_i64(n_obj); + /* INT64_MIN is the i64 null sentinel (0N) and `-INT64_MIN` is signed- + * overflow UB; reject it as a type error, symmetric with take, rather + * than silently dropping the whole collection. */ + if (n == INT64_MIN) + return ray_error("type", "drop: count is null or out of range"); int64_t start = 0; int64_t amount = len; if (n >= 0) { start = n < len ? n : len; amount = len - start; } else { - /* `-INT64_MIN` is signed-overflow UB; a drop-from-end of that - * magnitude removes the whole collection (|n| >= len), so treat it as - * cut == len (amount 0) rather than negating. */ - int64_t cut = (n == INT64_MIN) ? len : -n; + int64_t cut = -n; /* n != INT64_MIN here, so negation is safe */ amount = cut < len ? len - cut : 0; } return collection_slice(vec, start, amount); diff --git a/src/ops/datalog.c b/src/ops/datalog.c index d9db9bade..243e1e973 100644 --- a/src/ops/datalog.c +++ b/src/ops/datalog.c @@ -4409,18 +4409,23 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { * Programmatic Datalog API builtins * ══════════════════════════════════════════ */ -/* Opaque handle for dl_program_t stored in a ray_t atom. - * We store the pointer in the i64 field. */ +/* Opaque handle for dl_program_t stored in a ray_t atom. The pointer lives + * in the i64 field, tagged with RAY_ATTR_DLPROG so dl_unwrap_program can reject + * a plain integer (or an arithmetic copy, which does not carry the attr) + * instead of dereferencing an arbitrary value as a dl_program_t*. Mirrors the + * RAY_ATTR_GRAPH / RAY_ATTR_HNSW handle scheme. */ static ray_t* dl_wrap_program(dl_program_t* prog) { ray_t* obj = ray_alloc(0); if (!obj || RAY_IS_ERR(obj)) return ray_error("oom", NULL); obj->type = -RAY_I64; obj->i64 = (int64_t)(uintptr_t)prog; + obj->attrs |= RAY_ATTR_DLPROG; return obj; } static dl_program_t* dl_unwrap_program(ray_t* obj) { - if (!obj || obj->type != -RAY_I64) return NULL; + if (!obj || obj->type != -RAY_I64 || !(obj->attrs & RAY_ATTR_DLPROG)) + return NULL; return (dl_program_t*)(uintptr_t)obj->i64; } @@ -4514,16 +4519,22 @@ ray_t* ray_dl_provenance_fn(ray_t* prog_obj, ray_t* pred_obj) { /* (dl-free prog) — free a dl-program handle created by (dl-program). * The handle wraps a raw dl_program_t* with no automatic finalizer, so * without an explicit free the program block and all relation tables it - * owns leak. Idempotent: zeroes the handle so a second call is a no-op - * (returns false) instead of double-freeing. */ + * owns leak. On free we clear RAY_ATTR_DLPROG and zero the pointer, so a + * second call is an idempotent no-op (returns false) rather than a + * double-free. A tagged pointer that isn't an i64 is a type error, and a + * plain/forged integer (RAY_ATTR_DLPROG absent, non-zero value) is rejected + * as a type error instead of being dereferenced as a dl_program_t*. */ ray_t* ray_dl_free_fn(ray_t* x) { if (!x || x->type != -RAY_I64) return ray_error("type", "dl-free: arg must be a dl-program"); - dl_program_t* prog = dl_unwrap_program(x); - if (!prog) return ray_bool(false); /* already freed / null handle */ - dl_program_free(prog); - x->i64 = 0; - return ray_bool(true); + if (x->attrs & RAY_ATTR_DLPROG) { + dl_program_free((dl_program_t*)(uintptr_t)x->i64); + x->attrs &= (uint8_t)~RAY_ATTR_DLPROG; + x->i64 = 0; + return ray_bool(true); + } + if (x->i64 == 0) return ray_bool(false); /* already-freed handle: idempotent */ + return ray_error("type", "dl-free: not a dl-program handle"); } /* Reset global Datalog rule storage (called from ray_lang_destroy) */ diff --git a/src/ops/exec.c b/src/ops/exec.c index 9035d1e0d..6326424db 100644 --- a/src/ops/exec.c +++ b/src/ops/exec.c @@ -680,7 +680,7 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, * Null rows emit 0 regardless of negate (isn masks after the OR). * Bit-identical to the generic loops below; additive, chosen once. */ /* SYM verdict-LUT fast path: one byte load per row, no set scan. - * SYM has no null, so there is no per-element null branch either. */ + * Canonical null is raw id 0 and is handled by the same LUT lookup. */ if (!c->col_is_atom && c->symlut && ct == RAY_SYM) { const uint8_t* lut = c->symlut; uint8_t neg = (uint8_t)negate; @@ -870,6 +870,12 @@ static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, if (RAY_IS_PARTED(st)) st = (int8_t)RAY_PARTED_BASETYPE(st); if (ct == RAY_STR || st == RAY_STR) return IN_CTX_UNSUPPORTED; + /* GUID cells are 16-byte blobs; the typed kernel's READ_I64/IN_READ_I64 + * loops have no guid case and read them at the wrong width (every cell + * decodes to 0, so membership silently matched everything). Bail so the + * caller routes to the guid-aware hashset path, mirroring how RAY_STR bails + * above and the guid == fix. */ + if (ct == RAY_GUID || st == RAY_GUID) return IN_CTX_UNSUPPORTED; /* Classify each side: 0=int-family, 1=float-family, 2=sym. */ #define CLASSIFY(t) \ @@ -1094,6 +1100,76 @@ ray_t* ray_in_vec_exec(ray_t* col, ray_t* set, bool negate) { return out; } +static ray_t* flatten_parted_col(ray_t* col); + +/* GUID membership fallback: the typed `in` kernel bails on guid operands + * (16-byte cells it can't compare), so route them through the general + * ray_in_fn path, which builds a guid-aware hashset. `col` is a materialized + * column vector, so ray_in_fn returns a fresh RAY_BOOL vector we own and may + * invert in place for not-in. */ +static ray_t* exec_in_guid_fallback(ray_t* col, ray_t* set, bool negate) { + ray_t* input = col; + bool owns_input = false; + if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) { + input = flatten_parted_col(col); + if (!input || RAY_IS_ERR(input)) return input ? input : ray_error("oom", NULL); + owns_input = true; + } + + ray_t* r = ray_in_fn(input, set); + if (!r || RAY_IS_ERR(r)) { + if (owns_input) ray_release(input); + return r; + } + + /* ray_in_fn returns a scalar for a scalar GUID subject. Normalize it to + * the vector contract of exec_in before applying not-in. */ + if (ray_is_atom(r) && r->type == -RAY_BOOL) { + ray_t* out = ray_vec_new(RAY_BOOL, 1); + if (!out || RAY_IS_ERR(out)) { + ray_release(r); + return out ? out : ray_error("oom", NULL); + } + out->len = 1; + ((uint8_t*)ray_data(out))[0] = r->b8; + ray_release(r); + r = out; + } + + if (r->type == RAY_BOOL) { + uint8_t* b = (uint8_t*)ray_data(r); + if (negate) + for (int64_t i = 0; i < r->len; i++) b[i] = (uint8_t)!b[i]; + + /* Mask after inversion: null rows must remain false for both IN and + * NOT_IN, while the underlying membership helper may match null. */ + if (ray_is_atom(col)) { + if (RAY_ATOM_IS_NULL(col)) b[0] = 0; + } else if (input->type == RAY_GUID) { + /* GUID nulls are all-zero cells; older table construction paths + * may omit HAS_NULLS even though the sentinel is present. */ + static const uint8_t null_guid[16] = {0}; + const uint8_t* data = (const uint8_t*)ray_data(input); + for (int64_t i = 0; i < r->len; i++) + if (memcmp(data + i * 16, null_guid, 16) == 0) b[i] = 0; + } else if (col->attrs & RAY_ATTR_HAS_NULLS) { + for (int64_t i = 0; i < r->len; i++) + if (ray_vec_is_null(input, i)) b[i] = 0; + } + } + if (owns_input) ray_release(input); + return r; +} + +/* True when either operand is a guid column/atom (parted base included). */ +static bool in_is_guid(ray_t* col, ray_t* set) { + int8_t ct = ray_is_atom(col) ? (int8_t)(-col->type) : col->type; + int8_t st = ray_is_atom(set) ? (int8_t)(-set->type) : set->type; + if (RAY_IS_PARTED(ct)) ct = (int8_t)RAY_PARTED_BASETYPE(ct); + if (RAY_IS_PARTED(st)) st = (int8_t)RAY_PARTED_BASETYPE(st); + return ct == RAY_GUID || st == RAY_GUID; +} + static ray_t* exec_in(ray_graph_t* g, ray_op_t* op, ray_t* col, ray_t* set) { (void)g; bool negate = (op->opcode == OP_NOT_IN); @@ -1122,8 +1198,11 @@ static ray_t* exec_in(ray_graph_t* g, ray_op_t* op, ray_t* col, ray_t* set) { in_ctx_status_t st = in_build_worker_ctx(col, set, negate, svf_stack, svi_stack, &in_ctx, &sv_hdr, &lut_hdr); - if (st == IN_CTX_UNSUPPORTED) + if (st == IN_CTX_UNSUPPORTED) { + if (in_is_guid(col, set)) + return exec_in_guid_fallback(col, set, negate); return ray_error("nyi", "OP_IN on RAY_STR not yet implemented"); + } if (st == IN_CTX_OOM) return ray_error("oom", NULL); @@ -3723,6 +3802,30 @@ static bool dag_can_stream(ray_graph_t* g, ray_op_t* root) { static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root); +/* Validate compiler-marked missing scans before execution. Optimizer rewrites + * may replace a root or eliminate such a scan from the live DAG (for example + * count/missing-column), but that must not turn an invalid reference into a + * result. Do not revalidate every OP_SCAN against g->table here: graph APIs + * legitimately scan derived columns produced by upstream operators. */ +static ray_t* validate_scan_columns(ray_graph_t* g) { + if (!g) return ray_error("nyi", NULL); + + for (uint32_t i = 0; i < g->node_count; i++) { + ray_op_t* op = &g->nodes[i]; + if (op->opcode != OP_SCAN || + !(op->flags & OP_FLAG_INVALID_SCAN)) continue; + + ray_op_ext_t* ext = find_ext(g, op->id); + if (!ext) return ray_error("schema", "scan metadata missing"); + ray_t* name = ray_sym_str(ext->sym); + if (name) + return ray_error("schema", "column '%.*s' not found", + (int)ray_str_len(name), ray_str_ptr(name)); + return ray_error("schema", "column not found"); + } + return NULL; +} + ray_t* ray_execute(ray_graph_t* g, ray_op_t* root) { /* The qstats capture mode is armed once per query at the eval boundary * (ray_eval, eval_depth==0) — covering PROF (profiler/query-log) AND the @@ -3735,6 +3838,8 @@ ray_t* ray_execute(ray_graph_t* g, ray_op_t* root) { /* Progress ends at the eval boundary (the true query end), not here — * a query can drive several ray_execute calls, and ending after each * would reset the elapsed clock and fire premature "final" ticks. */ + ray_t* scan_err = validate_scan_columns(g); + if (scan_err) return scan_err; return ray_execute_inner(g, root); } diff --git a/src/ops/expr.c b/src/ops/expr.c index b458aa936..7d2b6470c 100644 --- a/src/ops/expr.c +++ b/src/ops/expr.c @@ -549,7 +549,7 @@ bool ray_expr_disable; /* test knob: force the fallback path */ static void expr_stats_dump(void) { static const char* names[EXPR_BAIL__N] = { "root-shape", "graph-size", "depth", "regs", "ins", - "mapcommon", "str", "nulls", "slice", "sym-domain", + "mapcommon", "str", "guid", "nulls", "slice", "sym-domain", "const", "null-shape", "other", }; fprintf(stderr, "expr_compile ok=%llu\n", @@ -686,7 +686,27 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { ray_t* col = ray_table_get_col(tbl, ext->sym); if (!col) EXPR_BAIL(EXPR_BAIL_OTHER); if (col->type == RAY_MAPCOMMON) EXPR_BAIL(EXPR_BAIL_MAPCOMMON); - if (col->type == RAY_STR) EXPR_BAIL(EXPR_BAIL_STR); /* RAY_STR needs string comparison path */ + /* Bail on the ELEMENT type: a parted wrapper carries + * RAY_PARTED_BASE + base and would sail past checks on + * col->type — a parted GUID column then zero-filled + * every lane and matched everything. */ + int8_t elem = RAY_IS_PARTED(col->type) + ? (int8_t)RAY_PARTED_BASETYPE(col->type) + : col->type; + if (elem == RAY_STR) EXPR_BAIL(EXPR_BAIL_STR); /* RAY_STR needs string comparison path */ + /* GUID cells are 16-byte blobs the fused program has no + * loads or compares for — without this bail the compiled + * expression read garbage and predicates silently + * matched nothing. The unfused executor compares GUIDs + * correctly. */ + if (elem == RAY_GUID) EXPR_BAIL(EXPR_BAIL_GUID); + /* Whitelist of element types expr_load_i64/f64 decode. + * Anything else (RAY_LIST from a legacy STRL splayed + * load, nested columns, future types) hits the loaders' + * default arm, which zero-fills the lane buffer. */ + if (!((elem >= RAY_BOOL && elem <= RAY_TIMESTAMP) || + elem == RAY_SYM)) + EXPR_BAIL(EXPR_BAIL_OTHER); if (col->attrs & RAY_ATTR_SLICE) EXPR_BAIL(EXPR_BAIL_SLICE); /* Length-1 columns used as scalar broadcasts are handled by the * fallback's exec_elementwise_binary (which has vec/scalar routing). @@ -2441,6 +2461,22 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { if (!result || RAY_IS_ERR(result)) return result; result->len = len; + /* ISNULL is defined for every vector type, including the canonical + * empty/null STR and width-adaptive SYM representations. Handle it + * before numeric opcode dispatch so unsupported input types cannot leave + * the BOOL result buffer unwritten. */ + if (op->opcode == OP_ISNULL) { + uint8_t* dst = (uint8_t*)ray_data(result); + if (input->type != RAY_STR && input->type != RAY_SYM && + !vec_may_have_nulls(input)) { + memset(dst, 0, (size_t)len); + } else { + for (int64_t i = 0; i < len; i++) + dst[i] = ray_vec_is_null(input, i) ? 1 : 0; + } + return result; + } + /* Hoist in_type, out_type, and opcode dispatch entirely outside the * morsel loop so each inner loop is a tight, single-type kernel. * This allows autovectorisation and eliminates per-element branch predict slots. */ @@ -2663,17 +2699,7 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { out_off += n; } } else if (in_type == RAY_I64 && out_type == RAY_BOOL) { - if (opc == OP_ISNULL) { - /* ISNULL over a non-null vec: always false here; the - * null-propagation pass at the end of the function sets - * dst[i]=1 for null rows of the input. */ - while (ray_morsel_next(&m)) { - int64_t n = m.morsel_len; - uint8_t* dst = (uint8_t*)((char*)ray_data(result) + out_off); - for (int64_t i = 0; i < n; i++) dst[i] = 0; - out_off += n; - } - } else if (opc == OP_CAST) { + if (opc == OP_CAST) { /* (as 'BOOL i64_col) — truthy semantics; NULL_I64 = INT64_MIN * sentinel is non-zero but logically missing, so skip it. */ while (ray_morsel_next(&m)) { @@ -2818,18 +2844,10 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { } } - /* Propagate null bitmap from input to result. - * ISNULL is special: set output to 1 for null elements. */ - if (vec_may_have_nulls(input)) { - if (op->opcode == OP_ISNULL) { - for (int64_t i = 0; i < len; i++) { - if (ray_vec_is_null(input, i)) - ((uint8_t*)ray_data(result))[i] = 1; - } - } else { - propagate_nulls(input, result, len); - } - } + /* Propagate null bitmap from input to result. OP_ISNULL never reaches + * here — it is handled and returned before the typed dispatch above. */ + if (vec_may_have_nulls(input)) + propagate_nulls(input, result, len); /* OP_NEG/OP_ABS over i64: |INT64_MIN| and -INT64_MIN don't fit — surface * as typed null (by convention). Loop above used unsigned wrap, so @@ -3556,6 +3574,61 @@ ray_t* exec_elementwise_binary(ray_graph_t* g, ray_op_t* op, ray_t* lhs, ray_t* } } + /* GUID comparison: 16-byte cells, memcmp equality. Without this + * branch a guid predicate fell into the numeric loops, which read + * the cells at the wrong width and silently matched nothing. Only + * == and != are defined for guid operands here (cmp.c orders guid + * ATOMS, but a ranged guid predicate over a column has no use). */ + { + bool l_guid = (l_scalar ? (lhs->type == -RAY_GUID || lhs->type == RAY_GUID) + : lhs->type == RAY_GUID); + bool r_guid = (r_scalar ? (rhs->type == -RAY_GUID || rhs->type == RAY_GUID) + : rhs->type == RAY_GUID); + if (l_guid || r_guid) { + uint16_t opc = op->opcode; + if (!l_guid || !r_guid) { + ray_release(result); + return ray_error("type", "expr eval: cannot compare %s and %s", + ray_type_name(lhs->type), ray_type_name(rhs->type)); + } + if (opc != OP_EQ && opc != OP_NE) { + ray_release(result); + return ray_error("type", "expr eval: guid operands support only == and !="); + } + uint8_t* out = (uint8_t*)ray_data(result); + const uint8_t* lb = (lhs->type == -RAY_GUID) + ? (const uint8_t*)ray_data(lhs->obj) + : (const uint8_t*)ray_data(lhs); + const uint8_t* rb = (rhs->type == -RAY_GUID) + ? (const uint8_t*)ray_data(rhs->obj) + : (const uint8_t*)ray_data(rhs); + for (int64_t i = 0; i < len; i++) { + const uint8_t* lp = lb + (l_scalar ? 0 : i * 16); + const uint8_t* rp = rb + (r_scalar ? 0 : i * 16); + uint8_t eq = (memcmp(lp, rp, 16) == 0) ? 1 : 0; + out[i] = (opc == OP_EQ) ? eq : (uint8_t)!eq; + } + return result; + } + } + + /* Gate vector operands on the types the numeric loops can read. + * Anything else (RAY_LIST from a legacy STRL splayed load, nested + * shapes, future types) previously fell into read_col_* default + * arms, which read the cells at the wrong width and silently + * mismatched every row. */ + { + bool l_ok = l_scalar || (lhs->type >= RAY_BOOL && lhs->type <= RAY_TIMESTAMP) + || RAY_IS_SYM(lhs->type); + bool r_ok = r_scalar || (rhs->type >= RAY_BOOL && rhs->type <= RAY_TIMESTAMP) + || RAY_IS_SYM(rhs->type); + if (!l_ok || !r_ok) { + ray_release(result); + return ray_error("type", "expr eval: unsupported column type in binary op, got %s and %s", + ray_type_name(lhs->type), ray_type_name(rhs->type)); + } + } + /* Reject string atom in arithmetic context (only comparisons are valid). */ { bool l_atom_str = (l_scalar && lhs->type == -RAY_STR); diff --git a/src/ops/filter.c b/src/ops/filter.c index ce7153101..4b10aa14e 100644 --- a/src/ops/filter.c +++ b/src/ops/filter.c @@ -287,6 +287,13 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { if (!input || RAY_IS_ERR(input)) return input; if (!pred || RAY_IS_ERR(pred)) return pred; + /* An atom predicate (scalar subject in a where-clause) has no per-row + * bits. Reject it before any morsel walk: ray_morsel_init derives the + * element size from the type, and a negative (atom) type indexes + * ray_type_sizes out of bounds. */ + if (pred->type < 0) + return ray_error("length", "filter: predicate must be a BOOL vector matching the input length, got an atom"); + /* A plain contiguous BOOL predicate over a large input takes the * parallel chunked count/fill; anything else (lazy / morsel-backed * pred, small input) keeps the sequential morsel sweep. */ diff --git a/src/ops/fused_pred.c b/src/ops/fused_pred.c index f3f322370..0768de087 100644 --- a/src/ops/fused_pred.c +++ b/src/ops/fused_pred.c @@ -100,18 +100,49 @@ static int fp_atom_col_compatible(int8_t atom_type, int8_t col_type) { } /* Reject columns the fused per-row compare can't read safely. - * Currently: any column carrying nulls (RAY_ATTR_HAS_NULLS). - * The fused evaluator reads raw payload bytes — for nullable columns it - * would compare the sentinel value rather than treating the slot as - * null, producing a different result from the unfused null-aware - * compare kernel. Until fp_eval_cmp learns to skip nulls, gate fused - * off here at compile so the planner falls back transparently. */ -static int fp_col_supported(const ray_t* col) { + * + * The fused evaluator reads raw payload bytes. For a NUMERIC or TEMPORAL + * column the null is an OUT-OF-BAND SENTINEL (NULL_I64, NULL_I32, NaN, ...) + * that does not stand for any real value, so comparing it would answer a + * question about the sentinel rather than about the null — a different result + * from the unfused null-aware kernel. Those stay rejected. + * + * SYM and STR are different in kind: their null is an IN-BAND ORDINARY VALUE. + * A SYM null is id 0, which is a genuine dictionary entry — the empty string, + * held at position 0 of every symfile by construction (domain.c enforces the + * reservation on open). A STR null is a zero-length descriptor. Comparing + * those raw payloads for EQUALITY therefore gives exactly the answer the + * unfused kernel gives: `== ""` is true precisely on the null cells, `!= ""` + * false precisely on them. Nothing is being skipped or guessed. + * + * Deliberately limited to EQ/NE: + * - ORDERING (LT/LE/GT/GE) is NOT safe by this argument. The sort kernels + * treat nulls as a separate order class placed by the `nulls_first` flag + * (sort_cmp; the single-key path partitions them out and rotates), NOT by + * their payload — so "" sorting as the smallest string is not the ordering + * a null-aware comparison implies. (SYM ordering ops are rejected outright + * a few lines below in any case.) + * - LIKE is not safe either: bfb5b380 made the string kernels + * null-propagating (e.g. `strlen` of a null SYM/STR is NULL_I64), so a + * pattern match against the empty payload need not equal the null-aware + * answer. LIKE keeps the strict gate. + * + * This mattered the moment converted stores started carrying HAS_NULLS on SYM + * columns (#416): ClickBench q24/q25/q26 are `where: (!= SearchPhrase "")`, + * and losing the fused path cost them ~70x for an identical result. */ +static int fp_col_supported_op(const ray_t* col, int eq_or_ne) { if (!col) return 0; - if (col->attrs & RAY_ATTR_HAS_NULLS) return 0; + if (col->attrs & RAY_ATTR_HAS_NULLS) + return eq_or_ne && (col->type == RAY_SYM || col->type == RAY_STR); return 1; } +/* Strict form — no nullable column at all. Used by the shapes whose + * evaluator arm is not an equality compare (LIKE, IN). */ +static int fp_col_supported(const ray_t* col) { + return fp_col_supported_op(col, 0); +} + static int fp_expr_const_str(ray_t* expr) { if (!expr) return 0; if (expr->type == -RAY_STR && !(expr->attrs & ATTR_QUOTED)) return 1; @@ -178,7 +209,7 @@ static int fp_check_simple_cmp(ray_t* expr, ray_t* tbl) { && ct != RAY_I16 && ct != RAY_I32 && ct != RAY_I64 && ct != RAY_DATE && ct != RAY_TIME && ct != RAY_TIMESTAMP) return -1; - if (!fp_col_supported(col)) return -1; + if (!fp_col_supported_op(col, code == 0 || code == 1)) return -1; if (!is_dict_str && !fp_atom_col_compatible(rhs->type, ct)) return -1; } return code; @@ -791,7 +822,7 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, * its code once; absent ⇒ EQ all-false / NE all-true via fold. */ if (col->type == RAY_STR && (out->op == FP_EQ || out->op == FP_NE) && ray_index_kind(col) == RAY_IDX_DICT) { - if (!fp_col_supported(col)) return -1; + if (!fp_col_supported_op(col, 1)) return -1; ray_t* cv_str = rext->literal; if (!cv_str || cv_str->type != -RAY_STR) return -1; ray_index_t* dix = ray_index_payload(col->index); @@ -816,10 +847,10 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, if (col->type == RAY_SYM && (out->op == FP_LT || out->op == FP_LE || out->op == FP_GT || out->op == FP_GE)) return -1; - /* Reject nullable columns — fp_eval_cmp doesn't read the null bitmap, - * so a comparison against a stored sentinel slot would diverge from - * the unfused null-aware kernel. */ - if (!fp_col_supported(col)) return -1; + /* Nullable columns: only SYM/STR equality is safe — see + * fp_col_supported_op for why sentinels and in-band nulls differ. */ + if (!fp_col_supported_op(col, out->op == FP_EQ || out->op == FP_NE)) + return -1; ray_t* cv = rext->literal; /* Atom type ↔ column class compatibility — block mixed-temporal diff --git a/src/ops/fused_topk.c b/src/ops/fused_topk.c index 83ba8e90a..10dd0778c 100644 --- a/src/ops/fused_topk.c +++ b/src/ops/fused_topk.c @@ -73,10 +73,14 @@ typedef struct { uint8_t esz; uint8_t desc; /* 0 = asc, 1 = desc */ /* When the column carries nulls, fpk_cmp consults them before - * reading the raw payload and orders nulls LAST for ASC, FIRST for - * DESC — matching sort.c's default null policy. has_nulls is the - * compile-time flag that gates the per-row probe. */ + * reading the raw payload and places them at the end this flag + * names. It is filled from sort_nulls_first, the one place that + * says where a null goes, so this path and the ordinary sort agree: + * they must, since a parted top-k runs this path per partition and + * is checked against the flat sort. has_nulls is the compile-time + * flag that gates the per-row probe. */ uint8_t has_nulls; + uint8_t nulls_first; /* SYM keys only: 1 when the column's domain is the runtime * singleton — cell ids then index the borrowed global snapshot * (ctx.sym_strings). 0 routes the compare through the column's @@ -138,18 +142,16 @@ static inline int fpk_cmp(const fpk_par_ctx_t* c, int64_t row_a, int64_t row_b) for (uint32_t k = 0; k < c->n_keys; k++) { const fpk_keyspec_t* ks = &c->keys[k]; int cmp = 0; - /* Null-aware leg. Default policy matches sort.c: NULLS LAST - * for ASC, NULLS FIRST for DESC. In the max-heap-of-K-best - * comparator, "worse" → evicted first, so for ASC a null is - * worse than any non-null (so it goes last), and for DESC a - * null is better than any non-null (so it goes first). Both - * legs short-circuit before the raw payload read. */ + /* Null-aware leg. In the max-heap-of-K-best comparator, "worse" + * → evicted first, so a null asked for first is better than any + * non-null and a null asked for last is worse. Both legs + * short-circuit before the raw payload read. */ if (ks->has_nulls) { bool a_null = ray_vec_is_null(ks->col, row_a); bool b_null = ray_vec_is_null(ks->col, row_b); if (a_null && b_null) continue; /* tie on this key */ - if (a_null) return ks->desc ? -1 : 1; /* a is null */ - if (b_null) return ks->desc ? 1 : -1; + if (a_null) return ks->nulls_first ? -1 : 1; + if (b_null) return ks->nulls_first ? 1 : -1; } if (ks->type == RAY_SYM) { /* cell-data: ids resolve over the COLUMN's domain. Runtime- @@ -216,12 +218,10 @@ static inline int fpk_cmp(const fpk_par_ctx_t* c, int64_t row_a, int64_t row_b) * want stable source-order semantics on ties. * * Future: caller-specified NULLS FIRST / NULLS LAST. The - * has_nulls leg above implements the default policy (LAST for - * ASC, FIRST for DESC). An explicit NULLS FIRST/LAST clause - * in the query DSL would need to thread through fpk_keyspec_t - * as a third orientation flag and override the default leg — - * the call site already has all the data needed. Tracked - * separately. */ + * has_nulls leg above already reads a per-key flag, but the flag + * is filled from the direction alone; an explicit clause in the + * query DSL would thread the caller's choice into it instead. + * Tracked separately. */ if (row_a > row_b) return 1; /* a is worse — evict first */ if (row_a < row_b) return -1; return 0; @@ -337,6 +337,7 @@ ray_t* ray_fused_topk_select(ray_t* tbl, ctx.keys[i].esz = ray_sym_elem_size(kt, col->attrs); ctx.keys[i].desc = sort_descs[i]; ctx.keys[i].has_nulls = (col->attrs & RAY_ATTR_HAS_NULLS) ? 1 : 0; + ctx.keys[i].nulls_first = sort_nulls_first(sort_descs[i]); ctx.keys[i].dom_runtime = (kt == RAY_SYM && ray_sym_vec_domain(col) == ray_sym_runtime_domain()) ? 1 : 0; diff --git a/src/ops/graph.c b/src/ops/graph.c index 142335301..63d29d056 100644 --- a/src/ops/graph.c +++ b/src/ops/graph.c @@ -773,9 +773,8 @@ ray_op_t* ray_sort_op(ray_graph_t* g, ray_op_t* table_node, if (nulls_first) { memcpy(ext->sort.nulls_first, nulls_first, nf_sz); } else { - /* Default: NULLS LAST for ASC, NULLS FIRST for DESC */ for (uint32_t i = 0; i < n_cols; i++) - ext->sort.nulls_first[i] = descs[i] ? 1 : 0; + ext->sort.nulls_first[i] = sort_nulls_first(descs[i]); } ext->sort.n_cols = n_cols; diff --git a/src/ops/group.c b/src/ops/group.c index 493a260c2..a44816596 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -1582,7 +1582,6 @@ typedef struct { * hot loop avoids the ray_t pointer indirection. */ static inline bool cdpg_is_null(const void* base, int64_t r, int8_t in_type, uint8_t esz) { - (void)esz; /* width only mattered for the (now removed) SYM arm */ switch (in_type) { case RAY_F64: { double f = ((const double*)base)[r]; return f != f; } case RAY_F32: { float f = ((const float*) base)[r]; return f != f; } @@ -1592,9 +1591,11 @@ static inline bool cdpg_is_null(const void* base, int64_t r, return ((const int32_t*)base)[r] == NULL_I32; case RAY_I16: return ((const int16_t*)base)[r] == NULL_I16; - /* SYM has no null — the empty sym (id 0) is a value, not null. This - * helper is only reached behind a has_nulls guard (= src HAS_NULLS, - * never set on SYM), so an in_type==RAY_SYM call cannot occur. */ + case RAY_SYM: + if (esz == 1) return ((const uint8_t*)base)[r] == 0; + if (esz == 2) return ((const uint16_t*)base)[r] == 0; + if (esz == 4) return ((const uint32_t*)base)[r] == 0; + return ((const int64_t*)base)[r] == 0; default: /* BOOL / U8 — non-nullable */ return false; } @@ -2743,9 +2744,15 @@ ray_t* ray_mode_per_group_buf(ray_t* src, * * Output is a LIST of n_groups cells; cells are pre-allocated typed * vecs of the same element type as `src`, so workers can write into - * cell data without locking. Null rows are skipped (matches the - * standalone topk_take_vec path which routes nulls-last for asc, - * nulls-first for desc and gathers only the non-null prefix). */ + * cell data without locking. + * + * Null rows are SKIPPED here, and that is a different policy from the + * standalone topk_take_vec, which orders by sort_nulls_first — a null is + * the smallest value — and so can return nulls in its result. Over + * [3 0N 1 0N 2] the standalone (bot v 2) is [0N 0N] while the grouped + * one is [1 2]. Both are defensible: ordering treats a null as a value + * at one end, aggregation treats it as no value at all. What is not + * defensible is claiming they agree, which this comment used to. */ typedef struct { const void* base; @@ -4432,7 +4439,7 @@ static inline void accum_from_entry(char* row, const char* entry, else if (af & GHT_AF_LAST) { if (take_last) memcpy(row + ly->off_sum + s * 8, val, 8); } else if (aflags2[a] & GHT_AF2_TRUTHY) { ROW_WR_I64(row, ly->off_sum, s) += (v != 0); } else if (af & GHT_AF_PROD) { ROW_WR_I64(row, ly->off_sum, s) = (int64_t)((uint64_t)ROW_RD_I64(row, ly->off_sum, s) * (uint64_t)v); } - else { ROW_WR_I64(row, ly->off_sum, s) += v; } + else { ROW_WR_I64(row, ly->off_sum, s) = wrap_add_i64(ROW_RD_I64(row, ly->off_sum, s), v); } } if (nf & GHT_NEED_MIN) { int64_t* p = &ROW_WR_I64(row, ly->off_min, s); @@ -4560,7 +4567,7 @@ static void accum_from_entry_nullable(char* row, const char* entry, } } else if (aflags2[a] & GHT_AF2_TRUTHY) { ROW_WR_I64(row, ly->off_sum, s) += (v != 0); } else if (af & GHT_AF_PROD) { ROW_WR_I64(row, ly->off_sum, s) = (int64_t)((uint64_t)ROW_RD_I64(row, ly->off_sum, s) * (uint64_t)v); } - else { ROW_WR_I64(row, ly->off_sum, s) += v; } + else { ROW_WR_I64(row, ly->off_sum, s) = wrap_add_i64(ROW_RD_I64(row, ly->off_sum, s), v); } } if (nf & GHT_NEED_MIN) { int64_t* p = &ROW_WR_I64(row, ly->off_min, s); @@ -5570,7 +5577,6 @@ typedef struct { int8_t* key_types; uint8_t* key_attrs; uint8_t* key_esizes; - ray_t** key_cols; /* [n_keys] output key vecs (for null bit writes) */ uint32_t n_keys; /* full width — a uint8 here wrapped 256 keys to 0 */ agg_out_t* agg_outs; uint32_t n_aggs; @@ -5618,13 +5624,27 @@ static void radix_phase3_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ int8_t kt = c->key_types[k]; size_t doff = (size_t)di * esz; if (nullw[k >> 6] & ((int64_t)((uint64_t)1 << (k & 63)))) { - if (c->key_cols && c->key_cols[k]) - grp_set_null(c->key_cols[k], di); - /* Fill the correct-width sentinel. */ + /* Fill the correct-width canonical null. EVERY key type + * must land in an arm here: the destination element is + * freshly allocated and NOT zeroed (ray_vec_new / + * ray_sym_vec_new), so falling through would emit + * uninitialized bytes as the group's key — for a SYM key + * that stale word resolves through the source domain to an + * arbitrary dictionary entry, i.e. a silent wrong answer + * whose counts still look right. + * + * The payload is the whole job here. HAS_NULLS is seeded + * from the source column before the dispatch and + * re-derived serially afterwards by grp_finalize_nulls, so + * no worker stores into the shared attrs byte that every + * other worker reads non-atomically through ray_data(). */ switch (kt) { case RAY_F64: { double v = NULL_F64; memcpy(dst + doff, &v, 8); break; } + case RAY_F32: { + float v = NULL_F32; memcpy(dst + doff, &v, 4); break; + } case RAY_I64: case RAY_TIMESTAMP: { int64_t v = NULL_I64; memcpy(dst + doff, &v, 8); break; } @@ -5634,8 +5654,18 @@ static void radix_phase3_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ case RAY_I16: { int16_t v = NULL_I16; memcpy(dst + doff, &v, 2); break; } - case RAY_STR: { memset(dst + doff, 0, sizeof(ray_str_t)); break; } - default: break; + default: + /* SYM (domain position 0 == ""), STR (len 0) and + * GUID (16 zero bytes) all encode their canonical + * null as all-zero bytes at the column's element + * width — the same payload + * ray_vec_set_null_checked writes on the serial + * emit path. The HAS_NULLS bit these three need + * (par_set_null does not write it for them) is + * seeded from the source column BEFORE the + * dispatch, so no worker touches attrs here. */ + memset(dst + doff, 0, esz); + break; } continue; } @@ -5773,7 +5803,7 @@ static void radix_phase3_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ switch (op) { case OP_SUM: v = ROW_RD_I64(row, ly->off_sum, s); - if (ao->affine) v += ao->bias_i64 * cnt; + if (ao->affine) v = wrap_add_i64(v, wrap_mul_i64(ao->bias_i64, cnt)); break; case OP_PROD: if (nn == 0) { v = int_null; grp_set_null(ao->vec, di); break; } @@ -6714,7 +6744,7 @@ static void emit_agg_columns(ray_t** result, ray_graph_t* g, const ray_op_ext_t* case OP_SUM: v = sum_i64[idx]; if (affine && affine[a].enabled) - v += affine[a].bias_i64 * counts[gi]; + v = wrap_add_i64(v, wrap_mul_i64(affine[a].bias_i64, counts[gi])); break; case OP_PROD: if (nn == 0) { v = int_null; ray_vec_set_null(new_col, gi, true); break; } @@ -7349,8 +7379,8 @@ static void scalar_sum_i64_fn(void* ctx, uint32_t worker_id, int64_t start, int6 const int64_t* restrict data = (const int64_t*)c->agg_ptrs[0]; int64_t sum = 0; for (int64_t r = start; r < end; r++) - sum += data[r]; - acc->sum[0].i += sum; + sum = wrap_add_i64(sum, data[r]); + acc->sum[0].i = wrap_add_i64(acc->sum[0].i, sum); acc->count[0] += end - start; } @@ -7373,7 +7403,7 @@ static void scalar_sum_linear_i64_fn(void* ctx, uint32_t worker_id, int64_t star const agg_linear_t* lin = &c->agg_linear[0]; int64_t n = end - start; - int64_t sum = lin->bias_i64 * n; + int64_t sum = wrap_mul_i64(lin->bias_i64, n); /* n_terms is bounded by AGG_LINEAR_MAX_TERMS (8, internal.h) — an * unrelated fixed cap on linear-expression arity, not a GROUP n_keys/ * n_aggs count, so it stays uint8_t. */ @@ -7384,11 +7414,11 @@ static void scalar_sum_linear_i64_fn(void* ctx, uint32_t worker_id, int64_t star int8_t type = lin->term_types[t]; int64_t term_sum = 0; for (int64_t r = start; r < end; r++) - term_sum += scalar_i64_at(ptr, type, r); - sum += coeff * term_sum; + term_sum = wrap_add_i64(term_sum, scalar_i64_at(ptr, type, r)); + sum = wrap_add_i64(sum, wrap_mul_i64(coeff, term_sum)); } - acc->sum[0].i += sum; + acc->sum[0].i = wrap_add_i64(acc->sum[0].i, sum); acc->count[0] += n; } @@ -7413,8 +7443,10 @@ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) /* n_terms bounded by AGG_LINEAR_MAX_TERMS (8) — see the note in * scalar_sum_linear_i64_fn above; unrelated to n_keys/n_aggs. */ for (uint8_t t = 0; t < lin->n_terms; t++) { - iv += lin->coeff_i64[t] * - scalar_i64_at(lin->term_ptrs[t], lin->term_types[t], r); + iv = wrap_add_i64( + iv, + wrap_mul_i64(lin->coeff_i64[t], + scalar_i64_at(lin->term_ptrs[t], lin->term_types[t], r))); } fv = (double)iv; } else { @@ -7447,7 +7479,7 @@ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) if (nn) nn[a]++; } } else if (RAY_LIKELY(!int_null)) { - acc->sum[a].i += iv; + acc->sum[a].i = wrap_add_i64(acc->sum[a].i, iv); if (acc->sumsq_f64) acc->sumsq_f64[a] += fv * fv; if (nn) nn[a]++; } @@ -7545,8 +7577,9 @@ static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64 } if (!c->agg_ptrs[a]) continue; if (c->agg_strlen && c->agg_strlen[a]) { - acc->sum[idx].i += group_strlen_at_cached( - c->agg_cols[a], r, c->sym_strings, c->sym_count); + acc->sum[idx].i = wrap_add_i64( + acc->sum[idx].i, + group_strlen_at_cached(c->agg_cols[a], r, c->sym_strings, c->sym_count)); if (nn) nn[idx]++; } else if (f64m & ((uint64_t)1 << a)) { /* NaN payload = null, skip from sum. */ @@ -7561,7 +7594,7 @@ static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64 uint8_t v_attrs = c->agg_cols[a] ? c->agg_cols[a]->attrs : 0; int64_t v = read_col_i64(c->agg_ptrs[a], r, c->agg_types[a], v_attrs); if (RAY_LIKELY(!((inm >> a) & 1) || v != c->agg_int_null_sentinel[a])) { - acc->sum[idx].i += v; + acc->sum[idx].i = wrap_add_i64(acc->sum[idx].i, v); if (nn) nn[idx]++; } } @@ -7912,7 +7945,7 @@ static void da_merge_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { } else if (group_fp_type(agg_types[a]) || agg_is_binary_agg(aop)) merged->sum[idx].f += wa->sum[idx].f; else - merged->sum[idx].i += wa->sum[idx].i; + merged->sum[idx].i = wrap_add_i64(merged->sum[idx].i, wa->sum[idx].i); } } if (c->need_flags & DA_NEED_MIN) { @@ -10104,12 +10137,16 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { for (uint32_t a = 0; a < n_aggs; a++) { \ if (ext->agg_ops[a] == OP_COUNT || !agg_ptrs[a]) continue; \ if (agg_strlen[a]) \ - sums[a].i += group_strlen_at_cached( \ - agg_vecs[a], dyn_row, strlen_sym_strings, strlen_sym_count); \ + sums[a].i = wrap_add_i64( \ + sums[a].i, \ + group_strlen_at_cached( \ + agg_vecs[a], dyn_row, strlen_sym_strings, strlen_sym_count)); \ else if (agg_f64_mask & ((uint64_t)1 << a)) \ sums[a].f += group_fp_at(agg_ptrs[a], agg_types[a], dyn_row); \ else \ - sums[a].i += read_col_i64(agg_ptrs[a], dyn_row, agg_types[a], 0); \ + sums[a].i = wrap_add_i64( \ + sums[a].i, \ + read_col_i64(agg_ptrs[a], dyn_row, agg_types[a], 0)); \ } \ } \ } while (0) @@ -10239,12 +10276,16 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { for (uint32_t a = 0; a < n_aggs; a++) { \ if (ext->agg_ops[a] == OP_COUNT || !agg_ptrs[a]) continue; \ if (agg_strlen[a]) \ - sums[a].i += group_strlen_at_cached( \ - agg_vecs[a], dyn_row, strlen_sym_strings, strlen_sym_count); \ + sums[a].i = wrap_add_i64( \ + sums[a].i, \ + group_strlen_at_cached( \ + agg_vecs[a], dyn_row, strlen_sym_strings, strlen_sym_count)); \ else if (agg_f64_mask & ((uint64_t)1 << a)) \ sums[a].f += group_fp_at(agg_ptrs[a], agg_types[a], dyn_row); \ else \ - sums[a].i += read_col_i64(agg_ptrs[a], dyn_row, agg_types[a], 0);\ + sums[a].i = wrap_add_i64( \ + sums[a].i, \ + read_col_i64(agg_ptrs[a], dyn_row, agg_types[a], 0)); \ } \ } while (0) if (match_idx) { @@ -11215,7 +11256,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (group_fp_type(agg_types[a])) m->sum[a].f += wa->sum[a].f; else - m->sum[a].i += wa->sum[a].i; + m->sum[a].i = wrap_add_i64(m->sum[a].i, wa->sum[a].i); } } } @@ -11884,7 +11925,7 @@ da_path:; uint16_t aop = ext->agg_ops[a]; if (aop == OP_SUM || aop == OP_AVG || aop == OP_ALL || aop == OP_ANY || aop == OP_STDDEV || aop == OP_STDDEV_POP || aop == OP_VAR || aop == OP_VAR_POP || agg_is_binary_agg(aop)) { if (group_fp_type(agg_types[a]) || agg_is_binary_agg(aop)) merged->sum[idx].f += wa->sum[idx].f; - else merged->sum[idx].i += wa->sum[idx].i; + else merged->sum[idx].i = wrap_add_i64(merged->sum[idx].i, wa->sum[idx].i); } else if (aop == OP_PROD) { /* Use per-(group, agg) non-null counts when * available so an all-null worker doesn't @@ -12011,7 +12052,7 @@ da_path:; * for integer x-columns — merge as float. */ merged->sum[idx].f += wa->sum[idx].f; else - merged->sum[idx].i += wa->sum[idx].i; + merged->sum[idx].i = wrap_add_i64(merged->sum[idx].i, wa->sum[idx].i); } } } @@ -12367,14 +12408,17 @@ da_path:; if (ext->agg_ops[a] == OP_COUNT || !agg_ptrs[a]) continue; if (agg_strlen[a]) - sums[a].i += group_strlen_at_cached( - agg_vecs[a], r, strlen_sym_strings, - strlen_sym_count); + sums[a].i = wrap_add_i64( + sums[a].i, + group_strlen_at_cached(agg_vecs[a], r, + strlen_sym_strings, + strlen_sym_count)); else if (agg_f64_mask & ((uint64_t)1 << a)) sums[a].f += group_fp_at(agg_ptrs[a], agg_types[a], r); else - sums[a].i += read_col_i64(agg_ptrs[a], r, - agg_types[a], 0); + sums[a].i = wrap_add_i64( + sums[a].i, + read_col_i64(agg_ptrs[a], r, agg_types[a], 0)); } } } @@ -12475,14 +12519,17 @@ da_path:; if (ext->agg_ops[a] == OP_COUNT || !agg_ptrs[a]) continue; if (agg_strlen[a]) - sums[a].i += group_strlen_at_cached( - agg_vecs[a], r, strlen_sym_strings, - strlen_sym_count); + sums[a].i = wrap_add_i64( + sums[a].i, + group_strlen_at_cached(agg_vecs[a], r, + strlen_sym_strings, + strlen_sym_count)); else if (agg_f64_mask & ((uint64_t)1 << a)) sums[a].f += group_fp_at(agg_ptrs[a], agg_types[a], r); else - sums[a].i += read_col_i64(agg_ptrs[a], r, - agg_types[a], 0); + sums[a].i = wrap_add_i64( + sums[a].i, + read_col_i64(agg_ptrs[a], r, agg_types[a], 0)); } } } @@ -12564,13 +12611,17 @@ da_path:; if (ext->agg_ops[a] == OP_COUNT || !agg_ptrs[a]) continue; if (agg_strlen[a]) - sums[a].i += group_strlen_at_cached( - agg_vecs[a], r, strlen_sym_strings, - strlen_sym_count); + sums[a].i = wrap_add_i64( + sums[a].i, + group_strlen_at_cached(agg_vecs[a], r, + strlen_sym_strings, + strlen_sym_count)); else if (agg_f64_mask & ((uint64_t)1 << a)) sums[a].f += group_fp_at(agg_ptrs[a], agg_types[a], r); else - sums[a].i += read_col_i64(agg_ptrs[a], r, agg_types[a], 0); + sums[a].i = wrap_add_i64( + sums[a].i, + read_col_i64(agg_ptrs[a], r, agg_types[a], 0)); } } } @@ -12705,13 +12756,17 @@ da_path:; if (ext->agg_ops[a] == OP_COUNT || !agg_ptrs[a]) continue; if (agg_strlen[a]) - sums[a].i += group_strlen_at_cached( - agg_vecs[a], r, strlen_sym_strings, - strlen_sym_count); + sums[a].i = wrap_add_i64( + sums[a].i, + group_strlen_at_cached(agg_vecs[a], r, + strlen_sym_strings, + strlen_sym_count)); else if (agg_f64_mask & ((uint64_t)1 << a)) sums[a].f += group_fp_at(agg_ptrs[a], agg_types[a], r); else - sums[a].i += read_col_i64(agg_ptrs[a], r, agg_types[a], 0); + sums[a].i = wrap_add_i64( + sums[a].i, + read_col_i64(agg_ptrs[a], r, agg_types[a], 0)); } } } @@ -13658,6 +13713,26 @@ v2_emit:; new_col = ray_vec_new(src_col->type, (int64_t)total_grps); if (!new_col || RAY_IS_ERR(new_col)) continue; new_col->len = (int64_t)total_grps; + /* Seed HAS_NULLS from the source key column, exactly as the + * gather-based emit does (agg_gather_key_col). radix_phase3_fn + * runs in parallel and par_set_null writes this bit for the + * sentinel types only, so setting it once here — serially, + * before the dispatch — keeps SYM/STR/GUID null keys flagged + * without a worker ever storing into a shared attrs byte that + * other workers read non-atomically via ray_data(). + * + * Hop the slice parent, exactly as ray_key_may_be_null does: a + * SLICE carries no HAS_NULLS of its own, so reading src_col->attrs + * directly would set the null-mask bits (which that predicate + * gates) while leaving the emitted column unflagged. Benign for + * SYM/STR (is_null reads the payload) and recoverable for the + * sentinel types (grp_finalize_nulls rescans), but GUID nullness + * rests SOLELY on this attr — its reader gates on HAS_NULLS before + * looking at the 16 zero bytes. */ + const ray_t* null_src = (src_col->attrs & RAY_ATTR_SLICE) + ? src_col->slice_parent : src_col; + if (null_src && (null_src->attrs & RAY_ATTR_HAS_NULLS)) + new_col->attrs |= RAY_ATTR_HAS_NULLS; key_cols[k] = new_col; key_dsts[k] = (char*)ray_data(new_col); key_out_types[k] = src_col->type; @@ -13737,7 +13812,6 @@ v2_emit:; .key_types = key_out_types, .key_attrs = key_attrs, .key_esizes = key_esizes, - .key_cols = key_cols, .n_keys = n_keys, .agg_outs = agg_outs, .n_aggs = n_aggs, @@ -14482,7 +14556,8 @@ sequential_fallback:; switch (agg_op) { case OP_SUM: v = ROW_RD_I64(row, ly->off_sum, s); - if (agg_affine[a].enabled) v += agg_affine[a].bias_i64 * cnt; + if (agg_affine[a].enabled) + v = wrap_add_i64(v, wrap_mul_i64(agg_affine[a].bias_i64, cnt)); break; case OP_PROD: if (nn == 0) { v = int_null; ray_vec_set_null(new_col, gi, true); break; } diff --git a/src/ops/idxop.c b/src/ops/idxop.c index 97dd5ff01..e39765767 100644 --- a/src/ops/idxop.c +++ b/src/ops/idxop.c @@ -1198,9 +1198,10 @@ static bool idx_fresh(ray_t* col, ray_idx_kind_t kind) { } /* v1 routing gate for the NEW consult paths: like idx_fresh but also - * excludes null-bearing columns. Sort perm orders nulls LAST while - * sentinel values order FIRST, and comparison semantics on null rows - * follow null-as-minimum — none of the new consults model that in v1. + * excludes null-bearing columns. A sort perm now orders nulls FIRST on + * ascending, agreeing with null-as-minimum rather than contradicting it + * — but a perm built before that and persisted still carries nulls last, + * and none of the new consults model either placement in v1. * (The pre-existing hash-eq probe keeps bare idx_fresh: its builder * skips null rows, making null-bearing probes structurally correct.) */ static bool idx_fresh_nonull(ray_t* col, ray_idx_kind_t kind) { @@ -2068,7 +2069,11 @@ bool ray_index_bloom_absent(ray_t* col, int64_t key) { * Sort index — ascending permutation of row ids * * Delegates to the existing parallel sort builder. Result is an I64 vec of - * length parent->len with default null-handling (nulls last for asc). + * length parent->len with the default null placement — a null is the + * smallest value, so nulls come first on ascending. An index persisted + * before that rule changed carries the old order; idx_fresh_nonull keeps + * such an index off the consult paths, which is what makes the difference + * unobservable rather than merely unlikely. * -------------------------------------------------------------------------- */ ray_t* ray_index_attach_sort(ray_t** vp) { diff --git a/src/ops/internal.h b/src/ops/internal.h index 8704c7fea..deda017ca 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -771,7 +771,8 @@ typedef struct { typedef enum { EXPR_BAIL_ROOT = 0, EXPR_BAIL_SIZE, EXPR_BAIL_DEPTH, EXPR_BAIL_REGS, - EXPR_BAIL_INS, EXPR_BAIL_MAPCOMMON, EXPR_BAIL_STR, EXPR_BAIL_NULLS, + EXPR_BAIL_INS, EXPR_BAIL_MAPCOMMON, EXPR_BAIL_STR, EXPR_BAIL_GUID, + EXPR_BAIL_NULLS, EXPR_BAIL_SLICE, EXPR_BAIL_SYM_DOMAIN, EXPR_BAIL_CONST, EXPR_BAIL_NULL_SHAPE, /* nullable program hit a not-yet-null-capable instruction */ EXPR_BAIL_OTHER, EXPR_BAIL__N @@ -787,6 +788,7 @@ extern bool ray_join_force_dup_fallback; /* perf-gate bypass: disable the auto dup-fallback to measure the pre-fix O(dup²) build */ extern bool ray_join_no_dup_fallback; extern uint64_t ray_join_dup_fallbacks; +extern uint64_t ray_join_null_fallbacks; extern bool ray_agg_engine_v2; /* route OP_GROUP through v2 agg engine; default off */ void ray_expr_stats_init(void); @@ -859,9 +861,21 @@ typedef struct { #define NEARLY_SORTED_FRAC 0.05 /* threshold for nearly-sorted detection */ #define MK_PRESCAN_MAX_KEYS 8 /* max sort keys for stack allocation */ +/* Where a null sorts, stated once for every sort path. + * + * A null is the smallest value, so ascending puts nulls first and descending + * puts them last. Any path that needs the default must ask here rather than + * spell it out: two paths spelling out opposite defaults is what made a null's + * position depend on the row count and the column type, since which path runs + * is chosen by both. */ +static inline uint8_t sort_nulls_first(uint8_t desc) { return (uint8_t)!desc; } + typedef struct { ray_t** vecs; uint8_t* desc; + /* NULL means "the default for each key's direction" — see + * sort_nulls_first. A caller with its own policy passes one flag per + * key. */ uint8_t* nulls_first; uint32_t n_sort; } sort_cmp_ctx_t; @@ -889,7 +903,10 @@ typedef struct { int8_t type; /* column type */ uint8_t col_attrs; /* RAY_SYM width attrs */ bool desc; - bool nulls_first; /* for single-key F64: 1=nulls first */ + /* Where this key's nulls go: 1=first, 0=last. Read by every typed + * single-key arm, not just the float one; the composite encode does + * not consult it and declines a nullable F64 key instead. */ + bool nulls_first; /* SYM rank mapping (NULL if not sym): */ const uint32_t* enum_rank; /* intern_id → sort rank */ /* Composite-key fields (n_keys > 1): */ @@ -1596,9 +1613,9 @@ ray_t* exec_node(ray_graph_t* g, ray_op_t* op); * with different idx, so each per-slot store is uncontended. attrs OR * is atomic so the read-modify-write on the shared attrs byte is safe. * - * BOOL/U8/SYM are non-nullable (rejected at the producer surface) and - * are no-ops here. STR/GUID don't appear in parallel aggregation/window - * output columns and likewise no-op. */ + * BOOL/U8 are non-nullable (rejected at the producer surface). SYM/STR/GUID + * don't appear in parallel aggregation/window output columns and are no-ops + * here. */ static inline void par_set_null(ray_t* vec, int64_t idx) { void* p = ray_data(vec); switch (vec->type) { diff --git a/src/ops/join.c b/src/ops/join.c index bf818fa2a..e73cedf59 100644 --- a/src/ops/join.c +++ b/src/ops/join.c @@ -41,6 +41,9 @@ bool ray_join_force_dup_fallback = false; bool ray_join_no_dup_fallback = false; /* Diagnostic: radix joins that fell back due to pathological key duplication. */ uint64_t ray_join_dup_fallbacks = 0; +/* Diagnostic: radix joins routed to the chained path upfront because the + * build side carries more all-null key rows than RADIX_DUP_RUN_MAX (#458). */ +uint64_t ray_join_null_fallbacks = 0; static int join_store_key_cell(ray_t* dst, int64_t dst_row, ray_t* src, int64_t src_row) { @@ -102,21 +105,33 @@ static inline bool join_str_eq_hashed(const ray_str_t* a, const char* pool_a, return memcmp(pa, pb, a->len) == 0; } +/* Hash payload for a null key cell. One canonical value per key POSITION + * (the ray_hash_combine chain below still mixes in k), so every null in a + * given key column lands in the same bucket on both sides of the join — + * the precondition for join_keys_eq's null == null. Any collision with a + * real key's hash is resolved by join_keys_eq, as for any other hash. */ +#define JOIN_NULL_KEY_HASH INT64_C(0x5B7A6D3F2E1C0A94) + static uint64_t hash_row_keys(ray_t** key_vecs, uint32_t n_keys, int64_t row) { uint64_t h = 0; for (uint32_t k = 0; k < n_keys; k++) { ray_t* col = key_vecs[k]; if (!col) continue; - /* NULL key — produce unique hash that won't match any other row */ - if (ray_vec_is_null(col, row)) - return h ^ ((uint64_t)row * 0x9E3779B97F4A7C15ULL); uint64_t kh; - if (col->type == RAY_STR) { + if (ray_vec_is_null(col, row)) { + /* null == null: hash every null cell alike instead of giving the + * row a private hash. A per-row hash made a null key unmatchable + * even against itself, so `anti-join [c] X X` came back non-empty + * and a null-keyed left-join row missed its real match. */ + kh = ray_hash_i64(JOIN_NULL_KEY_HASH); + } else if (col->type == RAY_STR) { const char* pool = NULL; const ray_str_t* str = join_str_cell(col, row, &pool); kh = ray_str_is_inline(str) ? ray_hash_bytes(str->data, str->len) : ray_str_t_hash32(str, pool); + } else if (col->type == RAY_GUID) { + kh = ray_hash_bytes((const uint8_t*)ray_data(col) + row * 16, 16); } else if (col->type == RAY_F64) { kh = ray_hash_f64(((double*)ray_data(col))[row]); } else { @@ -574,8 +589,26 @@ static inline bool join_keys_eq(ray_t* const* l_vecs, ray_t* const* r_vecs, uint ray_t* lc = l_vecs[k]; ray_t* rc = r_vecs[k]; if (!lc || !rc) return false; - /* NULL != NULL in join predicates */ - if (ray_vec_is_null(lc, l) || ray_vec_is_null(rc, r)) return false; + /* null == null, null != non-null. This is the rule the rest of the + * runtime already applies to key columns: collection.c's hashset + * folds every null into one bucket (so `distinct` keeps exactly one + * null and `in` matches null against null), group.c folds them into + * one group, and atom_eq answers 1 for two nulls. Joins used to + * reject a null outright, which made `anti-join [c] X X` non-empty + * whenever c held a null and made left-join miss a null-keyed match. + * As-of join keeps its own documented NULLs-never-match rule; it + * does not route through here. */ + bool l_null = ray_vec_is_null(lc, l); + bool r_null = ray_vec_is_null(rc, r); + if (l_null || r_null) { + if (l_null != r_null) return false; + /* No looser than the value arms below: they pair STR only with + * STR and GUID only with GUID, so two nulls of those types are + * equal only to their own kind. */ + if ((lc->type == RAY_STR) != (rc->type == RAY_STR)) return false; + if ((lc->type == RAY_GUID) != (rc->type == RAY_GUID)) return false; + continue; + } if (lc->type == RAY_STR || rc->type == RAY_STR) { if (lc->type != RAY_STR || rc->type != RAY_STR) return false; const char* lpool = NULL; @@ -583,6 +616,11 @@ static inline bool join_keys_eq(ray_t* const* l_vecs, ray_t* const* r_vecs, uint const ray_str_t* ls = join_str_cell(lc, l, &lpool); const ray_str_t* rs = join_str_cell(rc, r, &rpool); if (!ray_str_t_eq(ls, lpool, rs, rpool)) return false; + } else if (lc->type == RAY_GUID || rc->type == RAY_GUID) { + if (lc->type != RAY_GUID || rc->type != RAY_GUID) return false; + const uint8_t* lb = (const uint8_t*)ray_data(lc) + l * 16; + const uint8_t* rb = (const uint8_t*)ray_data(rc) + r * 16; + if (memcmp(lb, rb, 16) != 0) return false; } else if (lc->type == RAY_F64) { if (((double*)ray_data(lc))[l] != ((double*)ray_data(rc))[r]) return false; } else { @@ -1154,6 +1192,38 @@ static ray_t* exec_join_flat(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ra uint8_t radix_bits = radix_join_bits(build_rows); uint32_t n_rparts = (uint32_t)1 << radix_bits; + /* #458: every null key cell hashes to the one canonical null value, + * so a build side with more all-null key rows than RADIX_DUP_RUN_MAX + * is GUARANTEED to trip the dup-run abort mid-build and re-run the + * whole join chained — full hash/partition/HT work discarded, every + * execution. Massive duplication is the chained HT's job either way + * (O(dup) build vs the open table's O(dup²)), so detect the case + * upfront and go there directly. The scan runs only when a key + * column advertises HAS_NULLS, uses the same null predicate as + * hash_row_keys (so it counts exactly what would form the run), and + * stops at the threshold. */ + { + bool any_nullable = false; + for (uint32_t k = 0; k < n_keys && !any_nullable; k++) + if (build_keys[k] && (build_keys[k]->attrs & RAY_ATTR_HAS_NULLS)) + any_nullable = true; + if (any_nullable) { + int64_t null_rows = 0; + for (int64_t r = 0; r < build_rows; r++) { + bool all_null = true; + for (uint32_t k = 0; k < n_keys; k++) { + ray_t* col = build_keys[k]; + if (!col || !ray_vec_is_null(col, r)) { all_null = false; break; } + } + if (all_null && ++null_rows > RADIX_DUP_RUN_MAX) break; + } + if (null_rows > RADIX_DUP_RUN_MAX) { + ray_join_null_fallbacks++; + goto chained_ht_fallback; + } + } + } + /* Pre-compute hashes for both sides (once, reused by histogram+scatter) */ ray_t* r_hash_hdr = NULL; uint32_t* r_hashes = (uint32_t*)scratch_alloc(&r_hash_hdr, @@ -1368,7 +1438,8 @@ static ray_t* exec_join_flat(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ra /* Free per-partition buffers allocated by worker threads. * Safe: ray_pool_dispatch_n has completed (workers are back on semaphore), * ray_parallel_flag is 0, and ray_free handles cross-heap deallocation - * via the foreign-block list flushed by ray_heap_gc at ray_parallel_end. */ + * by handing each block to the worker heap that owns it, which takes + * it back on its own next allocation — no collector call involved. */ for (uint32_t rp2 = 0; rp2 < n_rparts; rp2++) { if (pp_l_hdr[rp2]) scratch_free(pp_l_hdr[rp2]); if (pp_r_hdr[rp2]) scratch_free(pp_r_hdr[rp2]); diff --git a/src/ops/ops.h b/src/ops/ops.h index abbf2d59d..33a50f5dc 100644 --- a/src/ops/ops.h +++ b/src/ops/ops.h @@ -379,6 +379,7 @@ static inline bool agg_is_truth_agg(uint16_t op) { /* Op flags */ #define OP_FLAG_PUSHED 0x01 /* filter interposed below a GROUP by predicate pushdown */ #define OP_FLAG_DEAD 0x02 +#define OP_FLAG_INVALID_SCAN 0x04 /* query compiler emitted an unknown column */ /* Sentinel node id for "no input". Node id 0 is a valid node (the first * one allocated), so zero cannot mean "none" — use the max value. All @@ -390,7 +391,7 @@ static inline bool agg_is_truth_agg(uint16_t op) { typedef struct ray_op { uint16_t opcode; /* OP_ADD, OP_SCAN, OP_FILTER, etc. */ uint8_t arity; /* 0, 1, or 2 */ - uint8_t flags; /* PUSHED, DEAD */ + uint8_t flags; /* PUSHED, DEAD, INVALID_SCAN */ int8_t out_type; /* inferred output type */ uint8_t pad[3]; uint32_t id; /* unique node ID (== index into g->nodes) */ @@ -877,7 +878,9 @@ void ray_graph_dump(ray_graph_t* g, ray_op_t* root, void* out); /* Sort columns and return index array (I64 vector of sorted indices). * Uses parallel radix sort for numerics, merge sort for strings/symbols. - * descs/nulls_first may be NULL (all-asc / nulls-last default). */ + * descs/nulls_first may be NULL: all-ascending, and the placement each + * direction gets from sort_nulls_first — a null is the smallest value, + * so nulls lead ascending and trail descending. */ ray_t* ray_sort_indices(ray_t** cols, uint8_t* descs, uint8_t* nulls_first, uint8_t n_cols, int64_t nrows); diff --git a/src/ops/query.c b/src/ops/query.c index e853c5922..e33347932 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -623,6 +623,12 @@ static ray_t* apply_sort_take(ray_t* result, ray_t** dict_elems, int64_t dict_n, if (ray_is_atom(tv) && (tv->type == -RAY_I64 || tv->type == -RAY_I32)) { int64_t atom_n = (tv->type == -RAY_I64) ? tv->i64 : tv->i32; ray_release(tv); + /* INT64_MIN is the i64 null sentinel (0N); negating it below is + * signed-overflow UB. Reject it up front, matching ray_take_fn. */ + if (atom_n == INT64_MIN) { + ray_release(result); + return ray_error("type", "select: take: count is null or out of range"); + } int64_t nrows = (result->type == RAY_TABLE) ? ray_table_nrows(result) @@ -737,8 +743,8 @@ static ray_t* apply_sort_take(ray_t* result, ray_t** dict_elems, int64_t dict_n, ray_t* sort_col = ray_table_get_col(result, key_syms[0]); if (sort_col) { topk = ray_topk_table(result, sort_col, - key_descs[0], key_descs[0] - /*nf=desc by default*/, k); + key_descs[0], + sort_nulls_first(key_descs[0]), k); } } else { ray_t* key_cols[TOPK_MAX_KEYS]; @@ -746,7 +752,7 @@ static ray_t* apply_sort_take(ray_t* result, ray_t** dict_elems, int64_t dict_n, int ok = 1; for (uint32_t i = 0; i < n_keys; i++) { key_cols[i] = ray_table_get_col(result, key_syms[i]); - nfs[i] = key_descs[i]; + nfs[i] = sort_nulls_first(key_descs[i]); if (!key_cols[i]) { ok = 0; break; } } if (ok) { @@ -862,6 +868,11 @@ static ray_t* apply_sort_take(ray_t* result, ray_t** dict_elems, int64_t dict_n, int64_t nrows = (sorted->type == RAY_TABLE) ? ray_table_nrows(sorted) : (ray_is_vec(sorted) ? sorted->len : 0); + /* INT64_MIN (0N) negated below is signed-overflow UB — reject it. */ + if (atom_n == INT64_MIN) { + ray_release(sorted); + return ray_error("type", "select: take: count is null or out of range"); + } int64_t start, amount; if (atom_n >= 0) { start = 0; @@ -1113,9 +1124,31 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { if (ray_is_atom(gv)) return ray_const_atom(g, gv); if (ray_is_vec(gv)) return ray_const_vec(g, gv); } - /* Unknown name — let ray_scan produce a column-not-found - * error at exec time, matching prior behavior. */ - return ray_scan(g, ray_str_ptr(s)); + /* Unknown name — retain an explicit invalid-scan marker. Optimizer + * shortcuts may make the scan dead (count/max/projection paths), but + * execution must still reject the original column reference. */ + ray_op_t* missing = ray_scan(g, ray_str_ptr(s)); + /* `_dist` is exempt, but only where it can legitimately appear: a + * rerank produces it during execution, so it is absent from the + * operand table at compile time. Exempting it unconditionally let + * every symptom of an unknown column back in for that one name — + * a projection under `_dist` shifted the labels left, and an + * aggregate over it answered its neutral element — in queries with + * no nearest: clause at all. */ + int64_t dist_sym = ray_sym_find("_dist", 5); + bool exempt = false; + if (missing && expr->i64 == dist_sym) { + for (uint32_t i = 0; i < g->node_count && !exempt; i++) + if (g->nodes[i].opcode == OP_ANN_RERANK || + g->nodes[i].opcode == OP_KNN_RERANK) + exempt = true; + } + if (missing && !exempt) { + missing->flags |= OP_FLAG_INVALID_SCAN; + ray_op_ext_t* ext = find_ext(g, missing->id); + if (ext) ext->base.flags |= OP_FLAG_INVALID_SCAN; + } + return missing; } /* Symbol literal (ATTR_QUOTED set; name refs handled above). Inside a @@ -5859,8 +5892,9 @@ ray_t* ray_select(ray_t** args, int64_t n) { } } /* Sort keys: only verify the column exists. Nulls are now - * handled by the null-aware leg in fpk_cmp (NULLS LAST for - * ASC, NULLS FIRST for DESC, matching sort.c's default). + * handled by the null-aware leg in fpk_cmp, which takes its + * placement from sort_nulls_first like every other sort path: + * a null is the smallest value, so first for ASC, last for DESC. * Output columns are also handled — the fused materialiser * propagates null bitmaps via ray_vec_set_null. */ if (!bad_clause) { @@ -9919,6 +9953,13 @@ ray_t* ray_select(ray_t** args, int64_t n) { if (!tv || RAY_IS_ERR(tv)) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return tv ? tv : ray_error("domain", "select: failed to evaluate `take:`"); } if (ray_is_atom(tv) && (tv->type == -RAY_I64 || tv->type == -RAY_I32)) { int64_t n_take = (tv->type == -RAY_I64) ? tv->i64 : tv->i32; + /* INT64_MIN (0N) negated for a tail pushdown is signed-overflow UB; + * reject it before it reaches ray_tail / the TAIL kernel. */ + if (n_take == INT64_MIN) { + ray_release(tv); + ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return ray_error("type", "select: take: count is null or out of range"); + } if (group_take_push) { take_pre.kind = TAKE_PRE_ATOM; take_pre.a = n_take; @@ -10127,8 +10168,16 @@ ray_t* ray_select(ray_t** args, int64_t n) { int j = 0; for (int64_t i = 0; i + 1 < dict_n; i += 2) { int64_t kid = dict_elems[i]->i64; + /* Every clause keyword has to be skipped here, not just + * most of them: this walk is positional, so a keyword it + * fails to skip consumes an output slot and every name + * after it lands on the wrong column. nearest: was + * missing, and it is counted out where the outputs are + * counted, so a query naming it before its outputs + * labelled them one position early. */ if (kid == from_id || kid == where_id || kid == by_id || - kid == take_id || kid == asc_id || kid == desc_id) continue; + kid == take_id || kid == asc_id || kid == desc_id || + kid == nearest_id) continue; if (n_key_cols + j < ncols) ray_table_set_col_name(result, n_key_cols + j, kid); j++; @@ -11360,6 +11409,16 @@ static int8_t typeless_col_type(ray_t* payload) { return RAY_I64; } +/* HAS_NULLS for a payload that may be a slice: slices carry the flag on + * their parent. Over-approximation is harmless (the flag is a fast-path + * gate; sentinels in the payload are the source of truth). */ +static bool payload_may_have_nulls(const ray_t* v) { + if (v->attrs & RAY_ATTR_HAS_NULLS) return true; + if ((v->attrs & RAY_ATTR_SLICE) && v->slice_parent) + return (v->slice_parent->attrs & RAY_ATTR_HAS_NULLS) != 0; + return false; +} + /* Helper: convert a Rayfall list of atoms into a typed column vector by * appending to an existing column (for insert/upsert). */ static ray_t* append_atom_to_col(ray_t* col_vec, ray_t* atom) { @@ -11675,8 +11734,16 @@ ray_t* ray_update(ray_t** args, int64_t n) { char* src = (char*)ray_data(full_col); char* dst = (char*)ray_data(sub_col); int64_t* idxs = (int64_t*)ray_data(idx_vec); - for (int64_t r = 0; r < gsize; r++) + bool copied_null = false; + for (int64_t r = 0; r < gsize; r++) { memcpy(dst + r * esz, src + idxs[r] * esz, esz); + copied_null |= ray_vec_is_null(full_col, idxs[r]); + } + /* Raw payload gathers do not carry vector metadata. The + * aggregate kernels use HAS_NULLS as their fast-path gate, + * so preserve it when any gathered row is null. */ + if (copied_null) + sub_col->attrs |= RAY_ATTR_HAS_NULLS; sub_tbl = ray_table_add_col(sub_tbl, cn, sub_col); ray_release(sub_col); if (RAY_IS_ERR(sub_tbl)) { ray_release(out_col); UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); return sub_tbl; } @@ -13895,6 +13962,187 @@ ray_t* ray_insert(ray_t** args, int64_t n) { ray_t** row_elems = (ray_t**)ray_data(row); int64_t nrows = ray_table_nrows(tbl); + /* ---- In-place append fast path (#455) ------------------------------- + * The rebuild below copies every existing row on every call, which + * makes a named-table ingest O(rows present) per insert — quadratic + * over a feed's lifetime. When the binding is the sole owner of the + * table and no column needs adoption or boxing, append the batch into + * the existing columns instead: ray_vec_append grows in place (the + * buddy allocator extends the block when the space is there), so the + * cost is O(rows appended), amortized — the same profile as the + * vector path. Any gate miss falls through to the rebuild, which + * keeps its copy semantics. + * + * On a mid-batch failure the appended lengths are rolled back, so the + * table keeps its pre-insert value; unlike the rebuild, already-grown + * capacity and dropped accelerator indexes are not restored. */ + bool inplace_ok = inplace_sym >= 0 && tbl->rc == 2 && tbl->mmod == 0 && + !(tbl->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)); + ray_t* live_cols = NULL; + if (inplace_ok) { + live_cols = ((ray_t**)ray_data(tbl))[1]; + if (!live_cols || live_cols->rc != 1 || live_cols->len != ncols) + inplace_ok = false; + } + for (int64_t c = 0; inplace_ok && c < ncols; c++) { + ray_t* col = ((ray_t**)ray_data(live_cols))[c]; + /* col->rc != 1: a shared column would be COW'd inside the append, + * and ray_cow releases the slot's reference — on a mid-append OOM + * the slot would dangle. Sharing also means someone is looking at + * the pre-insert value, which is what the rebuild is for. */ + if (!col || RAY_IS_ERR(col) || col->rc != 1 || + /* An EMPTY LIST column is typeless — the rebuild adopts a + * concrete type from the first payload. A non-empty LIST + * column is genuinely boxed and appends like any other: + * pointer cells, each retained by ray_list_append. */ + (col->type == RAY_LIST && ray_len(col) == 0) || + RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON || + col->mmod != 0 || + (col->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA))) { + inplace_ok = false; + break; + } + /* The rebuild normalizes SYM columns to W64 runtime-domain ids; + * appending into a narrow or store-domain column would not. */ + if (col->type == RAY_SYM && + ((col->attrs & RAY_SYM_W_MASK) != RAY_SYM_W64 || + col->sym_domain != ray_sym_runtime_domain())) { + inplace_ok = false; + break; + } + } + if (inplace_ok) { + ray_t** slots = (ray_t**)ray_data(live_cols); + ray_t* err = NULL; + for (int64_t c = 0; c < ncols && !err; c++) { + ray_t* col = slots[c]; + ray_t* pay = row_elems[c]; + int8_t ct = col->type; + ray_t* res; + if (ct == RAY_LIST) { + /* Boxed column: a table payload supplies a LIST whose cells + * are rows and is spliced; any other row shape boxes its + * payload (or a NULL slot) as one cell — the same contract + * as append_boxed_table_col, minus the copy. */ + if (tbl_row_list) { + if (!pay || RAY_IS_ERR(pay) || pay->type != RAY_LIST) { + res = ray_error("type", "insert: table payload for a LIST column must be LIST"); + } else { + ray_t** cells = (ray_t**)ray_data(pay); + int64_t m = pay->len; + res = col; + for (int64_t k = 0; k < m && !RAY_IS_ERR(res); k++) { + res = ray_list_append(res, cells[k]); + if (!RAY_IS_ERR(res)) { slots[c] = res; col = res; } + } + } + } else { + res = ray_list_append(col, pay); + } + } else if (!pay) { + ray_t* null_atom = ray_typed_null(-ct); + res = append_atom_to_col(col, null_atom); + ray_release(null_atom); + } else if (ray_is_atom(pay)) { + res = append_atom_to_col(col, pay); + } else if (pay->type == ct && ct == RAY_STR) { + bool pay_nulls = payload_may_have_nulls(pay); + res = col; + int64_t m = ray_len(pay); + for (int64_t k = 0; k < m && !RAY_IS_ERR(res); k++) { + int64_t at = res->len; + if (pay_nulls && ray_vec_is_null(pay, k)) { + res = ray_str_vec_append(res, "", 0); + if (!RAY_IS_ERR(res)) ray_vec_set_null(res, at, true); + } else { + size_t slen = 0; + const char* sp = ray_str_vec_get(pay, k, &slen); + res = ray_str_vec_append(res, sp ? sp : "", sp ? slen : 0); + } + if (!RAY_IS_ERR(res)) { slots[c] = res; col = res; } + } + } else if (pay->type == ct && ct == RAY_SYM && + ((pay->attrs & RAY_SYM_W_MASK) != RAY_SYM_W64 || + pay->sym_domain != ray_sym_runtime_domain())) { + /* Narrow or store-domain SYM payload: translate per cell. */ + bool pay_nulls = payload_may_have_nulls(pay); + res = col; + int64_t m = ray_len(pay); + for (int64_t k = 0; k < m && !RAY_IS_ERR(res); k++) { + int64_t sym_val = sym_cell_runtime_id(pay, k); + int64_t at = res->len; + res = ray_vec_append(res, &sym_val); + if (!RAY_IS_ERR(res)) { + slots[c] = res; + col = res; + if (pay_nulls && ray_vec_is_null(pay, k)) + ray_vec_set_null(res, at, true); + } + } + } else if (pay->type == ct) { + /* Same-typed fixed-width vector (SYM already W64 runtime + * here, so ids are verbatim): one reserve, one memcpy. + * Raw cells carry their null sentinels; propagate the + * flag with them. */ + res = ray_vec_append_raw(col, ray_data(pay), ray_len(pay)); + if (!RAY_IS_ERR(res) && payload_may_have_nulls(pay)) + res->attrs |= RAY_ATTR_HAS_NULLS; + } else if (ray_is_vec(pay) || pay->type == RAY_LIST) { + /* Differently-typed vector or generic list: coerce cell by + * cell, exactly like the rebuild does. */ + res = col; + int64_t m = ray_len(pay); + for (int64_t k = 0; k < m && !RAY_IS_ERR(res); k++) { + int alloc = 0; + ray_t* e = collection_elem(pay, k, &alloc); + if (!e) { + ray_t* na = ray_typed_null(-ct); + res = append_atom_to_col(res, na); + ray_release(na); + } else { + res = append_atom_to_col(res, e); + if (alloc) ray_release(e); + } + if (!RAY_IS_ERR(res)) { slots[c] = res; col = res; } + } + } else { + res = append_atom_to_col(col, pay); + } + if (RAY_IS_ERR(res)) err = res; + else slots[c] = res; + } + if (err) { + /* Roll the lengths back so the binding keeps its pre-insert + * value. The append helpers leave the passed vector alive on + * failure, so every slot pointer is still valid. Boxed cells + * were retained on append — release them before truncating. */ + for (int64_t c = 0; c < ncols; c++) { + ray_t* col = slots[c]; + if (col->type == RAY_LIST) { + ray_t** cells = (ray_t**)ray_data(col); + for (int64_t k = nrows; k < col->len; k++) + if (cells[k]) ray_release(cells[k]); + } + col->len = nrows; + } + } + if (dict_vals) { + ray_t** dv = (ray_t**)ray_data(dict_vals); + for (int64_t c = 0; c < ncols; c++) if (dv[c]) ray_release(dv[c]); + dict_vals->len = 0; + ray_free(dict_vals); + } + if (tbl_row_list) { + ray_t** trl = (ray_t**)ray_data(tbl_row_list); + for (int64_t c = 0; c < ncols; c++) if (trl[c]) ray_release(trl[c]); + tbl_row_list->len = 0; + ray_free(tbl_row_list); + } + ray_release(tbl); + ray_release(row_orig); + return err ? err : ray_sym(inplace_sym); + } + ray_t* result = ray_table_new(ncols); if (RAY_IS_ERR(result)) return result; @@ -15102,6 +15350,30 @@ static void wj_scan_fn(void* ctx_, uint32_t worker_id, int64_t start, int64_t en * * The legacy asof fall-through ((window-join L R [keys] time)) is mode-agnostic. */ +static int8_t join_i64_eq_key_type(ray_t* col) { + if (!col) return 0; + int8_t t = col->type; + if (RAY_IS_PARTED(t)) t = (int8_t)RAY_PARTED_BASETYPE(t); + return t; +} + +static bool join_i64_eq_key_supported(int8_t t) { + switch (t) { + case RAY_BOOL: + case RAY_U8: + case RAY_I16: + case RAY_I32: + case RAY_I64: + case RAY_DATE: + case RAY_TIME: + case RAY_TIMESTAMP: + case RAY_SYM: + return true; + default: + return false; + } +} + static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { if (n < 4) return ray_error("domain", "window-join: expects keys, intervals, left and right tables, got %lld args", (long long)n); @@ -15172,20 +15444,17 @@ static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { for (int i = 0; i < 4; i++) ray_release(eargs[i]); return ray_error("domain", "window-join: equality key column not found in both tables"); } - /* STR equality-key columns are silently mismatched: window-join - * sorts and probes eq cells through read_col_i64, which has no - * RAY_STR case (it reads one raw byte per row), so once there are - * enough distinct keys the byte collisions cross-contaminate - * groups and the aggregates are WRONG. Decline both sides — the - * base equi-join has a STR-aware kernel, these window kernels do - * not. */ - int8_t lct = left_eq[e]->type, rct = right_eq[e]->type; - if (RAY_IS_PARTED(lct)) lct = (int8_t)RAY_PARTED_BASETYPE(lct); - if (RAY_IS_PARTED(rct)) rct = (int8_t)RAY_PARTED_BASETYPE(rct); - if (lct == RAY_STR || rct == RAY_STR) { + /* Equality keys in the window kernels are sorted/probed through + * read_col_i64. Decline any type that reader cannot represent + * instead of silently comparing the wrong bytes. */ + int8_t lct = join_i64_eq_key_type(left_eq[e]); + int8_t rct = join_i64_eq_key_type(right_eq[e]); + if (!join_i64_eq_key_supported(lct) || + !join_i64_eq_key_supported(rct)) { scratch_free(eq_hdr); for (int i = 0; i < 4; i++) ray_release(eargs[i]); - return ray_error("nyi", "window-join: string equality key columns are not supported"); + return ray_error("nyi", "window-join: equality key column types %s and %s are not supported", + ray_type_name(lct), ray_type_name(rct)); } } @@ -15749,15 +16018,15 @@ static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { if (!eq_ops[i]) { scratch_free(eqops_hdr); ray_graph_free(g); if (_bxeq) ray_release(_bxeq); return ray_error("domain", "window-join: equality key column not found"); } ray_t* lcol = ray_table_get_col(left_tbl, eq_elems[i]->i64); ray_t* rcol = ray_table_get_col(right_tbl, eq_elems[i]->i64); - int8_t lct = lcol ? lcol->type : (int8_t)0; - int8_t rct = rcol ? rcol->type : (int8_t)0; - if (RAY_IS_PARTED(lct)) lct = (int8_t)RAY_PARTED_BASETYPE(lct); - if (RAY_IS_PARTED(rct)) rct = (int8_t)RAY_PARTED_BASETYPE(rct); - if (lct == RAY_STR || rct == RAY_STR) { + int8_t lct = join_i64_eq_key_type(lcol); + int8_t rct = join_i64_eq_key_type(rcol); + if (!join_i64_eq_key_supported(lct) || + !join_i64_eq_key_supported(rct)) { scratch_free(eqops_hdr); ray_graph_free(g); if (_bxeq) ray_release(_bxeq); - return ray_error("nyi", "window-join: string equality key columns are not supported"); + return ray_error("nyi", "window-join: equality key column types %s and %s are not supported", + ray_type_name(lct), ray_type_name(rct)); } } @@ -15869,22 +16138,19 @@ static ray_t* ray_asof_join_core(ray_t* keys_vec, ray_t* left_tbl, ray_t* right_ if (!nm) { scratch_free(eqops_hdr); ray_graph_free(g); if (_bxk) ray_release(_bxk); return ray_error("domain", "asof-join: unknown equality key symbol"); } eq_ops[i] = ray_scan(g, ray_str_ptr(nm)); if (!eq_ops[i]) { scratch_free(eqops_hdr); ray_graph_free(g); if (_bxk) ray_release(_bxk); return ray_error("domain", "asof-join: equality key column not found"); } - /* STR equality-key columns are silently mismatched: the asof kernel - * reads eq cells through read_col_i64 (asof_eq_lread), which has no - * RAY_STR case, so string keys compare as raw bytes and yield WRONG - * results (a key that should match can null out). The base equi-join - * has a separate STR-aware kernel; asof does not, so decline both - * sides rather than return corrupt data. */ + /* The asof kernel reads equality keys through read_col_i64 + * (asof_eq_lread). Decline types it cannot represent instead of + * returning silently corrupted matches. */ ray_t* lcol = ray_table_get_col(left_tbl, eq_syms[i]->i64); ray_t* rcol = ray_table_get_col(right_tbl, eq_syms[i]->i64); - int8_t lct = lcol ? lcol->type : (int8_t)0; - int8_t rct = rcol ? rcol->type : (int8_t)0; - if (RAY_IS_PARTED(lct)) lct = (int8_t)RAY_PARTED_BASETYPE(lct); - if (RAY_IS_PARTED(rct)) rct = (int8_t)RAY_PARTED_BASETYPE(rct); - if (lct == RAY_STR || rct == RAY_STR) { + int8_t lct = join_i64_eq_key_type(lcol); + int8_t rct = join_i64_eq_key_type(rcol); + if (!join_i64_eq_key_supported(lct) || + !join_i64_eq_key_supported(rct)) { scratch_free(eqops_hdr); ray_graph_free(g); if (_bxk) ray_release(_bxk); - return ray_error("nyi", "asof-join: string equality key columns are not supported"); + return ray_error("nyi", "asof-join: equality key column types %s and %s are not supported", + ray_type_name(lct), ray_type_name(rct)); } } diff --git a/src/ops/sort.c b/src/ops/sort.c index b50abf921..fb9249904 100644 --- a/src/ops/sort.c +++ b/src/ops/sort.c @@ -40,7 +40,8 @@ int sort_cmp(const sort_cmp_ctx_t* ctx, int64_t a, int64_t b) { int cmp = 0; int null_cmp = 0; int desc = ctx->desc ? ctx->desc[k] : 0; - int nf = ctx->nulls_first ? ctx->nulls_first[k] : desc; + int nf = ctx->nulls_first ? ctx->nulls_first[k] + : sort_nulls_first((uint8_t)desc); /* Check null bitmap for both elements */ int a_null = ray_vec_is_null(col, a); @@ -2278,7 +2279,8 @@ static void radix_decode_into(void* dst, int8_t type, const uint64_t* sorted_key * cols: array of n_cols vectors (sort keys, most significant first) * descs: array of n_cols flags (0=asc, 1=desc), or NULL for all-asc * nulls_first: array of n_cols flags (0=nulls last, 1=nulls first), or NULL - * for default convention (nulls last for asc, nulls first for desc) + * to take the default from sort_nulls_first — a null is the + * smallest value, so nulls first for asc, last for desc * n_cols: number of sort key columns (composite radix encode is used * up to 16 keys; wider sorts take the merge-sort fallback) * nrows: number of rows in each column @@ -2319,7 +2321,7 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first * internally; skips the rest of sort_indices_ex on success. */ if (n_cols == 1 && cols[0]->type == RAY_STR) { bool desc = descs ? descs[0] : 0; - bool nf = nulls_first ? nulls_first[0] : !desc; + bool nf = nulls_first ? nulls_first[0] : sort_nulls_first((uint8_t)desc); if (sort_str_msd_inplace(indices, nrows, cols[0], desc, nf)) { sorted_idx = indices; iota_done = true; @@ -2397,9 +2399,8 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first (size_t)nrows * sizeof(uint64_t)); if (keys) { bool desc = descs ? descs[0] : 0; - /* Null = minimum value. - * ASC → nulls first, DESC → nulls last. */ - bool nf = nulls_first ? nulls_first[0] : !desc; + bool nf = nulls_first ? nulls_first[0] + : sort_nulls_first((uint8_t)desc); radix_encode_ctx_t enc = { .keys = keys, .indices = indices, .data = ray_data(cols[0]), @@ -2577,10 +2578,30 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first uint16_t total_bits = 0; bool fits = true; + /* A float null is NaN, and the composite encode packs a + * double by flipping its bits — which puts NaN above every + * real number, i.e. last on ascending, whatever + * sort_nulls_first says. The other types carry a sentinel + * that already lands where the rule wants it (INT64_MIN is + * the smallest), so only F64 disagrees. Rather than teach + * the packing a second placement, hand a null-bearing float + * key to the rank-then-compose fallback, which ranks + * through sort_indices_ex and is null-aware. Leaving it in + * the direct encode is what made a multi-key sort place + * floats one way below 64 rows and the other way above. */ + bool nullable_f64_key = false; + for (uint32_t k = 0; k < n_cols; k++) + if (cols[k]->type == RAY_F64 && + (cols[k]->attrs & RAY_ATTR_HAS_NULLS)) { + nullable_f64_key = true; + break; + } + ray_pool_t* mk_prescan_pool = (nrows >= SMALL_POOL_THRESHOLD) ? pool : NULL; - if (has_wide_key) { + if (has_wide_key || nullable_f64_key) { /* RAY_STR / RAY_GUID can't be packed into a composite - * uint64 key. Force the rank-then-compose fallback. */ + * uint64 key, and a nullable float must not be. Force + * the rank-then-compose fallback. */ total_bits = UINT16_MAX; fits = false; } else if (n_cols <= MK_PRESCAN_MAX_KEYS && mk_prescan_pool) { @@ -2616,9 +2637,11 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first } mins[k] = kmin; maxs[k] = kmax; - uint64_t range = (uint64_t)(kmax - kmin); + /* Unsigned subtraction: kmin can be the i64 null + * sentinel, and kmax - kmin then overflows i64. */ + uint64_t range = (uint64_t)kmax - (uint64_t)kmin; uint8_t bits = 1; - while (((uint64_t)1 << bits) <= range && bits < 64) + while (bits < 64 && ((uint64_t)1 << bits) <= range) bits++; total_bits = (uint16_t)(total_bits + bits); } @@ -2678,9 +2701,11 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first mins[k] = kmin; maxs[k] = kmax; - uint64_t range = (uint64_t)(kmax - kmin); + /* Unsigned subtraction: kmin can be the i64 null + * sentinel, and kmax - kmin then overflows i64. */ + uint64_t range = (uint64_t)kmax - (uint64_t)kmin; uint8_t bits = 1; - while (((uint64_t)1 << bits) <= range && bits < 64) + while (bits < 64 && ((uint64_t)1 << bits) <= range) bits++; total_bits = (uint16_t)(total_bits + bits); } @@ -2712,7 +2737,8 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first uint32_t* rank_max = (uint32_t*)(rank_buf + rank_off_max); for (uint32_t k = 0; k < n_cols && rank_ok; k++) { uint8_t kdesc = descs ? descs[k] : 0; - uint8_t knf = nulls_first ? nulls_first[k] : !kdesc; + uint8_t knf = nulls_first ? nulls_first[k] + : sort_nulls_first(kdesc); ray_t* col_arg[1] = { cols[k] }; uint8_t desc_arg[1] = { kdesc }; uint8_t nf_arg[1] = { knf }; @@ -2910,22 +2936,9 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first if (!radix_done) { if (!iota_done) for (int64_t i = 0; i < nrows; i++) indices[i] = i; - /* Null = minimum value. - * ASC → nulls first (nf=1), DESC → nulls last (nf=0). */ - ray_t* default_nf_hdr = NULL; - if (!nulls_first) { - uint8_t* default_nf = (uint8_t*)scratch_alloc(&default_nf_hdr, n_cols); - if (!default_nf) { - for (uint32_t k = 0; k < n_cols; k++) - scratch_free(enum_rank_hdrs[k]); - scratch_free(enum_rank_hdrs_hdr); - scratch_free(indices_hdr); - return ray_error("oom", NULL); - } - for (uint32_t k = 0; k < n_cols; k++) - default_nf[k] = descs ? !descs[k] : 1; - nulls_first = default_nf; - } + /* No default array is built: a NULL nulls_first already means the + * default for each key's direction, and the comparator asks + * sort_nulls_first for it. */ sort_cmp_ctx_t cmp_ctx = { .vecs = cols, .desc = descs, @@ -2946,7 +2959,6 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first for (uint32_t k = 0; k < n_cols; k++) scratch_free(enum_rank_hdrs[k]); scratch_free(enum_rank_hdrs_hdr); - scratch_free(default_nf_hdr); scratch_free(indices_hdr); return ray_error("oom", NULL); } @@ -2990,7 +3002,6 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first scratch_free(tmp_hdr); } - scratch_free(default_nf_hdr); } str_msd_done:; @@ -3389,10 +3400,12 @@ ray_t* topk_take_vec(ray_t* v, int64_t k, uint8_t desc) { return desc ? ray_desc_fn(v) : ray_asc_fn(v); } - /* Try the bounded-heap fast path. Default nulls-last for ASC, - * nulls-first for DESC (matches sort defaults so the gathered - * non-null prefix is always K elements when nulls fit). */ - uint8_t nf = desc ? 1 : 0; + /* Try the bounded-heap fast path. It takes the placement from the + * shared rule, because the k >= len branch above hands the whole job + * to the full sort, which uses that rule: spelling out a different + * one here would put a null-bearing vector's nulls at one end while + * k < len and the other once k reaches it. */ + uint8_t nf = sort_nulls_first(desc); ray_t* idx = topk_indices_single(v, desc, nf, len, k); if (idx && !RAY_IS_ERR(idx)) { const int64_t* idata = (const int64_t*)ray_data(idx); @@ -3531,19 +3544,17 @@ ray_t* exec_sort(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t limit) { uint8_t desc = ext->sort.desc ? ext->sort.desc[0] : 0; uint8_t nf = ext->sort.nulls_first ? ext->sort.nulls_first[0] - : !desc; + : sort_nulls_first(desc); ray_t* topk_res = ray_topk_table(tbl, key_cols[0], desc, nf, limit); if (topk_res && !RAY_IS_ERR(topk_res)) return topk_res; if (topk_res && RAY_IS_ERR(topk_res)) ray_release(topk_res); } else { - /* Default nulls-first to !desc per-key when caller - * didn't supply a vector. */ uint8_t nfs[16]; for (uint32_t k = 0; k < n_sort; k++) { uint8_t d = ext->sort.desc ? ext->sort.desc[k] : 0; nfs[k] = ext->sort.nulls_first ? ext->sort.nulls_first[k] - : !d; + : sort_nulls_first(d); } ray_t* topk_res = ray_topk_table_multi(tbl, key_cols, ext->sort.desc, nfs, n_sort, limit); @@ -3605,11 +3616,10 @@ ray_t* exec_sort(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t limit) { * g->selection is always NULL here (exec.c compacts it before calling * exec_sort); the gate still checks defensively. * - * FUTURE TRAP: lifting the null-free restriction (idx_fresh_nonull) - * requires reconciling nulls placement — the index perm was built with - * sort_indices_ex's default (nulls FIRST), while ray_sort_op defaults - * to nulls LAST for ASC. Reusing the perm for a null-bearing column - * without that reconciliation silently misplaces the null block. */ + * The null-free restriction (idx_fresh_nonull) is no longer about where + * nulls land: the perm and the sort now place them the same way, since + * both take the default from sort_nulls_first. It stands only on what + * the index itself guarantees. */ uint64_t* sorted_keys = NULL; ray_t* sorted_keys_hdr = NULL; ray_t* idx_vec; @@ -3941,7 +3951,13 @@ static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) * read and a volatile flag load per row; here adjacent sym ids * compare directly (equal ids on ~all rows of a sorted table — the * string comparison only runs at run boundaries), the secondary key - * reads raw i64, and the bail flag is polled per 4096-row block. */ + * reads raw i64, and the bail flag is polled per 4096-row block. + * + * Callers reach this only for null-free keys (ray_key_cols_sorted rejects + * HAS_NULLS up front, including for SYM/STR). That is not squeamishness + * about in-band nulls: this loop ranks sym 0 by its domain string, i.e. + * smallest, whereas the real sort places nulls by the `nulls_first` flag + * independently of payload. See the note on ray_key_cols_sorted. */ if (!c->descending && c->n_keys == 2 && c->key_cols[0]->type == RAY_SYM && (c->key_cols[1]->type == RAY_I64 || @@ -4009,6 +4025,21 @@ static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) * null-free integer-family / SYM keys are decidable — anything else (float, * STR/LIST, or a HAS_NULLS column) returns false so the caller must NOT * assume sortedness (float NaN / null placement belong to the real sort). + * + * The HAS_NULLS rejection stands even for SYM/STR, whose nulls are IN-BAND + * ordinary values (sym id 0 is a real dictionary entry — the empty string at + * position 0 of every symfile; a STR null is a zero-length descriptor). That + * in-band property is what lets the fused predicate evaluator compare them for + * EQUALITY (see fp_col_supported_op in fused_pred.c), but it does NOT extend to + * ORDER: the sort kernels give nulls a dedicated order class placed by the + * `nulls_first` flag — sort_cmp answers `nf ? -1 : 1` for a null operand + * without looking at the payload, and the single-key path partitions nulls out + * and rotates them to the requested end. A payload-only scan such as this one + * ranks sym 0 as the smallest string, which now agrees with the default policy + * (sort_nulls_first: a null is the smallest value) but not with a caller that + * asked for the other end. So the rejection is conservatism about the + * requested placement, not an undecidable ordering — a caller that pins the + * default could decide it. * O(nrows) with early bail on the first violation; a 0/1-row column is * trivially sorted. Used by the parted ORDER BY streaming path in query.c * to verify each partition is internally sorted at O(partition), never a diff --git a/src/ops/string.c b/src/ops/string.c index 481d28b32..4d474dd33 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -27,6 +27,7 @@ #include "ops/rowsel.h" #include "core/pool.h" #include "lang/format.h" /* ray_type_name (error context) */ +#include "lang/internal.h" /* ray_like_fn (list-of-strings delegate) */ /* ============================================================================ * OP_LIKE: glob pattern matching on STR / SYM columns. See ops/glob.[ch]. @@ -563,6 +564,24 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { if (!input || RAY_IS_ERR(input)) { if (pat_v && !RAY_IS_ERR(pat_v)) ray_release(pat_v); return input; } if (!pat_v || RAY_IS_ERR(pat_v)) { ray_release(input); return pat_v; } + int8_t in_type = input->type; + bool in_parted = RAY_IS_PARTED(in_type); + int8_t base_type = in_parted ? (int8_t)RAY_PARTED_BASETYPE(in_type) : in_type; + + /* Shapes this executor doesn't own — scalar subjects, list-of-atom + * columns (the legacy STRL splayed-load shape), unsupported types — + * delegate to the direct builtin BEFORE reading input->len or + * allocating: an atom's SSO bytes alias ->len, so the result alloc + * below would request a garbage capacity, and the old fallthrough + * memset made unsupported predicates silently match nothing. */ + bool vec_shape = in_parted ? (base_type == RAY_STR || RAY_IS_SYM(base_type)) + : (in_type == RAY_STR || RAY_IS_SYM(in_type)); + if (!vec_shape) { + ray_t* r = ray_like_fn(input, pat_v); + ray_release(input); ray_release(pat_v); + return r; + } + /* Get pattern string */ const char* pat_str = ray_str_ptr(pat_v); size_t pat_len = ray_str_len(pat_v); @@ -574,9 +593,6 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { ray_glob_compiled_t pc = ray_glob_compile(pat_str, pat_len); bool use_simple = pc.shape != RAY_GLOB_SHAPE_NONE; - int8_t in_type = input->type; - bool in_parted = RAY_IS_PARTED(in_type); - int8_t base_type = in_parted ? (int8_t)RAY_PARTED_BASETYPE(in_type) : in_type; int64_t len = in_parted ? parted_row_count(input) : input->len; ray_t* result = ray_vec_new(RAY_BOOL, len); if (!result || RAY_IS_ERR(result)) { @@ -738,8 +754,6 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { : ray_glob_match(sp, sl, pat_str, pat_len)) ? 1 : 0; } } - } else { - memset(dst, 0, (size_t)len); } ray_release(input); ray_release(pat_v); @@ -748,6 +762,57 @@ ray_t* exec_like(ray_graph_t* g, ray_op_t* op) { /* Case-insensitive LIKE — same syntax as `like`, ASCII-fold both sides. */ +/* ILIKE over the shapes exec_ilike's vector loops don't own — scalar + * subjects, list-of-atom columns (the legacy STRL splayed-load shape) — + * plus the type error for everything else. ilike has no direct builtin + * to delegate to, so this mirrors ray_like_fn's atom and list branches + * with the case-folded matcher. */ +static ray_t* ilike_non_vec(ray_t* input, const char* pat_str, size_t pat_len) { + if (input->type == -RAY_STR || input->type == -RAY_SYM) { + ray_t* sym_str = NULL; + const char* s; size_t sl; + if (input->type == -RAY_SYM) { + sym_str = ray_sym_str(input->i64); + s = sym_str ? ray_str_ptr(sym_str) : ""; + sl = sym_str ? ray_str_len(sym_str) : 0; + } else { + s = ray_str_ptr(input); + sl = ray_str_len(input); + } + bool m = ray_glob_match_ci(s, sl, pat_str, pat_len); + if (sym_str) ray_release(sym_str); + return ray_bool(m); + } + if (input->type == RAY_LIST) { + int64_t n = input->len; + ray_t* result = ray_vec_new(RAY_BOOL, n); + if (!result || RAY_IS_ERR(result)) return result; + result->len = n; + uint8_t* out = (uint8_t*)ray_data(result); + ray_t** items = (ray_t**)ray_data(input); + for (int64_t i = 0; i < n; i++) { + ray_t* it = items[i]; + ray_t* sym_str = NULL; + const char* s; size_t sl; + if (it && it->type == -RAY_STR) { + s = ray_str_ptr(it); + sl = ray_str_len(it); + } else if (it && it->type == -RAY_SYM) { + sym_str = ray_sym_str(it->i64); + s = sym_str ? ray_str_ptr(sym_str) : ""; + sl = sym_str ? ray_str_len(sym_str) : 0; + } else { + ray_release(result); + return ray_error("type", "ilike: list items must be string or symbol atoms"); + } + out[i] = ray_glob_match_ci(s, sl, pat_str, pat_len) ? 1 : 0; + if (sym_str) ray_release(sym_str); + } + return result; + } + return ray_error("type", "ilike: expects string or symbol"); +} + ray_t* exec_ilike(ray_graph_t* g, ray_op_t* op) { ray_t* input = exec_node(g, op_child(g, op, 0)); ray_t* pat_v = exec_node(g, op_child(g, op, 1)); @@ -757,6 +822,16 @@ ray_t* exec_ilike(ray_graph_t* g, ray_op_t* op) { const char* pat_str = ray_str_ptr(pat_v); size_t pat_len = ray_str_len(pat_v); + int8_t in_type = input->type; + /* Dispatch before reading input->len or allocating — an atom's SSO + * bytes alias ->len, and the old fallthrough memset made ilike over + * an unsupported column type silently match nothing. */ + if (in_type != RAY_STR && !RAY_IS_SYM(in_type)) { + ray_t* r = ilike_non_vec(input, pat_str, pat_len); + ray_release(input); ray_release(pat_v); + return r; + } + int64_t len = input->len; ray_t* result = ray_vec_new(RAY_BOOL, len); if (!result || RAY_IS_ERR(result)) { @@ -766,7 +841,6 @@ ray_t* exec_ilike(ray_graph_t* g, ray_op_t* op) { result->len = len; uint8_t* dst = (uint8_t*)ray_data(result); - int8_t in_type = input->type; if (in_type == RAY_STR) { const ray_str_t* elems; const char* pool; str_resolve(input, &elems, &pool); @@ -820,8 +894,6 @@ ray_t* exec_ilike(ray_graph_t* g, ray_op_t* op) { dst[i] = ray_glob_match_ci(ray_str_ptr(s), ray_str_len(s), pat_str, pat_len) ? 1 : 0; } } - } else { - memset(dst, 0, (size_t)len); } ray_release(input); ray_release(pat_v); @@ -921,13 +993,24 @@ ray_t* exec_strlen(ray_graph_t* g, ray_op_t* op) { if (input->type == RAY_STR) { const ray_str_t* elems; const char* pool; str_resolve(input, &elems, &pool); - for (int64_t i = 0; i < len; i++) - dst[i] = (int64_t)elems[i].len; + for (int64_t i = 0; i < len; i++) { + if (ray_vec_is_null(input, i)) { + dst[i] = NULL_I64; + result->attrs |= RAY_ATTR_HAS_NULLS; + } else { + dst[i] = (int64_t)elems[i].len; + } + } } else { for (int64_t i = 0; i < len; i++) { - const char* sp; size_t sl; - sym_elem(input, i, &sp, &sl); - dst[i] = (int64_t)sl; + if (ray_vec_is_null(input, i)) { + dst[i] = NULL_I64; + result->attrs |= RAY_ATTR_HAS_NULLS; + } else { + const char* sp; size_t sl; + sym_elem(input, i, &sp, &sl); + dst[i] = (int64_t)sl; + } } } ray_release(input); diff --git a/src/ops/strop.c b/src/ops/strop.c index 831286c22..224b978cc 100644 --- a/src/ops/strop.c +++ b/src/ops/strop.c @@ -72,9 +72,14 @@ static ray_t* strlen_vec(ray_t* x) { if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); out->len = n; int64_t* dst = (int64_t*)ray_data(out); - /* STR/SYM have no null. */ - for (int64_t i = 0; i < n; i++) - strlen_vec_value(x, i, &dst[i]); + for (int64_t i = 0; i < n; i++) { + if (ray_vec_is_null(x, i)) { + dst[i] = NULL_I64; + out->attrs |= RAY_ATTR_HAS_NULLS; + } else { + strlen_vec_value(x, i, &dst[i]); + } + } return out; } @@ -97,9 +102,11 @@ static ray_t* strlen_mapcommon(ray_t* x) { int64_t off = 0; for (int64_t p = 0; p < counts->len; p++) { int64_t v = 0; - strlen_vec_value(keys, p, &v); /* STR/SYM have no null */ + bool is_null = ray_vec_is_null(keys, p); + if (!is_null) strlen_vec_value(keys, p, &v); for (int64_t r = 0; r < cnt[p]; r++) - dst[off++] = v; + dst[off++] = is_null ? NULL_I64 : v; + if (is_null) out->attrs |= RAY_ATTR_HAS_NULLS; } return out; } @@ -120,9 +127,13 @@ static ray_t* strlen_parted(ray_t* x) { for (int64_t s = 0; s < x->len; s++) { ray_t* seg = segs[s]; if (!seg || RAY_IS_ERR(seg)) continue; - /* STR/SYM have no null. */ for (int64_t i = 0; i < seg->len; i++) { - strlen_vec_value(seg, i, &dst[off]); + if (ray_vec_is_null(seg, i)) { + dst[off] = NULL_I64; + out->attrs |= RAY_ATTR_HAS_NULLS; + } else { + strlen_vec_value(seg, i, &dst[off]); + } off++; } } @@ -130,6 +141,8 @@ static ray_t* strlen_parted(ray_t* x) { } ray_t* ray_strlen_fn(ray_t* x) { + if (ray_is_atom(x) && RAY_ATOM_IS_NULL(x)) + return ray_typed_null(-RAY_I64); int64_t len = 0; if (strlen_atom_value(x, &len)) return ray_i64(len); if (ray_is_vec(x)) return strlen_vec(x); @@ -1079,6 +1092,31 @@ ray_t* ray_like_fn(ray_t* x, ray_t* pattern) { return result; } + /* List of string/symbol atoms — the shape splayed string columns + * load as (col_load_str_list). Mirrors str-find's list branch. */ + if (x->type == RAY_LIST) { + int64_t n = x->len; + ray_t* result = ray_vec_new(RAY_BOOL, n); + if (RAY_IS_ERR(result)) return result; + result->len = n; + uint8_t* out = (uint8_t*)ray_data(result); + ray_t** items = (ray_t**)ray_data(x); + for (int64_t i = 0; i < n; i++) { + if ((i & (RAY_MORSEL_ELEMS - 1)) == 0 && pool_cancelled(NULL)) { + ray_release(result); + return ray_error("cancel", NULL); + } + const char* s; size_t sl; + if (!str_atom_bytes(items[i], &s, &sl, NULL)) { + ray_release(result); + return ray_error("type", "like: list items must be string or symbol atoms"); + } + out[i] = (use_simple ? ray_glob_match_compiled(&pc, s, sl) + : ray_glob_match(s, sl, pat, pat_len)) ? 1 : 0; + } + return result; + } + return ray_error("type", "like: expects string or symbol"); } diff --git a/src/ops/system.c b/src/ops/system.c index 4d0751d39..c3fe450ef 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -784,6 +784,9 @@ ray_t* ray_mem_ts_fn(ray_t** args, int64_t n) { ray_t* ray_gc_fn(ray_t** args, int64_t n) { (void)args; (void)n; ray_heap_gc(); + /* Same statement-boundary rule as the REPL: an explicit maintenance + * call is also a chance to notice the process has gone quiet. */ + ray_heap_decay(); return ray_i64(0); } @@ -1435,8 +1438,16 @@ ray_t* ray_hopen_fn(ray_t** args, int64_t n) { if (part_lens[1] >= sizeof(port_str)) return ray_error("domain", ".ipc.open port field too long, got %lld bytes", (long long)part_lens[1]); memcpy(port_str, parts[1], part_lens[1]); port_str[part_lens[1]] = '\0'; - int port = atoi(port_str); - if (port <= 0 || port > 65535) return ray_error("domain", ".ipc.open port must be in 1..65535, got %d", port); + /* Strict parse: atoi("1abc") returns 1, silently accepting a malformed + * port with a numeric prefix. Require the whole field to be digits. */ + char* endp; + errno = 0; + long port_l = strtol(port_str, &endp, 10); + if (endp == port_str || *endp != '\0') + return ray_error("domain", ".ipc.open port must be numeric 1..65535, got \"%s\"", port_str); + if (errno == ERANGE || port_l <= 0 || port_l > 65535) + return ray_error("domain", ".ipc.open port must be in 1..65535, got \"%s\"", port_str); + int port = (int)port_l; char user[128] = ""; char password[128] = ""; diff --git a/src/ops/window.c b/src/ops/window.c index 78f154d35..f0b526f1b 100644 --- a/src/ops/window.c +++ b/src/ops/window.c @@ -1006,7 +1006,13 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { .type = sort_vecs[0]->type, .col_attrs = sort_vecs[0]->attrs, .desc = sort_descs[0], - .nulls_first = sort_descs[0], /* default: NULLS FIRST for DESC */ + /* The other two window sort paths take the default + * from sort_nulls_first via a NULL nulls_first, and + * which of the three runs is decided by the row count. + * Spelling the rule out here instead would put a + * window's nulls at one end below 64 rows and the + * other end above it. */ + .nulls_first = sort_nulls_first(sort_descs[0]), .enum_rank = enum_ranks[0], .n_keys = 1, }; if (sk_pool) diff --git a/src/store/col.c b/src/store/col.c index d36855d59..ab99a864c 100644 --- a/src/store/col.c +++ b/src/store/col.c @@ -24,6 +24,7 @@ #include "col.h" #include "core/platform.h" #include "mem/heap.h" +#include "mem/sys.h" /* ray_sys_alloc — the shared-mapping descriptor */ #include "store/serde.h" #include "store/fileio.h" #include "table/sym.h" @@ -589,6 +590,11 @@ static ray_t* col_read_recursive(const uint8_t** pp, size_t* remaining) { ray_release(col); /* table_add_col retains */ if (!tbl || RAY_IS_ERR(tbl)) return tbl; } + ray_t* shape_err = ray_table_validate_rectangular(tbl, "col load table"); + if (shape_err) { + ray_release(tbl); + return shape_err; + } return tbl; } @@ -916,6 +922,12 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { memset(&pool_header, 0, sizeof(pool_header)); if (vec->str_pool && !RAY_IS_ERR(vec->str_pool)) { memcpy(&pool_header, vec->str_pool, 32); + /* aux is runtime-only state and one of its arms is a live + * heap pointer — the shared-mapping descriptor a mapped pool + * carries. Only bytes 16-31 were being scrubbed, so that + * address went to disk verbatim and survived into the next + * generation of the file. */ + memset(pool_header.aux, 0, 16); } pool_header.mmod = 0; pool_header.order = 0; @@ -1080,7 +1092,15 @@ ray_err_t ray_col_save_sym_encoded(ray_t* vec, const char* path, /* Same-domain saves preserve positions, hence order; re-encoding * from another domain reorders ids — drop SORTED then. */ uint8_t keep_sorted = (src == target) ? (vec->attrs & RAY_ATTR_SORTED) : 0; - header.attrs = (uint8_t)(w | keep_sorted); + /* attrs is REBUILT here rather than inherited, because the width bits + * change with the target domain's size. Every other persisted bit has + * to be carried across explicitly: HAS_NULLS is one, and forgetting it + * silently dropped canonical sym-0 nulls on every splayed SYM column + * (issue #416) — an all-empty SYM column round-tripped as attrs 0. + * Re-encoding cannot change WHETHER a null is present: position 0 of + * any domain is the empty symbol, so a sym-0 cell stays sym-0. */ + header.attrs = (uint8_t)(w | keep_sorted | + (vec->attrs & RAY_ATTR_HAS_NULLS)); memset(header.aux, 0, 16); /* domain ptr is runtime-only state; * aux reserved (postponed index), never * the version (lives in `order` above). */ @@ -1611,11 +1631,41 @@ static ray_t* col_mmap_impl(const char* path, struct ray_sym_domain_s* dom, if (vec->type == RAY_STR) { ray_t* pool = (ray_t*)((char*)cm.mapped + cm.str_pool_offset); - pool->mmod = 2; pool->order = 0; /* Untrusted disk attrs — mask, see COL_DISK_ATTRS_MASK. */ pool->attrs &= COL_DISK_ATTRS_MASK; ray_atomic_store(&pool->rc, 1); + + /* The column and its pool are one mapping, and a gathered result + * shares the pool by reference — so the region must outlive + * whichever of them is freed first. The pool owns it; the column + * holds an ordinary reference to the pool and unmaps nothing. + * Without this the column's free took the pool's bytes with it and + * every selection over a mapped string column read freed memory. */ + /* Two references: one for the pool, one for the column. The column + * needs its own because its pool pointer is not permanent — + * str_pool_cow swaps in a heap copy before mutating a mapped + * column, and that release must not be the one that unmaps the + * region the column is standing in. Until such a swap the column + * reaches the descriptor through the pool, so nothing is + * registered here; str_pool_cow registers the column when it takes + * that path away. */ + ray_file_map_t* m = (ray_file_map_t*)ray_sys_alloc(sizeof(*m)); + if (!m) { + ray_vm_unmap_file(cm.mapped, cm.mapped_size); + return ray_error("oom", NULL); + } + m->base = cm.mapped; + m->len = cm.mapped_size; + m->rc = 2; + m->next = NULL; + /* Two references: one for the pool, one for the column. The + * column needs its own because its pool pointer is not permanent + * — str_pool_cow swaps in a heap copy before mutating a mapped + * column, and that release must not be the one that unmaps the + * region the column is standing in. */ + pool->mmod = 3; + pool->file_map = m; vec->str_pool = pool; } diff --git a/src/store/journal.c b/src/store/journal.c index 53ea0ad97..0fd94c8c0 100644 --- a/src/store/journal.c +++ b/src/store/journal.c @@ -29,6 +29,7 @@ #include "fileio.h" #include "serde.h" #include "core/ipc.h" +#include "core/timer.h" #include "lang/eval.h" #include "lang/env.h" #include "mem/sys.h" @@ -56,12 +57,14 @@ static struct { char base[RAY_JOURNAL_PATH_MAX]; char log_path[RAY_JOURNAL_PATH_MAX]; bool in_replay; + int64_t log_gen; /* live log's generation id, 0 = legacy/unknown */ } g_journal = { .mode = RAY_JOURNAL_OFF, .fp = NULL, .base = {0}, .log_path = {0}, .in_replay = false, + .log_gen = 0, }; /* ── helpers ──────────────────────────────────────────────────────── */ @@ -81,6 +84,57 @@ static bool file_exists(const char* path) { #endif } +/* ── log generation preamble (#420) ────────────────────────────────── + * + * Snapshot-then-roll is two renames that are individually but not + * jointly atomic. A crash between them leaves a fresh .qdb next + * to the OLD .log whose entries are already baked into that + * snapshot; replaying it applies every entry twice (entries are + * arbitrary expressions — not idempotent). The same happens without a + * crash when the roll's rename fails and the old log is reopened for + * append. + * + * The fix is identity, not ordering: a fresh log starts with a 16-byte + * preamble carrying a generation id, and the snapshot records inside + * the .qdb which (generation, byte length) it covers. Recovery then + * replays the live log only PAST the covered offset when the ids + * match — a crash in the window replays nothing; the roll-failure + * append path replays exactly the post-snapshot tail. A log without + * the preamble (pre-#420) keeps today's full-replay behavior. + * + * The preamble cannot be confused with a frame: entries start with + * RAY_SERDE_PREFIX, not this magic. */ + +#define RAY_JLOG_MAGIC "RAYJLG1" /* 7 chars + NUL = 8 bytes */ +#define RAY_JLOG_PREAMBLE 16 + +/* The sym key the snapshot dict reserves for the coverage marker; the + * recovery bind loop skips it. Value: I64 vec [generation, bytes]. */ +#define RAY_JLOG_COVER_KEY ".journal.covered" + +/* Probe a log file's preamble. Returns the byte offset where frames + * start (0 for a legacy headerless log) and sets *out_gen (0 legacy). */ +static int64_t jlog_probe(const char* path, int64_t* out_gen) { + if (out_gen) *out_gen = 0; + FILE* f = fopen(path, "rb"); + if (!f) return 0; + uint8_t pre[RAY_JLOG_PREAMBLE]; + size_t r = fread(pre, 1, sizeof(pre), f); + fclose(f); + if (r != sizeof(pre) || memcmp(pre, RAY_JLOG_MAGIC, 8) != 0) return 0; + int64_t gen; + memcpy(&gen, pre + 8, sizeof(gen)); + if (out_gen) *out_gen = gen; + return RAY_JLOG_PREAMBLE; +} + +/* Generation ids need only be distinct across the rolls of one journal; + * wall-clock ms with a low sequence salt is ample. */ +static int64_t jlog_fresh_gen(void) { + static int64_t seq = 0; + return (ray_time_now_ms() << 12) | (++seq & 0xFFF); +} + /* Read fixed-size buffer in a loop — fread can short-read on signals. * Returns SIZE_MAX on a real I/O error (vs. clean EOF) so the caller * can distinguish "log ended cleanly" from "torn read mid-frame". The @@ -183,10 +237,15 @@ ray_err_t ray_journal_write_bytes(const ray_ipc_header_t* hdr, return RAY_OK; } -ray_err_t ray_journal_replay(const char* path, - int64_t* out_chunks, - int64_t* out_eval_errors, - ray_jreplay_status_t* out_status) +/* Replay frames from `start_off` (bytes) to EOF. The offset is either + * the preamble size or the snapshot's covered length; seeking past EOF + * just reads a clean end (a log shorter than the covered length is a + * strict prefix of what the snapshot already holds — nothing to do). */ +static ray_err_t journal_replay_from(const char* path, + int64_t start_off, + int64_t* out_chunks, + int64_t* out_eval_errors, + ray_jreplay_status_t* out_status) { if (out_chunks) *out_chunks = 0; if (out_eval_errors) *out_eval_errors = 0; @@ -197,6 +256,11 @@ ray_err_t ray_journal_replay(const char* path, if (out_status) *out_status = RAY_JREPLAY_IO; return RAY_ERR_IO; } + if (start_off > 0 && fseek(f, (long)start_off, SEEK_SET) != 0) { + fclose(f); + if (out_status) *out_status = RAY_JREPLAY_IO; + return RAY_ERR_IO; + } bool prev_in_replay = g_journal.in_replay; g_journal.in_replay = true; @@ -293,6 +357,15 @@ ray_err_t ray_journal_replay(const char* path, return RAY_ERR_DOMAIN; } +ray_err_t ray_journal_replay(const char* path, + int64_t* out_chunks, + int64_t* out_eval_errors, + ray_jreplay_status_t* out_status) +{ + return journal_replay_from(path, jlog_probe(path, NULL), + out_chunks, out_eval_errors, out_status); +} + ray_err_t ray_journal_validate(const char* path, int64_t* out_chunks, int64_t* out_valid_bytes) @@ -303,8 +376,16 @@ ray_err_t ray_journal_validate(const char* path, FILE* f = fopen(path, "rb"); if (!f) return RAY_ERR_IO; + /* Frames start after the generation preamble (0 on legacy logs); + * valid_off stays an absolute file offset so truncate hints hold. */ + int64_t start = jlog_probe(path, NULL); + if (start > 0 && fseek(f, (long)start, SEEK_SET) != 0) { + fclose(f); + return RAY_ERR_IO; + } + int64_t chunks = 0; - int64_t valid_off = 0; + int64_t valid_off = start; /* Reuse one growing buffer for payload reads — most logs hold * many small entries plus the occasional large one, so growing on * demand is simpler than trying to size up front. */ @@ -344,10 +425,36 @@ ray_err_t ray_journal_validate(const char* path, return RAY_OK; } -/* Open .log in append mode after replay. */ +/* Open .log in append mode after replay. A fresh (empty or + * absent) log gets the generation preamble; an existing one keeps its + * generation (0 for a pre-#420 headerless log). */ static ray_err_t open_log_for_append(void) { + bool fresh = true; + { /* portable size probe (stat is unix-only here) */ + FILE* probe = fopen(g_journal.log_path, "rb"); + if (probe) { + if (fseek(probe, 0, SEEK_END) == 0 && ftell(probe) > 0) fresh = false; + fclose(probe); + } + } + if (!fresh) { + jlog_probe(g_journal.log_path, &g_journal.log_gen); + } g_journal.fp = fopen(g_journal.log_path, "ab"); if (!g_journal.fp) return RAY_ERR_IO; + if (fresh) { + int64_t gen = jlog_fresh_gen(); + uint8_t pre[RAY_JLOG_PREAMBLE] = {0}; + memcpy(pre, RAY_JLOG_MAGIC, 8); + memcpy(pre + 8, &gen, sizeof(gen)); + if (fwrite(pre, 1, sizeof(pre), g_journal.fp) != sizeof(pre) || + fflush(g_journal.fp) != 0) { + fclose(g_journal.fp); + g_journal.fp = NULL; + return RAY_ERR_IO; + } + g_journal.log_gen = gen; + } /* Disable stdio buffering: every fwrite must reach the OS buffer * immediately so a SIGTERM (or any non-clean shutdown) still leaves * the entry on disk. Without this, the default block-buffered FILE* @@ -372,6 +479,9 @@ ray_err_t ray_journal_recover(const char* base) { if (!path_join_ext(log_path, sizeof(log_path), base, ".log")) return RAY_ERR_DOMAIN; + int64_t cover_gen = 0; + int64_t cover_len = 0; + /* 1. Snapshot — load .qdb if present. */ if (file_exists(qdb_path)) { bool prev_in_replay = g_journal.in_replay; @@ -406,6 +516,21 @@ ray_err_t ray_journal_recover(const char* base) { } int64_t sym_id = ((int64_t*)ray_data(keys))[i]; ray_t* v = ray_list_get(vals, i); + /* The coverage marker (#420) is snapshot metadata, not a + * user binding — record it and keep it out of the env. */ + { + ray_t* ks = ray_sym_str(sym_id); /* borrowed */ + if (ks && !RAY_IS_ERR(ks) && + ray_str_len(ks) == strlen(RAY_JLOG_COVER_KEY) && + memcmp(ray_str_ptr(ks), RAY_JLOG_COVER_KEY, + strlen(RAY_JLOG_COVER_KEY)) == 0) { + if (v && v->type == RAY_I64 && v->len == 2) { + cover_gen = ((int64_t*)ray_data(v))[0]; + cover_len = ((int64_t*)ray_data(v))[1]; + } + continue; + } + } if (!v) { fprintf(stderr, "log: WARN snapshot value missing for sym %lld — skipping\n", (long long)sym_id); @@ -439,11 +564,24 @@ ray_err_t ray_journal_recover(const char* base) { } } - /* 2. Log — replay .log if present. */ + /* 2. Log — replay .log if present. When the snapshot's + * coverage marker names THIS log generation, its prefix is already + * baked into the .qdb we just loaded — a crash between the .qdb + * rename and the roll (or a failed roll that kept appending) — + * so replay starts past the covered bytes instead of applying + * every covered entry a second time (#420). */ if (file_exists(log_path)) { + int64_t log_gen = 0; + int64_t start = jlog_probe(log_path, &log_gen); + if (cover_gen != 0 && log_gen == cover_gen && cover_len > start) { + fprintf(stderr, + "log: snapshot covers %lld bytes of %s (gen %lld) — replaying tail only\n", + (long long)cover_len, log_path, (long long)log_gen); + start = cover_len; + } int64_t chunks = 0, errs = 0; ray_jreplay_status_t status = RAY_JREPLAY_OK; - ray_journal_replay(log_path, &chunks, &errs, &status); + journal_replay_from(log_path, start, &chunks, &errs, &status); switch (status) { case RAY_JREPLAY_OK: { fprintf(stderr, "log: replayed %lld entries (%lld eval errors) from %s\n", @@ -743,6 +881,46 @@ ray_err_t ray_journal_snapshot(void) { ray_sys_free(sym_ids); ray_sys_free(vals_buf); + /* Coverage marker (#420): record which live-log prefix this snapshot + * already contains, so recovery can skip it when a crash (or a failed + * roll) leaves that log next to the fresh .qdb. Captured before the + * .qdb rename so the marker can only under-cover, never over-cover: + * an entry logged after this point replays as tail. */ + if (g_journal.log_gen != 0) { + fflush(g_journal.fp); + long pos = ftell(g_journal.fp); + if (pos >= RAY_JLOG_PREAMBLE) { + int64_t marker[2] = { g_journal.log_gen, (int64_t)pos }; + ray_t* mv = ray_vec_from_raw(RAY_I64, marker, 2); + if (!mv || RAY_IS_ERR(mv)) { + if (mv) ray_error_free(mv); + ray_release(keys); + ray_release(vals); + return RAY_ERR_OOM; + } + int64_t mk = ray_sym_intern(RAY_JLOG_COVER_KEY, + (int64_t)strlen(RAY_JLOG_COVER_KEY)); + ray_t* prev_keys = keys; + keys = ray_vec_append(keys, &mk); + if (RAY_IS_ERR(keys)) { + ray_error_free(keys); + ray_release(prev_keys); + ray_release(vals); + ray_release(mv); + return RAY_ERR_OOM; + } + ray_t* prev_vals = vals; + vals = ray_list_append(vals, mv); + ray_release(mv); + if (RAY_IS_ERR(vals)) { + ray_error_free(vals); + ray_release(prev_vals); + ray_release(keys); + return RAY_ERR_OOM; + } + } + } + ray_t* snap = ray_dict_new(keys, vals); if (!snap || RAY_IS_ERR(snap)) { if (snap && RAY_IS_ERR(snap)) ray_error_free(snap); diff --git a/src/store/serde.c b/src/store/serde.c index bad939fa0..cc74e706c 100644 --- a/src/store/serde.c +++ b/src/store/serde.c @@ -801,6 +801,17 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { return e; } + /* Schema names and columns must be 1:1. The build loop below is + * bounded by min(cols->len, schema->len), so a crafted frame with a + * shorter schema (or more columns) would otherwise be accepted as a + * silently truncated table instead of being rejected. */ + if (schema->len != cols->len) { + ray_t* e = ray_error("domain", "deserialize table: schema/column count mismatch (%lld names, %lld columns)", (long long)schema->len, (long long)cols->len); + ray_release(schema); + ray_release(cols); + return e; + } + int64_t ncols = cols->len; ray_t* tbl = ray_table_new(ncols); if (!tbl || RAY_IS_ERR(tbl)) { @@ -811,13 +822,12 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { void* name_data = ray_data(schema); ray_t** col_ptrs = (ray_t**)ray_data(cols); - for (int64_t i = 0; i < ncols && i < schema->len; i++) { + for (int64_t i = 0; i < ncols; i++) { /* ncols == schema->len (guarded above) */ int64_t name_id = (schema->type == RAY_I64) ? ((int64_t*)name_data)[i] : ray_read_sym(name_data, i, RAY_SYM, schema->attrs); ray_t* new_tbl = ray_table_add_col(tbl, name_id, col_ptrs[i]); if (!new_tbl || RAY_IS_ERR(new_tbl)) { - ray_release(tbl); ray_release(schema); ray_release(cols); return new_tbl; @@ -825,6 +835,14 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { tbl = new_tbl; } + ray_t* shape_err = ray_table_validate_rectangular(tbl, "deserialize table"); + if (shape_err) { + ray_release(tbl); + ray_release(schema); + ray_release(cols); + return shape_err; + } + ray_release(schema); ray_release(cols); return tbl; @@ -846,6 +864,18 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { return vals; } + /* One value per key: a dict probe finds a key index in [0, keys->len) + * and reads the value at that index, so a crafted dict with more keys + * than values would index the value block out of bounds (OOB + * read/release). vals may be a LIST of column vectors or a flat value + * vector — either way its length must equal keys->len. */ + if (keys->len != vals->len) { + ray_t* e = ray_error("domain", "deserialize dict: key/value count mismatch (%lld keys, %lld values)", (long long)keys->len, (long long)vals->len); + ray_release(keys); + ray_release(vals); + return e; + } + /* Build dict: alloc with 2 slots */ ray_t* dict = ray_alloc(2 * sizeof(ray_t*)); if (!dict || RAY_IS_ERR(dict)) { diff --git a/src/store/splay.c b/src/store/splay.c index 4350c64c0..921161070 100644 --- a/src/store/splay.c +++ b/src/store/splay.c @@ -97,13 +97,13 @@ static ray_err_t splay_validate_persisted_names(ray_t* tbl) { if (!a || RAY_IS_ERR(a)) continue; const char* an = ray_str_ptr(a); size_t alen = ray_str_len(a); - if (!splay_col_name_safe(an, alen)) continue; + if (!splay_col_name_safe(an, alen)) return RAY_ERR_DOMAIN; for (int64_t j = c + 1; j < nc; j++) { ray_t* b = ray_sym_str(ray_table_col_name(tbl, j)); if (!b || RAY_IS_ERR(b)) continue; const char* bn = ray_str_ptr(b); size_t blen = ray_str_len(b); - if (!splay_col_name_safe(bn, blen)) continue; + if (!splay_col_name_safe(bn, blen)) return RAY_ERR_DOMAIN; if (alen == blen && memcmp(an, bn, alen) == 0) return RAY_ERR_DOMAIN; } @@ -171,7 +171,8 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa * This can only happen when a symfile is actually written: the table * has SYM columns AND the symfile lives directly in `dir`. The default * symfile is the dotfile ".sym", which no column can be named (dot-led - * names are skipped below), so the default convention never collides — + * names are rejected up-front by splay_validate_persisted_names), so the + * default convention never collides — * a plain column named "sym" round-trips fine (issue #280). But an * explicit sym_path (3-arg .db.splayed.set) may name anything, so the * guard matches the resolved symfile path, not the literal "sym". */ @@ -280,8 +281,9 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa if (!name_atom) continue; const char* name = ray_str_ptr(name_atom); size_t name_len = ray_str_len(name_atom); - if (!splay_col_name_safe(name, name_len)) - continue; /* unsafe name: no file, no .d entry */ + /* Name safety (dot-led, '/', '\\', NUL) is enforced up-front by + * splay_validate_persisted_names() at the top of this function, so + * every name reaching this write loop is already safe. */ char path[1024]; int path_len = snprintf(path, sizeof(path), "%s/%.*s", dir, diff --git a/src/table/dict.c b/src/table/dict.c index 444da191e..7214f8725 100644 --- a/src/table/dict.c +++ b/src/table/dict.c @@ -40,6 +40,10 @@ #define DICT_DATA_SIZE (2 * sizeof(ray_t*)) +static bool dict_side_is_list_or_vec(ray_t* side) { + return side && !RAY_IS_ERR(side) && (side->type == RAY_LIST || ray_is_vec(side)); +} + static ray_t* dict_alloc_block(ray_t* keys, ray_t* vals) { ray_t* d = ray_alloc(DICT_DATA_SIZE); if (!d || RAY_IS_ERR(d)) return d; @@ -69,6 +73,26 @@ ray_t* ray_dict_new(ray_t* keys, ray_t* vals) { ray_release(keys); return vals ? vals : ray_error("type", "dict: vals vector is null"); } + if (!dict_side_is_list_or_vec(keys)) { + ray_release(keys); + ray_release(vals); + return ray_error("domain", "dict: keys must be list/vector-like, got %s", + ray_type_name(keys->type)); + } + if (!dict_side_is_list_or_vec(vals)) { + ray_release(keys); + ray_release(vals); + return ray_error("domain", "dict: vals must be list/vector-like, got %s", + ray_type_name(vals->type)); + } + if (keys->len != vals->len) { + int64_t klen = keys->len; + int64_t vlen = vals->len; + ray_release(keys); + ray_release(vals); + return ray_error("domain", "dict: key/value count mismatch (%lld keys, %lld values)", + (long long)klen, (long long)vlen); + } ray_t* d = dict_alloc_block(keys, vals); if (!d || RAY_IS_ERR(d)) { ray_release(keys); diff --git a/src/table/domain.h b/src/table/domain.h index 6d62bf4d7..474c610d8 100644 --- a/src/table/domain.h +++ b/src/table/domain.h @@ -47,8 +47,8 @@ * ray_sym_domain_str a lock-free array read. * * Position-0 reservation: position 0 of every non-empty FILE domain is - * the ordinary empty symbol "" (mirrors global id 0). SYM has no distinct - * null; group kernels treat id 0 as an ordinary value. ray_sym_domain_open + * the canonical empty/null symbol "" (mirrors global id 0). Group kernels + * retain id 0 as a groupable null key. ray_sym_domain_open * VALIDATES this and refuses (NULL) files that violate it; intern on an * empty domain seeds "" at position 0 before the first real symbol, so * newly created symfiles always carry it. Empty vocabularies are fine. diff --git a/src/table/table.c b/src/table/table.c index e8d15d46e..10a6c09fb 100644 --- a/src/table/table.c +++ b/src/table/table.c @@ -58,6 +58,21 @@ static inline ray_t* tbl_cols(ray_t* tbl) { return tbl_slots(tbl)[1]; } +static bool table_col_is_valid(ray_t* col) { + if (!col || RAY_IS_ERR(col)) return false; + return col->type == RAY_LIST || + ray_is_vec(col) || + RAY_IS_PARTED(col->type) || + col->type == RAY_MAPCOMMON; +} + +static int64_t table_col_nrows(ray_t* col) { + if (!col) return 0; + if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) + return ray_parted_nrows(col); + return col->len; +} + /* -------------------------------------------------------------------------- * ray_table_new — allocates an empty table with capacity for `ncols`. * @@ -103,7 +118,11 @@ ray_t* ray_table_new(int64_t ncols) { ray_t* ray_table_add_col(ray_t* tbl, int64_t name_id, ray_t* col_vec) { if (!tbl || RAY_IS_ERR(tbl)) return tbl; - if (!col_vec || RAY_IS_ERR(col_vec)) return ray_error("type", "table add_col: column must be a vector, got %s", col_vec ? ray_type_name(col_vec->type) : "null"); + if (!table_col_is_valid(col_vec)) { + ray_release(tbl); + return ray_error("domain", "table add_col: column must be list/vector-like, got %s", + col_vec ? ray_type_name(col_vec->type) : "null"); + } tbl = ray_cow(tbl); if (!tbl || RAY_IS_ERR(tbl)) return tbl; @@ -127,6 +146,44 @@ ray_t* ray_table_add_col(ray_t* tbl, int64_t name_id, ray_t* col_vec) { return tbl; } +ray_t* ray_table_validate_rectangular(ray_t* tbl, const char* context) { + const char* where = context ? context : "table"; + if (!tbl) return ray_error("type", "%s: expected table, got null", where); + if (RAY_IS_ERR(tbl)) + return ray_error(ray_err_code(tbl) ? ray_err_code(tbl) : "error", + "%s: expected table, got error", where); + if (tbl->type != RAY_TABLE) + return ray_error("type", "%s: expected table, got %s", where, ray_type_name(tbl->type)); + + ray_t* schema = tbl_schema(tbl); + ray_t* cols = tbl_cols(tbl); + if (!schema || !cols || RAY_IS_ERR(schema) || RAY_IS_ERR(cols)) + return ray_error("domain", "%s: malformed table storage", where); + if (schema->len != cols->len) + return ray_error("domain", + "%s: schema/column count mismatch (%lld names, %lld columns)", + where, (long long)schema->len, (long long)cols->len); + + ray_t** col_ptrs = (ray_t**)ray_data(cols); + int64_t expected = 0; + for (int64_t i = 0; i < cols->len; i++) { + ray_t* col = col_ptrs[i]; + if (!table_col_is_valid(col)) + return ray_error("domain", "%s: column must be list/vector-like, got %s", + where, col ? ray_type_name(col->type) : "null"); + int64_t got = table_col_nrows(col); + if (i == 0) { + expected = got; + } else if (got != expected) { + return ray_error("domain", + "%s: ragged columns (column %lld has %lld rows, expected %lld)", + where, (long long)i, (long long)got, (long long)expected); + } + } + + return NULL; +} + /* -------------------------------------------------------------------------- * ray_table_get_col — lookup column by sym id; borrowed pointer or NULL. * -------------------------------------------------------------------------- */ diff --git a/src/vec/atom.c b/src/vec/atom.c index 7ae4ce7fc..084143222 100644 --- a/src/vec/atom.c +++ b/src/vec/atom.c @@ -183,7 +183,7 @@ ray_t* ray_typed_null(int8_t type) { * can deref obj without a NULL check. Other types use the payload * union — the sentinel write below is the source of truth. The * aux[0] bit represents typed null only for BOOL/U8; F32 uses NaN. - * SYM/STR typed-null requests collapse to ordinary empty values. */ + * SYM/STR typed-null requests use their canonical empty values. */ if (type == -RAY_GUID) { static const uint8_t NULL_GUID_BYTES[16] = {0}; ray_t* v = ray_guid(NULL_GUID_BYTES); @@ -201,8 +201,7 @@ ray_t* ray_typed_null(int8_t type) { case -RAY_I32: case -RAY_DATE: case -RAY_TIME: v->i32 = NULL_I32; break; case -RAY_I16: v->i16 = NULL_I16; break; case -RAY_SYM: - /* SYM has no null — a SYM "typed null" is just the empty symbol ' - * (sym 0), a value, mirroring STR. No aux[0] null bit. */ + /* SYM's canonical null is the empty symbol ' (sym 0). */ v->i64 = 0; return v; default: v->i64 = 0; break; diff --git a/src/vec/vec.c b/src/vec/vec.c index 5ff53e1c2..0bfc4b3bc 100644 --- a/src/vec/vec.c +++ b/src/vec/vec.c @@ -68,8 +68,8 @@ static inline bool sentinel_is_null(const ray_t* v, int64_t idx) { return ((const int32_t*)p)[idx] == NULL_I32; case RAY_I16: return ((const int16_t*)p)[idx] == NULL_I16; - /* SYM has no null (sym id 0 is the empty value, not null) — - * no arm here; ray_vec_is_null short-circuits SYM before this switch. */ + /* SYM uses id 0 as its canonical in-band null. Width-aware handling + * lives in ray_vec_is_null, so there is no arm here. */ case RAY_STR: return ((const ray_str_t*)p)[idx].len == 0; case RAY_GUID: { @@ -282,6 +282,9 @@ ray_t* ray_vec_append(ray_t* vec, const void* elem) { /* Append element */ char* dst = (char*)ray_data(vec) + vec->len * esz; memcpy(dst, elem, esz); + if (vec->type == RAY_SYM && + ray_read_sym(elem, 0, RAY_SYM, vec->attrs) == 0) + vec->attrs |= RAY_ATTR_HAS_NULLS; vec->len++; return vec; @@ -291,6 +294,67 @@ ray_t* ray_vec_append(ray_t* vec, const void* elem) { return ray_error("oom", NULL); } +/* -------------------------------------------------------------------------- + * ray_vec_append_raw + * + * Append `count` raw elements with one capacity reserve and one memcpy. + * Same contract as ray_vec_append (COW when shared, index drop, amortized + * power-of-two growth, original left alive on failure), minus the + * per-element call overhead — this is the batch-ingest primitive. + * + * The raw cells are copied verbatim, sentinels included; the caller + * propagates RAY_ATTR_HAS_NULLS from the source when it can carry nulls + * (for RAY_SYM the caller must also guarantee the ids are in this + * vector's width and domain). + * -------------------------------------------------------------------------- */ + +ray_t* ray_vec_append_raw(ray_t* vec, const void* src, int64_t count) { + if (!vec || RAY_IS_ERR(vec)) return vec; + if (vec->type <= 0 || vec->type >= RAY_TYPE_COUNT) + return ray_error("type", "vec_append_raw: expects a concrete vector type, got %s", ray_type_name(vec->type)); + if (vec->type == RAY_STR) return ray_error("type", "vec_append_raw: str vectors use ray_str_vec_append, got %s", ray_type_name(vec->type)); + if (count < 0) return ray_error("range", "vec_append_raw: count must be non-negative, got %lld", (long long)count); + if (count == 0) return vec; + if (!src) return ray_error("domain", "vec_append_raw: source pointer is null but count is %lld", (long long)count); + + ray_t* original = vec; + vec = ray_cow(vec); + if (!vec || RAY_IS_ERR(vec)) return vec; + + vec_drop_index_inplace(vec); + + uint8_t esz = ray_sym_elem_size(vec->type, vec->attrs); + int64_t cap = vec_capacity(vec); + + if (vec->len > INT64_MAX - count) goto fail; + if (vec->len + count > cap) { + size_t new_data_size = (size_t)(vec->len + count) * esz; + if (new_data_size < 32) new_data_size = 32; + else { + size_t s = 32; + while (s < new_data_size) { + if (s > SIZE_MAX / 2) goto fail; + s *= 2; + } + new_data_size = s; + } + ray_t* new_vec = ray_scratch_realloc(vec, new_data_size); + if (!new_vec || RAY_IS_ERR(new_vec)) { + if (vec != original) ray_release(vec); + return new_vec ? new_vec : ray_error("oom", NULL); + } + vec = new_vec; + } + + memcpy((char*)ray_data(vec) + (size_t)vec->len * esz, src, (size_t)count * esz); + vec->len += count; + return vec; + +fail: + if (vec != original) ray_release(vec); + return ray_error("oom", NULL); +} + /* -------------------------------------------------------------------------- * ray_vec_set * -------------------------------------------------------------------------- */ @@ -311,6 +375,9 @@ ray_t* ray_vec_set(ray_t* vec, int64_t idx, const void* elem) { uint8_t esz = ray_sym_elem_size(vec->type, vec->attrs); char* dst = (char*)ray_data(vec) + idx * esz; memcpy(dst, elem, esz); + if (vec->type == RAY_SYM && + ray_read_sym(elem, 0, RAY_SYM, vec->attrs) == 0) + vec->attrs |= RAY_ATTR_HAS_NULLS; return vec; } @@ -922,6 +989,36 @@ ray_t* ray_vec_from_raw(int8_t type, const void* data, int64_t count) { memcpy(ray_data(v), data, data_size); } + /* Raw payloads arrive with in-band null sentinels already in place + * (e.g. a binding passing INT64_MIN for an absent quantity), and + * HAS_NULLS is the fast-path gate ray_vec_is_null and the query/ + * serde paths trust — a sentinel without the flag renders and + * aggregates as ordinary data. Scan once at construction; the + * sentinel stays the source of truth. */ + switch (type) { + case RAY_SYM: + for (int64_t i = 0; i < count; i++) { + if (ray_read_sym(ray_data(v), i, RAY_SYM, v->attrs) == 0) { + v->attrs |= RAY_ATTR_HAS_NULLS; + break; + } + } + break; + case RAY_F64: case RAY_F32: + case RAY_I64: case RAY_TIMESTAMP: + case RAY_I32: case RAY_DATE: case RAY_TIME: + case RAY_I16: case RAY_GUID: + for (int64_t i = 0; i < count; i++) { + if (sentinel_is_null(v, i)) { + v->attrs |= RAY_ATTR_HAS_NULLS; + break; + } + } + break; + default: + break; /* BOOL/U8/LIST/TABLE: non-nullable or pointer payloads */ + } + /* LIST/TABLE elements are child pointers — retain them */ if (type == RAY_LIST || type == RAY_TABLE) { ray_t** ptrs = (ray_t**)ray_data(v); @@ -940,7 +1037,7 @@ ray_t* ray_vec_from_raw(int8_t type, const void* data, int64_t count) { * the payload (F64/F32 NaN, NULL_I64 / NULL_I32 / NULL_I16, ray_str_t{0,0}, * 16 zero bytes for GUID). A vec-level RAY_ATTR_HAS_NULLS flag is a * cheap fast-path gate; ray_vec_is_null reads the payload as source of - * truth. BOOL/U8/SYM are non-nullable. + * truth. BOOL/U8 are non-nullable; SYM/STR use canonical empty payloads. * -------------------------------------------------------------------------- */ ray_err_t ray_vec_set_null_checked(ray_t* vec, int64_t idx, bool is_null) { @@ -948,14 +1045,9 @@ ray_err_t ray_vec_set_null_checked(ray_t* vec, int64_t idx, bool is_null) { if (vec->attrs & RAY_ATTR_SLICE) return RAY_ERR_TYPE; /* cannot set null on slice — COW first */ if (idx < 0 || idx >= vec->len) return RAY_ERR_RANGE; - /* Types that don't accept set-null: - * - SYM: sym ID 0 (interned empty string, reserved by - * ray_sym_init) is the canonical "missing" value; callers - * write 0 directly. - * - BOOL / U8: non-nullable; they have nowhere to store a + /* BOOL / U8 are non-nullable; they have nowhere to store a * null, so reject to keep the producer surface clean. */ - if (vec->type == RAY_SYM || - vec->type == RAY_BOOL || + if (vec->type == RAY_BOOL || vec->type == RAY_U8) return RAY_ERR_TYPE; /* Mutation invalidates any attached accelerator index — drop it inline. @@ -977,11 +1069,13 @@ ray_err_t ray_vec_set_null_checked(ray_t* vec, int64_t idx, bool is_null) { case RAY_I64: case RAY_TIMESTAMP: ((int64_t*)p)[idx] = NULL_I64; break; case RAY_I32: case RAY_DATE: case RAY_TIME: ((int32_t*)p)[idx] = NULL_I32; break; case RAY_I16: ((int16_t*)p)[idx] = NULL_I16; break; + case RAY_SYM: + ray_write_sym(p, idx, 0, RAY_SYM, vec->attrs); + break; case RAY_STR: - /* STR has no null distinct from "": write the - * empty string but do NOT mark the column nullable. */ + /* Empty string is STR's canonical in-band null. */ memset(&((ray_str_t*)p)[idx], 0, sizeof(ray_str_t)); - return RAY_OK; + break; case RAY_GUID: memset((uint8_t*)p + idx * 16, 0, 16); break; @@ -1026,6 +1120,15 @@ static ray_t* str_pool_cow(ray_t* vec) { new_pool->mmod = saved_mmod; ray_atomic_store(&new_pool->rc, 1); + /* A mapped pool is the column's only route to the shared region's + * descriptor, and this is the moment that route disappears. Register + * the column under its own address first — that is what the region was + * mapped at — so its free can still find the reference it holds. The + * registry therefore contains mutated mapped columns only, which is + * usually none. */ + if (vec->str_pool->mmod == 3 && vec->mmod == 1) + ray_file_map_register(vec, vec->str_pool->file_map); + ray_release(vec->str_pool); vec->str_pool = new_pool; return vec; @@ -1138,6 +1241,7 @@ ray_t* ray_str_vec_append(ray_t* vec, const char* s, size_t len) { } vec->len++; + if (len == 0) vec->attrs |= RAY_ATTR_HAS_NULLS; return vec; fail_oom: @@ -1154,9 +1258,9 @@ ray_t* ray_str_vec_append(ray_t* vec, const char* s, size_t len) { * Allocates the string pool once (not per-element like ray_str_vec_append). * Pass 1 sums pooled bytes; pass 2 fills descriptors and pool in one sweep. * ptrs[i] may be NULL when lens[i]==0. nulls may be NULL (no missing - * inputs); when non-NULL, nulls[i]!=0 requests a missing input. STR cannot - * represent a distinct null, so that request collapses to an ordinary empty - * string (len==0) without RAY_ATTR_HAS_NULLS. + * inputs); when non-NULL, nulls[i]!=0 requests a missing input. Empty STR is + * the canonical null representation, so both requests and zero lengths mark + * the output HAS_NULLS. * -------------------------------------------------------------------------- */ ray_t* ray_str_vec_from_parts(const char* const* ptrs, const uint32_t* lens, @@ -1199,10 +1303,12 @@ ray_t* ray_str_vec_from_parts(const char* const* ptrs, const uint32_t* lens, ray_str_t* d = &elems[i]; memset(d, 0, sizeof(ray_str_t)); if (nulls && nulls[i]) { - /* Missing STR input collapses to ordinary empty: already len=0. */ + /* Missing STR input is the canonical empty representation. */ + v->attrs |= RAY_ATTR_HAS_NULLS; } else if (lens[i] <= RAY_STR_INLINE_MAX) { d->len = lens[i]; if (lens[i] > 0) memcpy(d->data, ptrs[i], lens[i]); + else v->attrs |= RAY_ATTR_HAS_NULLS; } else { if ((uint64_t)pool_used > UINT32_MAX || (uint64_t)lens[i] > UINT32_MAX - (uint64_t)pool_used) { @@ -1283,6 +1389,7 @@ ray_t* ray_str_vec_set(ray_t* vec, int64_t idx, const char* s, size_t len) { memset(elem, 0, sizeof(ray_str_t)); elem->len = (uint32_t)len; if (len > 0) memcpy(elem->data, s, len); + else vec->attrs |= RAY_ATTR_HAS_NULLS; } else { if (!vec->str_pool) { size_t init_pool = len < 256 ? 256 : len * 2; @@ -1439,11 +1546,6 @@ bool ray_vec_is_null(ray_t* vec, int64_t idx) { if (!vec || RAY_IS_ERR(vec)) return false; if (idx < 0 || idx >= vec->len) return false; - /* SYM and STR columns are no-null by design (empty "" / sym 0 is the - * convention — there is no null distinct from empty). Consumers - * that need empty detection test the value (sym id 0 / str len 0) directly. */ - if (vec->type == RAY_SYM || vec->type == RAY_STR) return false; - /* Slice: delegate to parent with adjusted index */ if (vec->attrs & RAY_ATTR_SLICE) { ray_t* parent = vec->slice_parent; @@ -1451,6 +1553,14 @@ bool ray_vec_is_null(ray_t* vec, int64_t idx) { return ray_vec_is_null(parent, pidx); } + /* SYM/STR nulls are canonical empty payloads. Check them directly even + * when HAS_NULLS is absent so older/persisted vectors and raw gathers + * observe the same semantics. */ + if (vec->type == RAY_SYM) + return ray_read_sym(ray_data(vec), idx, RAY_SYM, vec->attrs) == 0; + if (vec->type == RAY_STR) + return ((const ray_str_t*)ray_data(vec))[idx].len == 0; + /* Vec-level fast-path gate: HAS_NULLS clear means no null anywhere. */ if (!vec_any_nulls(vec)) return false; @@ -1463,7 +1573,6 @@ bool ray_vec_is_null(ray_t* vec, int64_t idx) { case RAY_I64: case RAY_TIMESTAMP: case RAY_I32: case RAY_DATE: case RAY_TIME: case RAY_I16: - case RAY_STR: case RAY_GUID: return sentinel_is_null(vec, idx); default: diff --git a/test/rfl/agg/parted_f64_agg.rfl b/test/rfl/agg/parted_f64_agg.rfl index 1a6b78178..e8562613b 100644 --- a/test/rfl/agg/parted_f64_agg.rfl +++ b/test/rfl/agg/parted_f64_agg.rfl @@ -100,6 +100,18 @@ (min (at Pi 'v)) -- 10 (max (at Pi 'v)) -- 50 +;; ─── parted I64 sum wrap via raw-column expression fallback ────────── +;; `(first (list c))` deliberately defeats expr_compile today, leaving the +;; quoted raw column visible to the runtime agg_parted_sum path. If the +;; planner learns this shape later, this test may need a different wrapper. +(.sys.exec "rm -rf /tmp/rfl_agg_pwrap") +(set Tw1 (table [v] (list [9223372036854775807]))) +(set Tw2 (table [v] (list [9223372036854775807]))) +(.db.splayed.set "/tmp/rfl_agg_pwrap/1/t/" Tw1) +(.db.splayed.set "/tmp/rfl_agg_pwrap/2/t/" Tw2) +(set Pw (.db.parted.get "/tmp/rfl_agg_pwrap/" 't)) +(at (select {r: ((fn [c] (sum (first (list c)))) 'v) from: Pw}) 'r) -- [-2 -2] + ;; ─── parted DATE sum type error (agg_parted_sum line 129) ──────────── ;; DATE base type is explicitly excluded from sum — hits the type error path. (.sys.exec "rm -rf /tmp/rfl_agg_pdate") @@ -111,5 +123,23 @@ ;; sum on parted DATE → type error (agg_parted_sum line 129) (sum (at Pd 'd)) !- type +;; ─── parted TIMESTAMP / LIST sum type errors ───────────────────────── +;; TIMESTAMP is an absolute point, not a duration. LIST is a non-numeric +;; wrapper; this guards against using the permissive plan-time admission check +;; as the final runtime gate, which would silently return 0 for parted LIST. +(.sys.exec "rm -rf /tmp/rfl_agg_pts /tmp/rfl_agg_plist") +(set Tts1 (table [ts] (list (as 'TIMESTAMP [1 2 3])))) +(set Tts2 (table [ts] (list (as 'TIMESTAMP [4 5])))) +(.db.splayed.set "/tmp/rfl_agg_pts/1/t/" Tts1) +(.db.splayed.set "/tmp/rfl_agg_pts/2/t/" Tts2) +(set Pts (.db.parted.get "/tmp/rfl_agg_pts/" 't)) +(select {r: ((fn [c] (sum c)) 'ts) from: Pts}) !- type +(set Tl1 (table [l] (list (list [1 2] [3 4])))) +(set Tl2 (table [l] (list (list [5 6])))) +(.db.splayed.set "/tmp/rfl_agg_plist/1/t/" Tl1) +(.db.splayed.set "/tmp/rfl_agg_plist/2/t/" Tl2) +(set Pl (.db.parted.get "/tmp/rfl_agg_plist/" 't)) +(select {r: ((fn [c] (sum (first (list c)))) 'l) from: Pl}) !- type + ;; ─── cleanup ───────────────────────────────────────────────────────── -(.sys.exec "rm -rf /tmp/rfl_agg_pf64 /tmp/rfl_agg_pf64b /tmp/rfl_agg_pf64g /tmp/rfl_agg_pi64 /tmp/rfl_agg_pdate") +(.sys.exec "rm -rf /tmp/rfl_agg_pf64 /tmp/rfl_agg_pf64b /tmp/rfl_agg_pf64g /tmp/rfl_agg_pi64 /tmp/rfl_agg_pwrap /tmp/rfl_agg_pdate /tmp/rfl_agg_pts /tmp/rfl_agg_plist") diff --git a/test/rfl/agg/prod_builtin.rfl b/test/rfl/agg/prod_builtin.rfl index b57f48a39..e79d50615 100644 --- a/test/rfl/agg/prod_builtin.rfl +++ b/test/rfl/agg/prod_builtin.rfl @@ -8,5 +8,10 @@ (prod []) -- 1 (prod ['a 'b]) !- type +;; i64 list product reads i64 atoms directly (not via f64), so it stays exact +;; above 2^53 and wraps via unsigned math on overflow instead of hitting UB. +(prod (list 9007199254740993 1)) -- 9007199254740993 +(prod (list 9223372036854775807 4)) -- -4 + (set Tp (table [g x] (list ['a 'a 'b] [2 3 4]))) (at (select {from: Tp p: (prod x) by: g}) 'p) -- [6 4] diff --git a/test/rfl/agg/sum.rfl b/test/rfl/agg/sum.rfl index 9a409ab7f..8a58ce194 100644 --- a/test/rfl/agg/sum.rfl +++ b/test/rfl/agg/sum.rfl @@ -25,6 +25,13 @@ (sum (list 0Ni 0Ni 0Ni)) -- 0 (sum (list)) -- 0 +;; ────────────── i64 overflow wraps (no signed-overflow UB) ────────────── +;; A boxed (list ...) reduces through the scalar path. Integer accumulation +;; must wrap via unsigned math rather than trigger UB; 2*(2^63-1) wraps to -2. +;; i64 atoms are read directly, so magnitudes above 2^53 stay exact. +(sum (list 9223372036854775807 9223372036854775807)) -- -2 +(sum (list 9007199254740992 1)) -- 9007199254740993 + ;; ---- RAY_IS_ERR propagation: sum(erroring arg) ---- (sum (* 'bad 1)) !- type (sum (+ "a" 1)) !- type @@ -96,3 +103,23 @@ (at (select {r: (sum t) by: k from: Mtm}) 'r) -- [18:00:00.000 01:00:00.000] ;; integer families still widen to I64 (no spurious type preservation) (type (at (select {r: (sum k) from: Mtm}) 'r)) -- 'I64 + +;; ---- table-scan sum kernels wrap on i64 overflow (no signed-overflow UB) ---- +;; The select scalar-sum path (group.c scalar_sum_i64_fn / _linear_i64_fn) must +;; wrap like the flat and boxed-list reductions. 2*(2^63-1) wraps to -2. +(set Movf (table [g v] (list (as 'I64 [1 1]) [9223372036854775807 9223372036854775807]))) +(at (select {r: (sum v) from: Movf}) 'r) -- [-2] +(at (select {r: (sum v) by: g from: Movf}) 'r) -- [-2] +;; linear affine column expr in select (scalar_sum_linear_i64_fn): 2^62+2^62 per +;; row = 2^63 (wraps to MIN); two rows sum to 0. +(set Mlin (table [v] (list [4611686018427387904 4611686018427387904]))) +(at (select {r: (sum (+ v v)) from: Mlin}) 'r) -- [0] +;; Above the parallel threshold, worker-local partial sums and the final +;; cross-worker merge must use the same wrap semantics. 131072*(2^46+1) +;; wraps to INT64_MIN+131072, avoiding the NULL_I64 sentinel exactly. +(set Mpar (table [g v] (list (take [1] 131072) (take [70368744177665] 131072)))) +(at (select {r: (sum v) from: Mpar}) 'r) -- [-9223372036854644736] +(at (select {r: (sum v) by: g from: Mpar}) 'r) -- [-9223372036854644736] +;; Linear expression path: 131072*(2*(2^45+1)) wraps to INT64_MIN+262144. +(set Mparlin (table [v] (list (take [35184372088833] 131072)))) +(at (select {r: (sum (+ v v)) from: Mparlin}) 'r) -- [-9223372036854513664] diff --git a/test/rfl/arith/sum_affine.rfl b/test/rfl/arith/sum_affine.rfl index 5f37321fd..a50cd6647 100644 --- a/test/rfl/arith/sum_affine.rfl +++ b/test/rfl/arith/sum_affine.rfl @@ -74,3 +74,11 @@ ;; Anonymous lambda in head position: e[0]->type == RAY_LAMBDA (not -RAY_SYM) ;; → try_sum_affine_expr returns NULL at line 183; sum falls back to normal path (sum ((fn [a b] (+ a b)) [1 2 3] 10)) -- 36 + +;; ── affine fast path wraps on i64 overflow (no signed-overflow UB) ─────────── +;; (sum (+ v c)) folds to sum_i(v) + c*n; both the c*n multiply and the final +;; add must wrap deterministically in int64 two's-complement, matching flat sum. +;; v=[MAX MAX], c=2: sum_i = -2 (wrap), + 2*2 => 2 +(sum (+ [9223372036854775807 9223372036854775807] 2)) -- 2 +;; v=[MAX 1], c=1: sum_i = MIN (wrap), + 1*2 => MIN+2 +(sum (+ [9223372036854775807 1] 1)) -- -9223372036854775806 diff --git a/test/rfl/collection/atomic_map_coverage.rfl b/test/rfl/collection/atomic_map_coverage.rfl index bc72c425c..7eba0de75 100644 --- a/test/rfl/collection/atomic_map_coverage.rfl +++ b/test/rfl/collection/atomic_map_coverage.rfl @@ -91,9 +91,9 @@ (== syms null) -- false (!= syms null) -- true -;; sym vec vs the empty-symbol atom ('): ' is a VALUE (sym id 0), not a null. +;; sym vec vs the canonical empty/null atom ('), represented by sym id 0. ;; None of {a,b,c} equals the empty symbol → == all-false, != all-true. -;; The per-width compare loop runs (no null short-circuit; SYM has no null). +;; The per-width raw-id compare loop handles canonical null directly. (sum (== syms ')) -- 0 (sum (!= syms ')) -- 5 diff --git a/test/rfl/collection/collection_branch_cov.rfl b/test/rfl/collection/collection_branch_cov.rfl index cf0b8f66e..b187b9e05 100644 --- a/test/rfl/collection/collection_branch_cov.rfl +++ b/test/rfl/collection/collection_branch_cov.rfl @@ -752,13 +752,13 @@ ;; reverse on STR vec with nulls (lines 1860-1871) (set _rsn (reverse _scn)) (count _rsn) -- 4 -(nil? (at _rsn 2)) -- false +(nil? (at _rsn 2)) -- true (at _rsn 0) -- "hello" (at _rsn 3) -- "hello" ;; filter on STR vec (typed vec path with null bitmap, lines 554-562) (set _fsn (filter _scn [true true false true])) -(nil? (at _fsn 1)) -- false +(nil? (at _fsn 1)) -- true (at _fsn 0) -- "hello" (at _fsn 2) -- "hello" diff --git a/test/rfl/collection/cov4.rfl b/test/rfl/collection/cov4.rfl index 1302b36a8..61b0a9bb0 100644 --- a/test/rfl/collection/cov4.rfl +++ b/test/rfl/collection/cov4.rfl @@ -62,13 +62,13 @@ (set _t_snull (.csv.read [STR] "rf_cov4_null.csv")) (set _snull_col (at _t_snull 'name)) ;; confirm the null is present (empty cell = null in STR vec) -(nil? (at _snull_col 1)) -- false +(nil? (at _snull_col 1)) -- true ;; reverse the null-bearing STR vec (set _rev_null (reverse _snull_col)) (count _rev_null) -- 4 ;; reversed: foo, world, null, hello (at _rev_null 0) -- "foo" -(nil? (at _rev_null 2)) -- false +(nil? (at _rev_null 2)) -- true (at _rev_null 3) -- "hello" (.sys.exec "rm -f rf_cov4_null.csv") -- 0 diff --git a/test/rfl/collection/distinct.rfl b/test/rfl/collection/distinct.rfl index f52b15f4d..8cf07c215 100644 --- a/test/rfl/collection/distinct.rfl +++ b/test/rfl/collection/distinct.rfl @@ -166,14 +166,11 @@ (at (at rk2s 's) 66) -- 2 (at (at rk2s 'p) 99) -- 3.0 (at (at rk2s 's) 99) -- 2 -;; The original test here ran a SYM null-rank-collapse regression -;; using [' ' aa] over 99 rows. SYM columns are now no-null by -;; design (sym 0 = empty string is the canonical "missing" value), -;; so the null-collapse case it covered no longer exists. Other -;; non-SYM null tests above and below still exercise the rank -;; fallback paths; this block is intentionally removed rather than -;; rewritten because the empty-sym variant would just be a -;; same-value-many-rows sort, which the rk2 block already covers. +;; The original test here ran a SYM rank-collapse regression using +;; [' ' aa] over 99 rows. Canonical SYM null is now id 0 and remains a +;; distinct/groupable key, so the old rank-collapse case no longer applies. +;; Other null tests above and below exercise the fallback paths; this block +;; remains omitted because the empty-sym variant duplicates rk2. ;; RAY_STR multi-key. 100 rows, three distinct strings, three ;; distinct prices. Pre-fix, has_wide_key didn't exist and RAY_STR ;; wasn't in can_radix, so this would fall into merge sort; now it diff --git a/test/rfl/collection/drop_cut_rotate_cross.rfl b/test/rfl/collection/drop_cut_rotate_cross.rfl index 74b9538be..264e1c45a 100644 --- a/test/rfl/collection/drop_cut_rotate_cross.rfl +++ b/test/rfl/collection/drop_cut_rotate_cross.rfl @@ -4,9 +4,10 @@ (drop [1 2 3 4 5] -2) -- [1 2 3] (drop [1 2 3] 10) -- [] (drop [1 2 3] -10) -- [] -;; INT64_MIN count: `-INT64_MIN` is signed-overflow UB (was tripped in -;; ray_drop_fn); |n| that large drops the whole collection. -(drop [1 2 3] -9223372036854775808) -- [] +;; INT64_MIN count is the i64 null sentinel (0N), and `-INT64_MIN` is signed- +;; overflow UB (was tripped in ray_drop_fn). Reject it as a type error, +;; symmetric with take, rather than silently dropping the whole collection. +(drop [1 2 3] -9223372036854775808) !- type (drop "abcdef" 2) -- "cdef" (drop "abcdef" -2) -- "abcd" (drop ['a 'b 'c] 1) -- ['b 'c] diff --git a/test/rfl/collection/take.rfl b/test/rfl/collection/take.rfl index bb1a954a0..110529ad5 100644 --- a/test/rfl/collection/take.rfl +++ b/test/rfl/collection/take.rfl @@ -175,12 +175,21 @@ (count (take [1 2 3 4 5] [2 0])) -- 0 ;; range take with start = count → empty (count (take [1 2 3 4 5] [5 3])) -- 0 -;; INT64_MIN count: `-INT64_MIN` is signed-overflow UB (was tripped computing -;; the magnitude in every scalar-count take branch — vector, string, char, -;; scalar, list). Its magnitude is unrepresentable as int64, so it is a range -;; error, not UB followed by a bogus allocation. -(take [1 2 3] -9223372036854775808) !- range -(take "hello" -9223372036854775808) !- range -(take "a" -9223372036854775808) !- range -(take 42 -9223372036854775808) !- range -(take (list 1 2 3) -9223372036854775808) !- range +;; INT64_MIN count is the i64 null sentinel (0N), and `-INT64_MIN` is signed- +;; overflow UB (was tripped computing the magnitude in every scalar-count take +;; branch — vector, string, char, scalar, list). Reject it as a *type* error, +;; symmetric with drop and the window verbs, rather than negating a null count. +(take [1 2 3] -9223372036854775808) !- type +(take "hello" -9223372036854775808) !- type +(take "a" -9223372036854775808) !- type +(take 42 -9223372036854775808) !- type +(take (list 1 2 3) -9223372036854775808) !- type +;; Float counts are rejected up front as a type error. The guard also covers +;; F32 (as_i64 on an f32 would bit-read the storage and mis-fire the INT64_MIN +;; check), but F32 atoms have no rfl literal / `as` form, so only F64 is pinned. +(take [1 2 3] 2.5) !- type +;; Range take: amount up to INT64_MAX must clamp to the available length; +;; `start + amount` overflowed int64 (UB → bogus count → memcpy) before the fix. +(take [1 2 3] [1 9223372036854775807]) -- [2 3] +(take "hello" [1 9223372036854775807]) -- "ello" +(count (take (list 1 2 3) [1 9223372036854775807])) -- 2 diff --git a/test/rfl/datalog/datalog_coverage.rfl b/test/rfl/datalog/datalog_coverage.rfl index 43b90187a..c498f99a3 100644 --- a/test/rfl/datalog/datalog_coverage.rfl +++ b/test/rfl/datalog/datalog_coverage.rfl @@ -544,6 +544,24 @@ (dl-query FP 'edge) !- type (dl-free 'notprog) !- type +;; --- Claim 5b: forged/copied dl-program handles must not be dereferenced --- +;; A plain integer is NOT a dl-program handle. Every dl-* builtin that unwraps +;; one must reject it with a type error rather than reinterpreting the value as +;; a dl_program_t* pointer — before the RAY_ATTR_DLPROG tag check, (dl-free 1) +;; and friends dereferenced address 1 and crashed with SIGSEGV. +(dl-free 1) !- type +(dl-stratify 1) !- type +(dl-eval 1) !- type +(dl-query 1 'edge) !- type +(dl-add-edb 1 'edge (table ['a 'b] (list [1] [2])) 2) !- type +;; An arithmetic copy of a live handle drops the tag (attrs are not carried +;; through arithmetic), so it can't be freed — which would otherwise +;; double-free the original. The original still frees exactly once. +(set CP (dl-program)) +(set CPcopy (+ CP 0)) +(dl-free CPcopy) !- type +(dl-free CP) -- true + ;; --- Claim 4: fixpoint non-convergence must error loudly, not return a partial result --- ;; Reachability over a linear chain needs ~N iterations. The loop caps at 1000. diff --git a/test/rfl/fused/fused_topk_coverage.rfl b/test/rfl/fused/fused_topk_coverage.rfl index 425955cc6..77936dfd0 100644 --- a/test/rfl/fused/fused_topk_coverage.rfl +++ b/test/rfl/fused/fused_topk_coverage.rfl @@ -179,16 +179,17 @@ (at (at (select {v: v from: Tdesc where: (>= v 0) desc: v take: 3}) 'v) 2) -- 47 ;; ===================================================================== -;; 15. Null sort key — NULLS LAST for ASC, NULLS FIRST for DESC +;; 15. Null sort key — a null is the smallest value: NULLS FIRST for ASC, +;; NULLS LAST for DESC, the same rule the ordinary sort follows. ;; ===================================================================== ;; 0N is the I64 null literal; the table has nulls at positions 0 and 5. (set Tnull (table [k v] (list [0Nl 1 2 3 4 0Nl 6 7 8 9] (til 10)))) -;; ASC: nulls go last; top 3 are smallest non-null: 1, 2, 3 -(at (at (select {k: k from: Tnull where: (>= v 0) asc: k take: 3}) 'k) 0) -- 1 -(at (at (select {k: k from: Tnull where: (>= v 0) asc: k take: 3}) 'k) 1) -- 2 -(at (at (select {k: k from: Tnull where: (>= v 0) asc: k take: 3}) 'k) 2) -- 3 -;; DESC: nulls go first; top 4 DESC = 2 nulls then 9, 8 -(nil? (at (at (select {k: k from: Tnull where: (>= v 0) desc: k take: 4}) 'k) 0)) -- true -(nil? (at (at (select {k: k from: Tnull where: (>= v 0) desc: k take: 4}) 'k) 1)) -- true -(at (at (select {k: k from: Tnull where: (>= v 0) desc: k take: 4}) 'k) 2) -- 9 -(at (at (select {k: k from: Tnull where: (>= v 0) desc: k take: 4}) 'k) 3) -- 8 +;; ASC: the smallest rows ARE the nulls, so top 3 = 2 nulls then 1. +(nil? (at (at (select {k: k from: Tnull where: (>= v 0) asc: k take: 3}) 'k) 0)) -- true +(nil? (at (at (select {k: k from: Tnull where: (>= v 0) asc: k take: 3}) 'k) 1)) -- true +(at (at (select {k: k from: Tnull where: (>= v 0) asc: k take: 3}) 'k) 2) -- 1 +;; DESC: nulls go last; top 4 DESC = 9, 8, 7, 6 +(at (at (select {k: k from: Tnull where: (>= v 0) desc: k take: 4}) 'k) 0) -- 9 +(at (at (select {k: k from: Tnull where: (>= v 0) desc: k take: 4}) 'k) 1) -- 8 +(at (at (select {k: k from: Tnull where: (>= v 0) desc: k take: 4}) 'k) 2) -- 7 +(at (at (select {k: k from: Tnull where: (>= v 0) desc: k take: 4}) 'k) 3) -- 6 diff --git a/test/rfl/group/nullable_symkey_emit.rfl b/test/rfl/group/nullable_symkey_emit.rfl new file mode 100644 index 000000000..3738bd488 --- /dev/null +++ b/test/rfl/group/nullable_symkey_emit.rfl @@ -0,0 +1,95 @@ +;; ════════════════════════════════════════════════════════════════════ +;; nullable_symkey_emit.rfl — the fused top-N radix group-by must emit a +;; CANONICAL NULL for a null SYM key, not whatever bytes were in the +;; freshly-allocated output column. +;; +;; The bug (silent wrong answers, counts right / keys wrong): +;; radix_phase3_fn (src/ops/group.c) scatters each surviving group's key +;; tuple out of the partition HT rows. When key k's null-mask bit is set +;; it wrote the type-correct NULL_* sentinel — but only for +;; F64/I64/TIMESTAMP/I32/DATE/TIME/I16/STR. SYM (and GUID) fell through +;; `default: break`, and grp_set_null (= par_set_null) documents itself as +;; a no-op for SYM/STR/GUID, so NOTHING was written to the destination +;; element. ray_sym_vec_new does not zero its payload, so the emitted key +;; was an uninitialized word resolved through the source column's domain +;; into an arbitrary dictionary entry. A null SYM key is domain position +;; 0 (== ""), so the correct payload is all-zero bytes. +;; +;; Only a column that ADVERTISES nulls reaches that branch, which is why +;; this stayed hidden until HAS_NULLS started round-tripping honestly on +;; SYM columns (#416, 3ebf8f23). Both fixtures below carry it: the +;; in-memory table AND the converted splayed store (file-domain, positional +;; SYM), so this pins the engine path, not the store. +;; +;; Fixture shape — the routing matters: +;; * 70 000 rows (> RAY_PARALLEL_THRESHOLD 65536) so the parallel radix +;; pipeline runs at all; +;; * `by:` with the nullable SYM as a NON-LEADING key (1-key shapes route +;; elsewhere and were always right); +;; * `desc: s take: 500` — the top-N fusion is what routes into +;; radix_phase3_fn's key scatter. `take` also has to be large enough +;; that the output key column is a recycled (non-zeroed) block; at +;; take: 6 the emitted garbage happened to be zero and the bug hid. +;; +;; Oracle: `uid` is even exactly when its SearchPhrase-analogue `sp` is "" +;; (by construction), so every emitted (key-tuple) can be checked against +;; its own key — no reliance on which groups the top-N cut keeps. Ground +;; truth is taken with literal "" filters. Pre-fix, every section under- +;; counts the empty-sp rows (the exact wrong number depends on what was in +;; the recycled block) and the odd-uid parity check fails outright. +;; ════════════════════════════════════════════════════════════════════ + +(.sys.exec "rm -rf rf_test_nullsym_store") -- 0 + +(set NSK 70000) +(set nsk_uid (% (til NSK) 1000)) +;; sp is "" (the canonical SYM null) on even uid, "p" on odd uid. +(set nsk_sp (as 'SYM (at ["" "p"] (% nsk_uid 2)))) +(set nsk_g3 (% (til NSK) 7)) +(set Tnsk (table [uid sp g3 v] (list nsk_uid nsk_sp nsk_g3 (til NSK)))) + +;; ---------- 1. in-memory twin ---------- +;; 1000 (uid, sp) groups, sum v strictly increasing in uid, so the top 500 +;; are uid 500..999 → exactly 250 empty and 250 non-empty phrases. +(set RM2 (select {s: (sum v) from: Tnsk by: {uid: uid sp: sp} desc: s take: 500})) +(count RM2) -- 500 +(count (select {from: RM2 where: (== sp "")})) -- 250 +(count (select {from: RM2 where: (!= sp "")})) -- 250 +(all (== (% (at (select {from: RM2 where: (== sp "")}) 'uid) 2) 0)) -- true +(all (== (% (at (select {from: RM2 where: (!= sp "")}) 'uid) 2) 1)) -- true + +;; ---------- 2. converted splayed store, 2 keys ---------- +;; HAS_NULLS round-trips onto the on-disk SYM column (#416), and the loaded +;; column is file-domain / positional — the shape the ClickBench q17/q18 +;; regression was found on. +(count (.db.splayed.set "rf_test_nullsym_store" Tnsk)) -- 70000 +(set Snsk (.db.splayed.get "rf_test_nullsym_store" 'Tnsk)) +(count Snsk) -- 70000 + +(set RS2 (select {s: (sum v) from: Snsk by: {uid: uid sp: sp} desc: s take: 500})) +(count RS2) -- 500 +(count (select {from: RS2 where: (== sp "")})) -- 250 +(count (select {from: RS2 where: (!= sp "")})) -- 250 +(all (== (% (at (select {from: RS2 where: (== sp "")}) 'uid) 2) 0)) -- true +(all (== (% (at (select {from: RS2 where: (!= sp "")}) 'uid) 2) 1)) -- true + +;; ---------- 3. converted splayed store, 3 keys ---------- +;; 7000 (uid, sp, g3) groups; the parity oracle holds per emitted row +;; regardless of which 500 the cut keeps. Both halves must be non-empty so +;; neither parity check can pass vacuously. +(set RS3 (select {s: (sum v) from: Snsk by: {uid: uid sp: sp g3: g3} desc: s take: 500})) +(count RS3) -- 500 +(count (select {from: RS3 where: (== sp "")})) -- 250 +(count (select {from: RS3 where: (!= sp "")})) -- 250 +(all (== (% (at (select {from: RS3 where: (== sp "")}) 'uid) 2) 0)) -- true +(all (== (% (at (select {from: RS3 where: (!= sp "")}) 'uid) 2) 1)) -- true + +;; ---------- 4. the unordered emit stays correct ---------- +;; Same grouping without the top-N fusion (a different emit path) — it was +;; already right; pin that it stays right. +(set RS0 (select {s: (sum v) from: Snsk by: {uid: uid sp: sp}})) +(count RS0) -- 1000 +(count (select {from: RS0 where: (== sp "")})) -- 500 +(all (== (% (at (select {from: RS0 where: (== sp "")}) 'uid) 2) 0)) -- true + +(.sys.exec "rm -rf rf_test_nullsym_store") -- 0 diff --git a/test/rfl/hof/eval_coverage2.rfl b/test/rfl/hof/eval_coverage2.rfl index bce5df0db..be9512d1e 100644 --- a/test/rfl/hof/eval_coverage2.rfl +++ b/test/rfl/hof/eval_coverage2.rfl @@ -32,10 +32,10 @@ (count (where (!= sv8 'y))) -- 2 ;; ═══════════════════════════════════════════════════════════════════ -;; 3. SYM compare: empty-symbol atom (') is a value absent from the vec +;; 3. SYM compare: canonical empty/null atom (') is absent from the vec ;; Compare a SYM vec {a,b,c} against the empty symbol ' (sym id 0). -;; ' is a VALUE, not a null (SYM has no null); it matches no row → -;; == all-false, != all-true. Hits the per-width compare loop. +;; Canonical null is compared as raw id 0; it matches no row here → +;; == all-false, != all-true. Hits the per-width compare loop. ;; ═══════════════════════════════════════════════════════════════════ (set snull ') (set snv (as 'SYM ['a 'b 'c])) @@ -45,19 +45,18 @@ (sum (as 'I64 (!= snv snull))) -- 3 ;; ═══════════════════════════════════════════════════════════════════ -;; 4. SYM compare: empty symbol in the vec is a value, not a null +;; 4. SYM compare: canonical empty/null symbol in the vec ;; Build a SYM vec containing the empty symbol ' and compare against -;; a specific sym atom. The vec carries no nulls (SYM has no null); -;; the ' cell is just another value. +;; a specific sym atom. Equality still compares the in-band raw id. ;; ═══════════════════════════════════════════════════════════════════ -;; SYM vec [a ' a b] — the ' cell is the empty-symbol VALUE, not a null +;; SYM vec [a ' a b] — the ' cell is canonical null (raw id 0) (set t_sym (table ['s] (list (as 'SYM ['a ' 'a 'b])))) (set col_s (at t_sym 's)) ;; == 'a → [true, false, true, false] (the ' cell simply isn't 'a) (count (where (== col_s 'a))) -- 2 (count (where (!= col_s 'a))) -- 2 -;; empty sym == empty sym atom → value equality (SYM has no null; ' is a value, -;; mirroring STR "" == ""). The ' row equals the ' atom → 1 match. +;; empty sym == empty sym atom → in-band id equality. The ' row equals the +;; ' atom → 1 match. (sum (as 'I64 (== col_s '))) -- 1 (sum (as 'I64 (!= col_s '))) -- 3 diff --git a/test/rfl/hof/eval_coverage3.rfl b/test/rfl/hof/eval_coverage3.rfl index 3fbe89aeb..7c1750e11 100644 --- a/test/rfl/hof/eval_coverage3.rfl +++ b/test/rfl/hof/eval_coverage3.rfl @@ -143,7 +143,7 @@ _dcov_y -- 5 (set t_str_n (table ['s 'k] (list (as 'STR [1 0Nl 2]) [2 1 3]))) (set t_str_s (xasc t_str_n 'k)) ;; After sort by k: row k=1 is first, s[0] = null str -(nil? (at (at t_str_s 's) 0)) -- false +(nil? (at (at t_str_s 's) 0)) -- true ;; ═══════════════════════════════════════════════════════════════════ ;; 8. affine_sum_cache: vec has RAY_ATTR_HAS_NULLS → cache bypass diff --git a/test/rfl/integration/fused_group_parity.rfl b/test/rfl/integration/fused_group_parity.rfl index 24e4953d6..2835f5353 100644 --- a/test/rfl/integration/fused_group_parity.rfl +++ b/test/rfl/integration/fused_group_parity.rfl @@ -273,28 +273,28 @@ ;; id = [10, 20, 30, 40, 50] (non-null filter col) (set Tnk (table [v id] (list [3 0N 1 0N 2] [10 20 30 40 50]))) -;; ASC top-5: smallest non-null first, nulls go LAST in source order -;; (stable tie-break by row index — null rows sort tied via the null -;; leg, then row-index breaks the tie). Order: v=1 (id=30), -;; v=2 (id=50), v=3 (id=10), null (id=20), null (id=40). -(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 0) -- 30 -(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 1) -- 50 -(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 2) -- 10 -(nil? (at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'v) 3)) -- true -(nil? (at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'v) 4)) -- true -(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 3) -- 20 -(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 4) -- 40 +;; ASC top-5: a null is the smallest value, so the nulls lead in source +;; order (stable tie-break by row index — null rows sort tied via the null +;; leg, then row-index breaks the tie), then the non-nulls ascending. +;; Order: null (id=20), null (id=40), v=1 (id=30), v=2 (id=50), v=3 (id=10). +(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 0) -- 20 +(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 1) -- 40 +(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 2) -- 30 +(nil? (at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'v) 0)) -- true +(nil? (at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'v) 1)) -- true +(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 3) -- 50 +(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 5}) 'id) 4) -- 10 -;; ASC top-3: nulls don't make the cut at all (LAST policy). -(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 3}) 'id) 0) -- 30 -(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 3}) 'id) 1) -- 50 -(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 3}) 'id) 2) -- 10 +;; ASC top-3: the two nulls are the two smallest, so they take two of the +;; three slots and only v=1 (id=30) follows. +(nil? (at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 3}) 'v) 0)) -- true +(nil? (at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 3}) 'v) 1)) -- true +(at (at (select {v: v id: id from: Tnk where: (>= id 0) asc: v take: 3}) 'id) 2) -- 30 -;; DESC top-3: nulls go FIRST. Source order tie-break on the two -;; null rows: id=20 then id=40. Third entry is the largest non- -;; null, v=3 (id=10). -(nil? (at (at (select {v: v id: id from: Tnk where: (>= id 0) desc: v take: 3}) 'v) 0)) -- true -(nil? (at (at (select {v: v id: id from: Tnk where: (>= id 0) desc: v take: 3}) 'v) 1)) -- true -(at (at (select {v: v id: id from: Tnk where: (>= id 0) desc: v take: 3}) 'id) 0) -- 20 -(at (at (select {v: v id: id from: Tnk where: (>= id 0) desc: v take: 3}) 'id) 1) -- 40 -(at (at (select {v: v id: id from: Tnk where: (>= id 0) desc: v take: 3}) 'id) 2) -- 10 +;; DESC top-3: a null is the smallest value, so it goes LAST and never +;; enters a top-3 while three larger values exist. Descending by v: +;; 3 (id=10), 2 (id=50), 1 (id=30). +(nil? (at (at (select {v: v id: id from: Tnk where: (>= id 0) desc: v take: 3}) 'v) 0)) -- false +(at (at (select {v: v id: id from: Tnk where: (>= id 0) desc: v take: 3}) 'id) 0) -- 10 +(at (at (select {v: v id: id from: Tnk where: (>= id 0) desc: v take: 3}) 'id) 1) -- 50 +(at (at (select {v: v id: id from: Tnk where: (>= id 0) desc: v take: 3}) 'id) 2) -- 30 diff --git a/test/rfl/integration/null.rfl b/test/rfl/integration/null.rfl index f134ec71a..0d4c2d613 100644 --- a/test/rfl/integration/null.rfl +++ b/test/rfl/integration/null.rfl @@ -5,8 +5,8 @@ (nil? 0Nl) -- true (nil? 0) -- false (nil? 1) -- false -;; STR has no distinct null; "" is the ordinary empty value. -(nil? "") -- false +;; Empty STR is the canonical in-band null. +(nil? "") -- true ;; nil? distinguishes typed nulls from zero-valued atoms across types (nil? 0Ni) -- true (nil? 0Nf) -- true diff --git a/test/rfl/io/csv_parallel_scan.rfl b/test/rfl/io/csv_parallel_scan.rfl new file mode 100644 index 000000000..d8b0e7370 --- /dev/null +++ b/test/rfl/io/csv_parallel_scan.rfl @@ -0,0 +1,62 @@ +;; Parallel row-offset scan (csv.c build_row_offsets_par) — exactness. +;; +;; The scan splits the file into chunks and reconciles quote parity across +;; them, so its whole risk surface is the chunk BOUNDARY: a quoted field that +;; contains a newline, a "" escape that flips parity twice, and a two-byte +;; line terminator split down the middle. Both fixtures below are built past +;; CSV_SCAN_PAR_MIN_BYTES (4 MiB) so the parallel path is actually taken — +;; a smaller file silently falls back to the serial scanner and proves +;; nothing. Row counts are exact (fixed block repeated 2^n times), so a +;; dropped, duplicated or mis-split row fails the count assertion. +;; +;; Fixtures use the rf_test_csvps_* prefix so the Makefile `rm -f +;; rf_test_*.csv` rule keeps the tree clean. + +;; ── scrub stale state ─────────────────────────────────────────────────────── +(.sys.exec "rm -f rf_test_csvps_q.csv rf_test_csvps_p.csv") -- 0 + +;; ════════════════════════════════════════════════════════════════════════════ +;; 1. Quoted / mixed-terminator file — the slow (quote-parity) state machine. +;; +;; One block = 4 rows, each exercising a different boundary hazard: +;; "a\nb",1,plain\r\n quoted embedded LF, then a CRLF terminator +;; "q""q",2,x\n doubled-quote escape (parity flips twice) +;; 3,4\r lone-CR terminator AND a short row (2 of 3 cols) +;; "c,d",5,"e\r\nf"\n quoted delimiter and a quoted CRLF +;; Doubled 17 times => 131072 blocks = 524288 rows, ~5.9 MB. +;; ════════════════════════════════════════════════════════════════════════════ +(.sys.exec "printf 'a,b,c\n' > rf_test_csvps_q.csv; printf '\"a\nb\",1,plain\r\n\"q\"\"q\",2,x\n3,4\r\"c,d\",5,\"e\r\nf\"\n' > rf_test_csvps_blk; i=0; while [ $i -lt 17 ]; do cat rf_test_csvps_blk rf_test_csvps_blk > rf_test_csvps_blk2; mv rf_test_csvps_blk2 rf_test_csvps_blk; i=$((i+1)); done; cat rf_test_csvps_blk >> rf_test_csvps_q.csv; rm -f rf_test_csvps_blk") -- 0 + +(set Q (.csv.read [STR I64 STR] "rf_test_csvps_q.csv")) +;; 4 rows per block x 2^17 blocks — off-by-one anywhere in the stitching +;; changes this number. +(count Q) -- 524288 +;; b column: 1 + 2 + 4 + 5 per block => 12 x 131072. The short row's missing +;; third field must NOT shift the next row's fields. +(sum (at Q 'b)) -- 1572864 +;; Field-level spot checks at both ends of the file. +(at (at Q 'b) 0) -- 1 +(at (at Q 'c) 1) -- "x" +(at (at Q 'a) 2) -- "3" +(at (at Q 'b) 524287) -- 5 +(at (at Q 'c) 524285) -- "x" +(.sys.exec "rm -f rf_test_csvps_q.csv") -- 0 + +;; ════════════════════════════════════════════════════════════════════════════ +;; 2. Quote-free file — the fast (memchr) state machine, whose terminator +;; grammar differs: only '\n' ends a row and an immediately following '\r' +;; is absorbed into it. The block ends one row with "\n\r" so a boundary +;; landing between those two bytes is exercised. +;; One block = 3 rows, doubled 18 times => 262144 blocks = 786432 rows, +;; ~4.7 MB. +;; ════════════════════════════════════════════════════════════════════════════ +(.sys.exec "printf 'a,b\n' > rf_test_csvps_p.csv; printf '10,20\n30,40\n\r50,60\n' > rf_test_csvps_blk; i=0; while [ $i -lt 18 ]; do cat rf_test_csvps_blk rf_test_csvps_blk > rf_test_csvps_blk2; mv rf_test_csvps_blk2 rf_test_csvps_blk; i=$((i+1)); done; cat rf_test_csvps_blk >> rf_test_csvps_p.csv; rm -f rf_test_csvps_blk") -- 0 + +(set P (.csv.read [I64 I64] "rf_test_csvps_p.csv")) +(count P) -- 786432 +(sum (at P 'a)) -- 23592960 +(sum (at P 'b)) -- 31457280 +(at (at P 'a) 0) -- 10 +(at (at P 'a) 2) -- 50 +(at (at P 'b) 786431) -- 60 +(.sys.exec "rm -f rf_test_csvps_p.csv") -- 0 diff --git a/test/rfl/io/csv_splayed.rfl b/test/rfl/io/csv_splayed.rfl index 41128af25..15c8a5b8b 100644 --- a/test/rfl/io/csv_splayed.rfl +++ b/test/rfl/io/csv_splayed.rfl @@ -257,10 +257,71 @@ (sum (at Rheal 'px)) -- 7.5 (at (at Rheal 's) 1) -- 'bb +;; ════════════════════════════════════════════════════════════════ +;; 7. HAS_NULLS on a CONVERTED SYM column — the two csv.c store sites +;; of issue #416, one per conversion route. +;; +;; Empty cells in a SYM column are canonical nulls (bfb5b380: sym id 0, +;; which domain.c reserves as the empty string at position 0 of every +;; symfile). An in-memory `.csv.read` and a store built from the SAME +;; csv must therefore agree that those cells are null. Two separate +;; places used to drop the bit on the way to disk, and each one is +;; reachable through exactly ONE route — so they need two fixtures: +;; +;; csv_splayed_writer_append -> `.csv.splayed` (streaming; only the +;; NON-SYM arm propagated HAS_NULLS, the SYM arm re-encodes cells as +;; domain positions and never set had_nulls). Reverting that hunk +;; flips the splayed byte below 0x42 -> 0x02 and NOTHING else. +;; +;; csv_materialize_rows -> `.csv.parted` (the per-chunk table it +;; builds is what ray_splay_save persists per part; it carried the +;; pre-bfb5b380 rule and explicitly CLEARED HAS_NULLS for SYM/STR). +;; Reverting that hunk flips the parted byte 0x40 -> 0x00 and +;; NOTHING else. The streaming writer does not depend on it, +;; because its SYM arm tests the position it WRITES rather than the +;; chunk vec's attrs. +;; +;; Both routes need an explicit all-SYMBOL schema: `.csv.splayed` falls +;; back to a full in-memory read + ray_splay_save the moment any column +;; resolves to RAY_STR, which is a third site (ray_col_save_sym_encoded, +;; covered at C level by splay/has_nulls_roundtrip). +;; +;; The assertion reads the on-disk column header directly, because no +;; language verb exposes attrs: byte 0x13 of the 32-byte header is +;; `attrs` (aux[16] then mmod, order, type, attrs). The low bits are the +;; SYM width, so the whole byte is asserted and the widths are pinned +;; too: 0x42 = HAS_NULLS|W32 (the streaming writer is fixed-W32), +;; 0x40 = HAS_NULLS|W8 (ray_splay_save sizes to the part's domain, +;; 3 symbols -> W8), 0x00 = neither. +;; +;; Fixture: 3 rows, both columns holding exactly one empty cell, split +;; into 2-row parts so part 0 has the empties and part 1 has none — +;; the negative case proves the bit is DERIVED, not stamped blindly. +;; a,b = ("", "x") / ("p", "") / ("q", "y") +;; ════════════════════════════════════════════════════════════════ +(.sys.exec "rm -rf rf_test_splayed_nullbit rf_test_splayed_nullpart") -- 0 +(.sys.exec "printf 'a,b\\n,x\\np,\\nq,y\\n' > rf_test_splayed_nullbit.csv") -- 0 + +;; ── route 1: streaming .csv.splayed ── +(count (.csv.splayed [a b] [SYMBOL SYMBOL] "rf_test_splayed_nullbit.csv" "rf_test_splayed_nullbit/")) -- 3 +(at (read-bytes "rf_test_splayed_nullbit/a") 19) -- 0x42 +(at (read-bytes "rf_test_splayed_nullbit/b") 19) -- 0x42 +;; and the reloaded column really does read those cells as null +(count (select {from: (.db.splayed.get "rf_test_splayed_nullbit/") where: (== a "")})) -- 1 + +;; ── route 2: .csv.parted (csv_materialize_rows -> per-part splay save) ── +(count (.csv.parted [a b] [SYMBOL SYMBOL] "rf_test_splayed_nullbit.csv" 2 "rf_test_splayed_nullpart/" 'ct)) -- 3 +;; part 0 = rows ("","x") and ("p","") — one empty in each column +(at (read-bytes "rf_test_splayed_nullpart/0/ct/a") 19) -- 0x40 +(at (read-bytes "rf_test_splayed_nullpart/0/ct/b") 19) -- 0x40 +;; part 1 = row ("q","y") — no empty anywhere, so no bit +(at (read-bytes "rf_test_splayed_nullpart/1/ct/a") 19) -- 0x00 +(at (read-bytes "rf_test_splayed_nullpart/1/ct/b") 19) -- 0x00 + ;; ────────────── cleanup ────────────── ;; CSV files match the Makefile's `rf_test_*.csv` clean rule; splayed ;; dirs we created need explicit removal. -(.sys.exec "rm -rf rf_test_splayed_basic rf_test_splayed_nulls rf_test_splayed_str rf_test_splayed_sym rf_test_splayed_torn rf_test_splayed_*.csv") -- 0 +(.sys.exec "rm -rf rf_test_splayed_basic rf_test_splayed_nulls rf_test_splayed_str rf_test_splayed_sym rf_test_splayed_torn rf_test_splayed_nullbit rf_test_splayed_nullpart rf_test_splayed_*.csv") -- 0 ;; ────────────── reachability notes ────────────── ;; csv_splayed_writer_zero_nulls — only the count<=0 early-return is diff --git a/test/rfl/io/csv_types.rfl b/test/rfl/io/csv_types.rfl index de067b59c..671f73668 100644 --- a/test/rfl/io/csv_types.rfl +++ b/test/rfl/io/csv_types.rfl @@ -211,6 +211,111 @@ (sum (at Ttsv 'a)) -- 9 (sum (at Ttsv 'b)) -- 12 +;; ════════════════════════════════════════════════════════════════════════════ +;; 18. Typed temporal parse rejects malformed input (separators / trailing +;; garbage) instead of silently coercing it. fast_date / fast_time / +;; fast_timestamp validate the ':' and '-' separators, the 'T'|' ' date/time +;; separator, and require the field to be fully consumed (bar a trailing UTC +;; offset on a timestamp). Well-formed values — including signed / >=24h +;; durations and 'Z' / ±HH:MM offsets — still parse. +;; ════════════════════════════════════════════════════════════════════════════ +;; DATE: wrong separators ("/", "x") and trailing garbage → null; valid → value. +(.sys.exec "printf 'a\n2024/01/02\n2024x01x02\n2024-01-02junk\n2024-01-02\n' > rf_test_csv_types_datestrict.csv") -- 0 +(set Tds (.csv.read [DATE] "rf_test_csv_types_datestrict.csv")) +(nil? (at (at Tds 'a) 0)) -- true +(nil? (at (at Tds 'a) 1)) -- true +(nil? (at (at Tds 'a) 2)) -- true +(at (at Tds 'a) 3) -- 2024.01.02 + +;; TIME: wrong separator ("-") and trailing garbage → null; valid → value. +(.sys.exec "printf 'a\n12-34-56\n12:34:56xyz\n12:34:56\n' > rf_test_csv_types_timestrict.csv") -- 0 +(set Tms (.csv.read [TIME] "rf_test_csv_types_timestrict.csv")) +(nil? (at (at Tms 'a) 0)) -- true +(nil? (at (at Tms 'a) 1)) -- true +(at (at Tms 'a) 2) -- 12:34:56.000 + +;; TIMESTAMP: bad date separator, bad 'D' date/time separator, trailing garbage +;; → null; valid 'T'/space forms and a trailing UTC offset still parse. +(.sys.exec "printf 'a\n2024x01x02T01:02:03\n2024-01-02D01:02:03\n2024-01-02T01:02:03junk\n2024-01-02T01:02:03\n2024-01-02T01:00:00+01:00\n' > rf_test_csv_types_tsstrict.csv") -- 0 +(set Tss (.csv.read [TIMESTAMP] "rf_test_csv_types_tsstrict.csv")) +(nil? (at (at Tss 'a) 0)) -- true +(nil? (at (at Tss 'a) 1)) -- true +(nil? (at (at Tss 'a) 2)) -- true +(at (at Tss 'a) 3) -- 2024.01.02D01:02:03.000000000 +;; +01:00 offset is subtracted to yield UTC. +(at (at Tss 'a) 4) -- 2024.01.02D00:00:00.000000000 + +;; Explicit DATE stays strict: timestamp-shaped cells are malformed for a +;; caller-requested DATE column rather than prefix-parsed. +(.sys.exec "printf 'd\n2024-01-02T01:02:03\n2024-01-02\n' > rf_test_csv_types_datesuffix.csv") -- 0 +(set Tdx (.csv.read [DATE] "rf_test_csv_types_datesuffix.csv")) +(nil? (at (at Tdx 'd) 0)) -- true +(at (at Tdx 'd) 1) -- 2024.01.02 + +;; Schema-less inference must use the same strict temporal grammar. Temporal +;; prefixes with unconsumed suffixes or bare fractional dots demote to STR +;; instead of inferring TIME/TIMESTAMP and then silently nulling every row. +(.sys.exec "awk 'BEGIN{print \"ts\"; for(i=0;i<300;i++) printf(\"2024-01-02 01:02:03 UTC%d\\n\",i)}' > rf_test_csv_types_tssuffix_auto.csv") -- 0 +(set Ttsa (.csv.read "rf_test_csv_types_tssuffix_auto.csv")) +(type (at Ttsa 'ts)) -- 'STR +(at (at Ttsa 'ts) 0) -- "2024-01-02 01:02:03 UTC0" +(.sys.exec "awk 'BEGIN{print \"tm\"; for(i=0;i<300;i++) printf(\"%d:34:56 EST\\n\",i)}' > rf_test_csv_types_timesuffix_auto.csv") -- 0 +(set Tmsa (.csv.read "rf_test_csv_types_timesuffix_auto.csv")) +(type (at Tmsa 'tm)) -- 'STR +(at (at Tmsa 'tm) 12) -- "12:34:56 EST" +(.sys.exec "awk 'BEGIN{print \"tm\"; for(i=0;i<300;i++) printf(\"%d:34:56.\\n\",i)}' > rf_test_csv_types_timedot_auto.csv") -- 0 +(set Tmda (.csv.read "rf_test_csv_types_timedot_auto.csv")) +(type (at Tmda 'tm)) -- 'STR +(at (at Tmda 'tm) 12) -- "12:34:56." + +;; Lowercase 't' is accepted as the ISO/RFC3339 date-time separator, matching +;; the already-accepted lowercase 'z' UTC suffix. +(.sys.exec "printf 'ts\n2024-01-02t01:02:03\n2024-01-02t01:02:03z\n' > rf_test_csv_types_tlower.csv") -- 0 +(set Ttl (.csv.read [TIMESTAMP] "rf_test_csv_types_tlower.csv")) +(at (at Ttl 'ts) 0) -- 2024.01.02D01:02:03.000000000 +(at (at Ttl 'ts) 1) -- 2024.01.02D01:02:03.000000000 +(type (at (.csv.read "rf_test_csv_types_tlower.csv") 'ts)) -- 'TIMESTAMP +(.sys.exec "rm -f rf_test_csv_types_datestrict.csv rf_test_csv_types_timestrict.csv rf_test_csv_types_tsstrict.csv rf_test_csv_types_datesuffix.csv rf_test_csv_types_tssuffix_auto.csv rf_test_csv_types_timesuffix_auto.csv rf_test_csv_types_timedot_auto.csv rf_test_csv_types_tlower.csv") -- 0 + +;; ════════════════════════════════════════════════════════════════════════════ +;; 18b. Typed temporal parse rejects impossible CALENDAR dates instead of +;; silently normalizing them. A well-formed "YYYY-MM-DD" with day <= 31 +;; used to pass fast_date()'s coarse bound and then civil_to_days() rolled +;; e.g. "2024-02-31" over into a *different* real day (2024.03.02). The day +;; must now be validated against the actual, leap-aware length of the month, +;; matching the strict (as 'DATE str) cast. fast_timestamp() reuses +;; fast_date(), so [TIMESTAMP] inherits the same validation. +;; ════════════════════════════════════════════════════════════════════════════ +;; Rows 0-4 are impossible dates → null; rows 5-7 are valid → value. +;; 0 2024-02-31 Feb never has 31 (was silently 2024.03.02) +;; 1 2024-04-31 Apr has 30 days (was silently 2024.05.01) +;; 2 2024-06-31 Jun has 30 days +;; 3 2023-02-29 non-leap Feb (was silently 2023.03.01) +;; 4 2100-02-29 century, not divisible by 400 → not a leap year +;; 5 2024-02-29 leap year (÷4) → valid +;; 6 2000-02-29 leap year (÷400) → valid +;; 7 2024-01-31 31-day month → valid +(.sys.exec "printf 'a\n2024-02-31\n2024-04-31\n2024-06-31\n2023-02-29\n2100-02-29\n2024-02-29\n2000-02-29\n2024-01-31\n' > rf_test_csv_types_caldate.csv") -- 0 +(set Tcd (.csv.read [DATE] "rf_test_csv_types_caldate.csv")) +(count Tcd) -- 8 +(nil? (at (at Tcd 'a) 0)) -- true +(nil? (at (at Tcd 'a) 1)) -- true +(nil? (at (at Tcd 'a) 2)) -- true +(nil? (at (at Tcd 'a) 3)) -- true +(nil? (at (at Tcd 'a) 4)) -- true +(at (at Tcd 'a) 5) -- 2024.02.29 +(at (at Tcd 'a) 6) -- 2000.02.29 +(at (at Tcd 'a) 7) -- 2024.01.31 + +;; TIMESTAMP shares the leading date parse: an impossible calendar day nulls the +;; whole timestamp, while a valid leap day parses. +(.sys.exec "printf 'ts\n2024-02-31T00:00:00\n2023-02-29T12:00:00\n2024-02-29T12:00:00\n' > rf_test_csv_types_calts.csv") -- 0 +(set Tct (.csv.read [TIMESTAMP] "rf_test_csv_types_calts.csv")) +(nil? (at (at Tct 'ts) 0)) -- true +(nil? (at (at Tct 'ts) 1)) -- true +(at (at Tct 'ts) 2) -- 2024.02.29D12:00:00.000000000 +(.sys.exec "rm -f rf_test_csv_types_caldate.csv rf_test_csv_types_calts.csv") -- 0 + ;; ════════════════════════════════════════════════════════════════════════════ ;; 18. Short row guard (p >= row_end path, lines 918+/1086+) ;; Row 1 has fewer fields than header → remaining columns get null/default. diff --git a/test/rfl/join/guid_key.rfl b/test/rfl/join/guid_key.rfl new file mode 100644 index 000000000..66b402268 --- /dev/null +++ b/test/rfl/join/guid_key.rfl @@ -0,0 +1,25 @@ +;; guid_key.rfl -- equi-join keys must compare full 16-byte GUID cells. +;; +;; Regression: join hashing used read_col_i64 on GUID columns, effectively +;; reading bytes at row offsets instead of row*16 cells. A right key vector +;; derived through `at` has a distinct buffer, so the old path silently +;; produced no matches. + +(set gs (guid 5)) +(set L (table [k x] (list gs [1 2 3 4 5]))) +(set R (table [k y] (list (at gs [1 3]) [222 444]))) +(set LJ (left-join [k] L R)) +(set IJ (inner-join [k] L R)) +(set FJ (full-join [k] L R)) +(set AJ (anti-join [k] L R)) + +(at LJ 'y) -- [0Nl 222 0Nl 444 0Nl] +(count IJ) -- 2 +(at IJ 'x) -- [2 4] +(at IJ 'y) -- [222 444] + +;; Full join keeps the matched rows instead of treating every right row as +;; unmatched, and anti-join excludes the two matching GUID keys. +(count FJ) -- 5 +(sum (at FJ 'y)) -- 666 +(at AJ 'x) -- [1 3 5] diff --git a/test/rfl/join/null_key_equality.rfl b/test/rfl/join/null_key_equality.rfl new file mode 100644 index 000000000..67db307b7 --- /dev/null +++ b/test/rfl/join/null_key_equality.rfl @@ -0,0 +1,95 @@ +;; null_key_equality.rfl -- a null equi-join key equals another null key. +;; +;; Regression: hash_row_keys handed every null-keyed row a private, row-derived +;; hash and join_keys_eq returned false the moment either side was null, so a +;; null key matched nothing -- not even a null sitting in the same cell of the +;; same table. Two consequences, both pinned below: +;; +;; * `anti-join [cols] X X` was NON-EMPTY whenever a key column held a null. +;; Self-anti-join must be empty for every table and every key set; a service +;; using anti-join to find not-yet-seen tuples re-reported every null-keyed +;; tuple on every pass and grew without bound. +;; * left-join filled a null payload for a left row whose null key DID have a +;; match on the right, instead of returning that match. +;; +;; null == null is the rule the rest of the runtime already applies to key +;; columns: `distinct` keeps exactly one null (test/rfl/null/distinct.rfl), +;; group-by folds nulls into a single group, and `in`/atom_eq answer true for +;; two nulls (collection.c). As-of join is the ONE documented exception and is +;; unchanged -- pinned at the bottom. + +;; ── The reported reproduction ───────────────────────────────────────────── +;; A left-join miss produces a null V; anti-joining the result against ITSELF +;; on V must still be empty. +(set NKL (table [K] (list (as 'I32 [1 2 3])))) +(set NKR (table [K V] (list (as 'I32 [1 2]) (as 'F64 [10.0 20.0])))) +(set NKJ (left-join [K] NKL NKR)) +(count (select {from: NKJ where: (nil? V)})) -- 1 +(count (anti-join [V] NKJ NKJ)) -- 0 +(count (anti-join [K] NKJ NKJ)) -- 0 + +;; ── Self-anti-join is empty for every key type that can carry a null ────── +(set NKT (table [i f s u] (list [1 0N 3] (as 'F64 [1.0 0N 3.0]) (as 'SYM ["a" "" "c"]) (as 'STR ["a" "" "c"])))) +(count (anti-join [i] NKT NKT)) -- 0 +(count (anti-join [f] NKT NKT)) -- 0 +(count (anti-join [s] NKT NKT)) -- 0 +(count (anti-join [u] NKT NKT)) -- 0 +(count (anti-join [i f] NKT NKT)) -- 0 +(count (anti-join [i f s u] NKT NKT)) -- 0 + +;; ── A null key MATCHES a null key: it is not merely "kept" ──────────────── +(set NKA (table [s x] (list (as 'SYM ["a" "" "c"]) [1 2 3]))) +(set NKB (table [s y] (list (as 'SYM ["" "c"]) [20 30]))) +(at (left-join [s] NKA NKB) 'y) -- [0Nl 20 30] +(count (inner-join [s] NKA NKB)) -- 2 +(at (anti-join [s] NKA NKB) 'x) -- [1] + +;; ── ...and a null still never equals a NON-null ─────────────────────────── +(set NKC (table [s z] (list (as 'SYM ["a" "b"]) [10 20]))) +(count (inner-join [s] NKA NKC)) -- 1 +(at (anti-join [s] NKA NKC) 'x) -- [2 3] + +;; ── F64: the null is a NaN payload, so `!=` alone would reject it ───────── +(set NKF (table [f n] (list (as 'F64 [1.0 0N 3.0]) [1 2 3]))) +(set NKG (table [f m] (list (as 'F64 [0N 3.0]) [200 300]))) +(at (left-join [f] NKF NKG) 'm) -- [0Nl 200 300] +(count (anti-join [f] NKF NKG)) -- 1 + +;; ── STR keys: the radix path specializes single STR keys onto raw +;; descriptors, the chained path goes through join_keys_eq. Same answer. +(set NKU (table [u x] (list (as 'STR ["a" "" "c"]) [1 2 3]))) +(set NKV (table [u y] (list (as 'STR ["" "c"]) [20 30]))) +(at (left-join [u] NKU NKV) 'y) -- [0Nl 20 30] +(at (anti-join [u] NKU NKV) 'x) -- [1] + +;; ── Multi-key: a null in ONE key column does not swallow the other ──────── +(set NKM (table [a b w] (list (as 'SYM ["p" "p" ""]) [1 0N 1] [10 20 30]))) +(set NKN2 (table [a b] (list (as 'SYM ["p" ""]) [0N 1]))) +(at (anti-join [a b] NKM NKN2) 'w) -- [10] +(count (anti-join [a b] NKM NKM)) -- 0 + +;; ── The radix path (build side past RAY_PARALLEL_THRESHOLD = 65536) reaches +;; the same conclusion as the chained hash table used for small inputs. +;; NKBIG key k: row 0 null, row i (i>0) holds i-1; payload v holds 100+i. +;; Asserted on sums, not positions: the radix path consolidates per +;; partition, so left-row output order is not part of the contract here. +(set NKN 70000) +(set NKBIG (table [k v] (list (concat [0N] (til (- NKN 1))) (+ 100 (til NKN))))) +(count NKBIG) -- 70000 +(set NKPROBE (table [k p] (list [0N 5 999999] [1 2 3]))) +(set NKLJ (left-join [k] NKPROBE NKBIG)) +(count NKLJ) -- 3 +;; 100 (the null key matched right row 0) + 106 (k=5 sits at right row 6) +(sum (at NKLJ 'v)) -- 206 +(count (select {from: NKLJ where: (nil? v)})) -- 1 +(count (inner-join [k] NKPROBE NKBIG)) -- 2 +(at (anti-join [k] NKPROBE NKBIG) 'p) -- [3] +(count (anti-join [k] NKBIG NKBIG)) -- 0 + +;; ── As-of join is the documented exception and is NOT changed. Its merge +;; walk skips null-keyed right rows and lets null-keyed left rows fall +;; through to the left-outer null fill; it never routes through +;; join_keys_eq. See docs/queries/joins.md, "Null-key semantics". +(set NKAT (table [S Time Price] (list (as 'SYM ["" "b"]) [10:00:01.000 10:00:01.000] (as 'F64 [1.0 2.0])))) +(set NKAQ (table [S Time Bid] (list (as 'SYM ["" "b"]) [10:00:00.000 10:00:00.000] (as 'F64 [99.0 88.0])))) +(at (asof-join [S Time] NKAT NKAQ) 'Bid) -- (as 'F64 [0Nf 88.0]) diff --git a/test/rfl/join/str_key_nyi.rfl b/test/rfl/join/str_key_nyi.rfl index 8ec45a0d0..3bc2658a7 100644 --- a/test/rfl/join/str_key_nyi.rfl +++ b/test/rfl/join/str_key_nyi.rfl @@ -1,27 +1,30 @@ -;; str_key_nyi.rfl — STR equality-key columns are unsupported in the asof and -;; window join kernels and must be DECLINED, not silently mis-answered. +;; str_key_nyi.rfl -- unsupported equality-key columns in the asof and window +;; join kernels must be DECLINED, not silently mis-answered. ;; ;; Root cause: both kernels read equality-key cells through read_col_i64 ;; (asof via asof_eq_lread; window when it sorts/probes the right side), and -;; read_col_i64 has no RAY_STR case — a STR column falls into the byte-wide -;; default. asof then mismatches outright (a key that should match nulls -;; out); window only reads one byte per row, so small key sets coincide by -;; luck but enough distinct keys collide and cross-contaminate groups, so the -;; aggregates are WRONG. The base equi-join (inner/left/anti) uses a separate -;; STR-aware kernel and stays correct, so the fix is scoped to asof + window: -;; reject a STR eq-key on either side with `nyi` instead of returning corrupt -;; data. window-join1 shares the window kernel; the 4-argument compatibility +;; read_col_i64 can only represent bool/u8/i16/i32/i64/date/time/timestamp/sym. +;; STR, GUID, F32, F64, and object-shaped keys otherwise compare the wrong +;; bytes and can corrupt matches or aggregates. The base equi-join uses a +;; separate type-aware kernel and stays correct, so the fix is scoped to asof + +;; window. window-join1 shares the window kernel; the 4-argument compatibility ;; window forms fall through to the asof executor, so they need the same guard. ;; ── asof-join: STR equality key → nyi (both operand orders) ────────── (set tr (table [Sym Time Price] (list ["A" "A"] [12:00:01 12:00:04] [100 101])))(set qs (table [Sym Time Bid] (list ["A" "A"] [12:00:00 12:00:05] [99 100])))(asof-join [Sym Time] tr qs) !- nyi (set tr (table [Sym Time Price] (list ["A" "A"] [12:00:01 12:00:04] [100 101])))(set qs (table [Sym Time Bid] (list ["A" "A"] [12:00:00 12:00:05] [99 100])))(asof-join [Sym Time] qs tr) !- nyi +(set G (guid 2))(set trG (table [K Time Price] (list G [12:00:01 12:00:04] [100 101])))(set qsG (table [K Time Bid] (list (at G [1 0]) [12:00:00 12:00:05] [20 10])))(asof-join [K Time] trG qsG) !- nyi +(set trF (table [K Time Price] (list [1.5 2.5] [12:00:01 12:00:04] [100 101])))(set qsF (table [K Time Bid] (list [2.5 1.5] [12:00:00 12:00:05] [20 10])))(asof-join [K Time] trF qsF) !- nyi ;; ── window-join / window-join1: STR equality key → nyi ─────────────── (set wt (table [Sym Time Price] (list ["a" "a"] [10:00:01.000 10:00:05.000] [100 200])))(set wq (table [Sym Time Bid] (list ["a" "a" "a"] [10:00:00.000 10:00:02.000 10:00:04.000] [99 100 101])))(set wi (map-left + [-2000 2000] (at wt 'Time)))(window-join [Sym Time] wi wt wq {minBid: (min Bid)}) !- nyi (set wt (table [Sym Time Price] (list ["a" "a"] [10:00:01.000 10:00:05.000] [100 200])))(set wq (table [Sym Time Bid] (list ["a" "a" "a"] [10:00:00.000 10:00:02.000 10:00:04.000] [99 100 101])))(set wi (map-left + [-2000 2000] (at wt 'Time)))(window-join1 [Sym Time] wi wt wq {minBid: (min Bid)}) !- nyi (set wt (table [Sym Time Price] (list ["a" "a"] [10:00:01.000 10:00:05.000] [100 200])))(set wq (table [Sym Time Bid] (list ["a" "a" "a"] [10:00:00.000 10:00:02.000 10:00:04.000] [99 100 101])))(at (window-join wt wq [Sym] 'Time) 'Bid) !- nyi (set wt (table [Sym Time Price] (list ["a" "a"] [10:00:01.000 10:00:05.000] [100 200])))(set wq (table [Sym Time Bid] (list ["a" "a" "a"] [10:00:00.000 10:00:02.000 10:00:04.000] [99 100 101])))(at (window-join1 wt wq [Sym] 'Time) 'Bid) !- nyi +(set WG (guid 2))(set wtG (table [K Time Price] (list WG [10:00:01.000 10:00:05.000] [100 200])))(set wqG (table [K Time Bid] (list (at WG [0 0 1]) [10:00:00.000 10:00:02.000 10:00:04.000] [99 100 101])))(set wiG (map-left + [-2000 2000] (at wtG 'Time)))(window-join [K Time] wiG wtG wqG {minBid: (min Bid)}) !- nyi +(set WF (table [K Time Price] (list [1.5 2.5] [10:00:01.000 10:00:05.000] [100 200])))(set WQF (table [K Time Bid] (list [1.5 1.5 2.5] [10:00:00.000 10:00:02.000 10:00:04.000] [99 100 101])))(set WIF (map-left + [-2000 2000] (at WF 'Time)))(window-join1 [K Time] WIF WF WQF {minBid: (min Bid)}) !- nyi +(set WG (guid 2))(set wtG (table [K Time Price] (list WG [10:00:01.000 10:00:05.000] [100 200])))(set wqG (table [K Time Bid] (list (at WG [0 0 1]) [10:00:00.000 10:00:02.000 10:00:04.000] [99 100 101])))(at (window-join wtG wqG [K] 'Time) 'Bid) !- nyi +(set WF (table [K Time Price] (list [1.5 2.5] [10:00:01.000 10:00:05.000] [100 200])))(set WQF (table [K Time Bid] (list [1.5 1.5 2.5] [10:00:00.000 10:00:02.000 10:00:04.000] [99 100 101])))(at (window-join1 WF WQF [K] 'Time) 'Bid) !- nyi ;; ── SYM equality keys keep working and stay order-independent ──────── (set KS (as 'sym ["AAPL" "AAPL"]))(set trS (table [Sym Time Price] (list KS [12:00:01 12:00:04] [100 101])))(set qsS (table [Sym Time Bid] (list KS [12:00:00 12:00:05] [99 100])))(at (asof-join [Sym Time] trS qsS) 'Bid) -- [99 99] diff --git a/test/rfl/linkop/coverage.rfl b/test/rfl/linkop/coverage.rfl index 486076044..6aebc2bb5 100644 --- a/test/rfl/linkop/coverage.rfl +++ b/test/rfl/linkop/coverage.rfl @@ -203,7 +203,7 @@ linked_sd.name -- (list 'carol 'alice 'bob 'alice) (set linked_sdn (.col.link 'dim_sd rids_sdn)) (set res_sdn linked_sdn.name) (.col.link? linked_sdn) -- true -(nil? (at res_sdn 1)) -- false +(nil? (at res_sdn 1)) -- true (at res_sdn 0) -- 'carol (at res_sdn 2) -- 'bob diff --git a/test/rfl/null/sort.rfl b/test/rfl/null/sort.rfl index 2df0ee233..2312ae706 100644 --- a/test/rfl/null/sort.rfl +++ b/test/rfl/null/sort.rfl @@ -63,16 +63,16 @@ (at (at (xasc Tn 'k) 'k) 4) -- 3 ;; ────────────── (select {asc:}) exec_sort path — nulls land LAST ────────────── -;; NOTE: the (select {asc: k}) exec_sort path puts nulls LAST, the OPPOSITE of -;; (asc vec)/xasc which put nulls FIRST. Same key column [2 0Nl 1 0Nl 3] yields -;; [0Nl 0Nl 1 2 3] under xasc but [1 2 3 0Nl 0Nl] under (select {asc:}). -;; This split is asserted to its ACTUAL behaviour, not normalised away. -(at (select {from: Tn asc: k}) 'k) -- [1 2 3 0Nl 0Nl] -(nil? (at (at (select {from: Tn asc: k}) 'k) 4)) -- true -(nil? (at (at (select {from: Tn asc: k}) 'k) 3)) -- true -;; survivors still ascend ahead of the trailing null block: -(at (at (select {from: Tn asc: k}) 'k) 0) -- 1 -(at (at (select {from: Tn asc: k}) 'k) 2) -- 3 +;; A null is the smallest value, so ascending puts nulls first — the same +;; answer (asc vec)/xasc give. These two used to disagree: the query path +;; put nulls last while the bare verb put them first, and both were asserted +;; as correct (#417). +(at (select {from: Tn asc: k}) 'k) -- [0Nl 0Nl 1 2 3] +(nil? (at (at (select {from: Tn asc: k}) 'k) 0)) -- true +(nil? (at (at (select {from: Tn asc: k}) 'k) 1)) -- true +;; survivors still ascend behind the leading null block: +(at (at (select {from: Tn asc: k}) 'k) 2) -- 1 +(at (at (select {from: Tn asc: k}) 'k) 4) -- 3 (count (select {from: Tn asc: k})) -- 5 ;; ────────────── take with nulls — negative count slices from tail ────────────── diff --git a/test/rfl/null/sort_null_placement.rfl b/test/rfl/null/sort_null_placement.rfl new file mode 100644 index 000000000..7f11b4a47 --- /dev/null +++ b/test/rfl/null/sort_null_placement.rfl @@ -0,0 +1,175 @@ +;; Where a null lands in a sort, pinned for every path that can run. +;; +;; A null is the SMALLEST value: ascending puts nulls first, descending last. +;; That policy lives in one place (sort_nulls_first, ops/internal.h) and every +;; path takes its default from there. +;; +;; The reason this file exists (#417): the policy used to be spelled out +;; separately in four places, and they did not agree — sort_cmp derived it from +;; `desc`, sort_indices_ex and the query builder from `!desc`, and the fused +;; top-k hardcoded its own. Which one answered depended on the ROW COUNT (a +;; small input takes the comparison path, a large one the radix path) and on +;; the COLUMN TYPE (SYM, STR and numeric arms are separate). So the same query +;; over the same data gave different answers as the table grew. +;; +;; Every check below therefore comes in pairs: the same question asked under +;; the comparison path and under the radix path, and asked of SYM, STR and a +;; numeric column. A single-size or single-type test would not have caught it. + +;; ── Small input: comparison path ─────────────────────────────────────────── +(at (asc [3 0N 1 2]) 0) -- 0Nl +(at (desc [3 0N 1 2]) 3) -- 0Nl + +;; `'` on its own is the empty symbol, which is a null. +(set _Ss ['b ' 'c ' 'a]) +(nil? (at (asc _Ss) 0)) -- true +(nil? (at (asc _Ss) 4)) -- false +(nil? (at (desc _Ss) 4)) -- true +(nil? (at (desc _Ss) 0)) -- false + +(set _St ["b" "" "c" "" "a"]) +(nil? (at (asc _St) 0)) -- true +(nil? (at (asc _St) 4)) -- false +(nil? (at (desc _St) 4)) -- true +(nil? (at (desc _St) 0)) -- false + +;; ── Large input: radix / parallel path. 16384 rows is four times +;; RADIX_SORT_THRESHOLD, so this is a different kernel from the block +;; above, not the same one with more rows. ──────────────────────────────── +(.sys.exec "rm -f rf_np.csv rf_np_blk") -- 0 +(.sys.exec "printf 's,u,n\n' > rf_np.csv; printf ',,\nb,b,7\n,,\nc,c,3\n' > rf_np_blk; i=0; while [ $i -lt 12 ]; do cat rf_np_blk rf_np_blk > rf_np_blk2; mv rf_np_blk2 rf_np_blk; i=$((i+1)); done; cat rf_np_blk >> rf_np.csv; rm -f rf_np_blk") -- 0 + +(set B (.csv.read [SYMBOL STR I64] "rf_np.csv")) +(count B) -- 16384 + +;; SYM: nulls first on asc, last on desc. +(nil? (at (asc (at B 's)) 0)) -- true +(nil? (at (asc (at B 's)) 16383)) -- false +(nil? (at (desc (at B 's)) 0)) -- false +(nil? (at (desc (at B 's)) 16383)) -- true + +;; STR: the same answers as the SYM column it mirrors. These two used to +;; disagree with each other at this size. +(nil? (at (asc (at B 'u)) 0)) -- true +(nil? (at (asc (at B 'u)) 16383)) -- false +(nil? (at (desc (at B 'u)) 0)) -- false +(nil? (at (desc (at B 'u)) 16383)) -- true + +;; Numeric: unchanged by the fix, and here to prove the three types agree. +(nil? (at (asc (at B 'n)) 0)) -- true +(nil? (at (desc (at B 'n)) 16383)) -- true + +;; ── The same question through a QUERY sort, which took its default from a +;; different place than the bare verb did. The numeric column is what +;; shows it: a SYM or STR null is IN-BAND (sym id 0, a zero-length +;; descriptor) and sorts smallest on payload alone, so those columns land +;; nulls first whatever the policy says. A numeric null is out of band and +;; only the policy places it. ──────────────────────────────────────────── +(nil? (at (at (select {from: B asc: n}) 'n) 0)) -- true +(nil? (at (at (select {from: B asc: n}) 'n) 16383)) -- false +(nil? (at (at (select {from: B desc: n}) 'n) 0)) -- false +(nil? (at (at (select {from: B desc: n}) 'n) 16383)) -- true + +;; ── And through filter + top-k, which runs the fused comparator rather than +;; a sort — a separate implementation of the same policy. The predicate +;; keeps every row, so the k smallest of a null-bearing column are nulls. ─ +(nil? (at (at (select {n: n s: s from: B where: (!= s "zzz") asc: n take: 3}) 'n) 0)) -- true +(nil? (at (at (select {n: n s: s from: B where: (!= s "zzz") asc: n take: 3}) 'n) 2)) -- true +(nil? (at (at (select {n: n s: s from: B where: (!= s "zzz") desc: n take: 3}) 'n) 0)) -- false + +;; ── Window functions sort by their partition keys, and pick between three +;; sort paths by row count — insertion below 64 rows, radix above it, merge +;; otherwise. Placement itself is not visible here, since a group is a run +;; of equal keys and the null run reads the same from either end; what these +;; pin is that the paths agree on WHICH rows are null, across the threshold +;; that chooses between them. ────────────────────────────────────────────── +(set _Ws (table [k v] (list [0N 1 0N 2 1] [10 20 30 40 50]))) +(at (window {from: _Ws part: [k] funcs: {mn: (min v)}}) 'mn) -- [10 20 10 40 20] + +(set _Wk (concat [0N 1 0N 2 1 0N 1 0N 2 1] (til 90))) +(set _Wl (table [k v] (list _Wk (til 100)))) +(count _Wl) -- 100 +;; the four null-key rows form one group: v = 0,2,5,7 → min 0 +(at (at (window {from: _Wl part: [k] funcs: {mn: (min v)}}) 'mn) 0) -- 0 +(at (at (window {from: _Wl part: [k] funcs: {mn: (min v)}}) 'mn) 2) -- 0 +(at (at (window {from: _Wl part: [k] funcs: {mn: (min v)}}) 'mn) 5) -- 0 +(at (at (window {from: _Wl part: [k] funcs: {mn: (min v)}}) 'mn) 7) -- 0 +;; and the non-null groups are unaffected: k=1 rows are 1,4,6,9,11 → min 1 +(at (at (window {from: _Wl part: [k] funcs: {mn: (min v)}}) 'mn) 1) -- 1 + +;; ── A MULTI-KEY sort packs its keys into one 64-bit word when they fit, +;; and that packing has no null leg: a float null is NaN, whose bits +;; encode above every real number, so it would land last on ascending +;; whatever the rule says. Integer keys hide this — their null is +;; INT64_MIN, already the smallest — so only a float key shows it, and +;; only at the sizes where the packing runs. Below 64 rows the +;; comparator answers; above it the packed encode does, first through +;; introsort and then through the radix pass. All three must agree. +;; (#430 review: the packed path used to disagree above 64 rows.) +;; First the plain vector, small enough to read at a glance. Both signs +;; and a value on each side of zero: the encode flips a float's bits to +;; make them sort as integers, and that flip is sign-dependent, so an +;; all-positive vector would exercise half of it. +;; Zero is in there because it is where the flip changes hands: every +;; negative maps below it and every positive above, so a mistake in the +;; sign half of the encode shows up as zero landing on the wrong side. +(asc [3.5 0Nf 1.5 2.5 -1.2 -2.5 -12.3 -0.8 0.3 0.0]) -- [0Nf -12.3 -2.5 -1.2 -0.8 0.0 0.3 1.5 2.5 3.5] +(desc [3.5 0Nf 1.5 2.5 -1.2 -2.5 -12.3 -0.8 0.3 0.0]) -- [3.5 2.5 1.5 0.3 0.0 -0.8 -1.2 -2.5 -12.3 0Nf] + +;; Then the multi-key query on six rows — still the comparator, still +;; readable in full. g breaks the tie between the two -1.2s. +(set _Ft (table [f g] (list [2.5 0Nf -1.2 0Nf -1.2 -12.3] [0 1 1 0 0 0]))) +(at (select {from: _Ft asc: [f g]}) 'f) -- [0Nf 0Nf -12.3 -1.2 -1.2 2.5] +(at (select {from: _Ft asc: [f g]}) 'g) -- [0 1 0 0 1 0] +(at (select {from: _Ft desc: [f g]}) 'f) -- [2.5 -1.2 -1.2 -12.3 0Nf 0Nf] + +;; Above 64 rows the packed encode takes over, and above the radix +;; threshold a third path does. Same question, same answer, read off the +;; two ends. +;; These use NON-NEGATIVE reals on purpose. A negative value encodes far +;; below zero, so min..max spans nearly the whole 64-bit range and the +;; packing declines the key for not fitting — which would make the check +;; pass for the wrong reason. With only non-negative reals the span is +;; small enough that the packing genuinely runs, which is the path under +;; test: with the key ungated it answered [1.5 1.5 1.5] here, and the +;; overflowing negative variant answered correctly while UBSan reported +;; a signed overflow and a 64-bit shift underneath it. +(set _Gt (table [f g] (list (at [1.5 0Nf 2.5] (% (til 100) 3)) (% (til 100) 2)))) +(take (at (select {from: _Gt asc: [f g]}) 'f) 3) -- [0Nf 0Nf 0Nf] +(take (at (select {from: _Gt desc: [f g]}) 'f) 3) -- [2.5 2.5 2.5] + +(set _Ht (table [f g] (list (at [1.5 0Nf 2.5] (% (til 5000) 3)) (% (til 5000) 2)))) +(take (at (select {from: _Ht asc: [f g]}) 'f) 3) -- [0Nf 0Nf 0Nf] +(take (at (select {from: _Ht desc: [f g]}) 'f) 3) -- [2.5 2.5 2.5] + +;; And the negative/zero span too, since it takes the other branch: the +;; answer must be the same whichever way the packing decides. +(set _Nt (table [f g] (list (at [1.5 0Nf -2.5 0.0] (% (til 5000) 4)) (% (til 5000) 2)))) +(take (at (select {from: _Nt asc: [f g]}) 'f) 3) -- [0Nf 0Nf 0Nf] +(take (at (select {from: _Nt desc: [f g]}) 'f) 3) -- [1.5 1.5 1.5] + +;; The integer twin, which agreed all along and must keep agreeing — its +;; null is INT64_MIN, already the smallest, so the packing never had to +;; place it deliberately. +(set _It (table [f g] (list (at [1 0N 2] (% (til 5000) 3)) (% (til 5000) 2)))) +(take (at (select {from: _It asc: [f g]}) 'f) 3) -- [0Nl 0Nl 0Nl] +(take (at (select {from: _It desc: [f g]}) 'f) 3) -- [2 2 2] + +;; ── take must be a PREFIX of the sorted order. This is the contract, not +;; just a matter of taste: the same data placed SYM nulls at opposite ends +;; depending on whether take: was present, because the take path consulted +;; a different rule than the sort did. Stated as a differential rather +;; than as literals, so it holds whatever the placement is. ────────────── +(take (at (select {s: s from: B asc: s}) 's) 6) -- (at (select {s: s n: n from: B where: (!= s 'zzz) asc: s take: 6}) 's) +(take (at (select {n: n from: B desc: n}) 'n) 6) -- (at (select {s: s n: n from: B where: (!= s 'zzz) desc: n take: 6}) 'n) + +;; ── top/bot over a bare vector choose a bounded heap below k = len and a +;; full sort at or above it. The same prefix contract applies across that +;; switch, so the two must not disagree about where nulls sit. ─────────── +(set _Tv [3 0N 1 0N 2]) +(take (asc _Tv) 3) -- (bot _Tv 3) +(bot _Tv 5) -- (asc _Tv) +(take (desc _Tv) 3) -- (top _Tv 3) +(top _Tv 5) -- (desc _Tv) + +(.sys.exec "rm -f rf_np.csv") -- 0 diff --git a/test/rfl/null/sym_no_null.rfl b/test/rfl/null/sym_no_null.rfl index 4e4d3fe9d..f39f3573e 100644 --- a/test/rfl/null/sym_no_null.rfl +++ b/test/rfl/null/sym_no_null.rfl @@ -1,16 +1,15 @@ -;; SYM has no null — the empty symbol ' (sym 0) is a value, mirroring STR "". -;; Parity: empty STR and empty SYM behave identically (no null). -(nil? ') -- false -(nil? "") -- false -;; the empty symbol round-trips through a SYM vector as a value, not null +;; Empty SYM ' and empty STR "" are their canonical in-band null values. +(nil? ') -- true +(nil? "") -- true +;; the empty symbol round-trips through a SYM vector as canonical null (== ' (at (as 'SYM [' a]) 0)) -- true -(nil? (at (as 'SYM [' a]) 0)) -- false -;; FIRST of an all-empty-symbol group is the empty symbol, not null +(nil? (at (as 'SYM [' a]) 0)) -- true +;; FIRST of an all-empty-symbol group is canonical null (set Te (table [k v] (list (as 'SYM [' ']) [1 2]))) -(nil? (at (at (select {f: (first k) by: v from: Te}) 'f) 0)) -- false -;; an empty-symbol vector carries no nulls +(nil? (at (at (select {f: (first k) by: v from: Te}) 'f) 0)) -- true +;; empty-symbol vector cells are detected as null (set sv (as 'SYM [a ' c])) -(nil? (at sv 1)) -- false +(nil? (at sv 1)) -- true ;; ── Task 2 surface: the empty symbol renders as ' (not 0Ns) ── ;; format interpolation of the empty symbol prints the bare quote literal (format "%" ') -- "'" @@ -18,15 +17,13 @@ (== ' (eval (parse "'"))) -- true ;; 0Ns is no longer a literal — it parses as `0 Ns`; eval raises (undefined name) (== 'caught (try (eval (parse "0Ns")) (fn [e] 'caught))) -- true -;; ── Task 4: empty-symbol count-distinct parity (no-null hardening) ── -;; Under the old null-skipping behavior, count(distinct [a ' a ' b]) would -;; give 2 (empty sym skipped as null). With no-null it must give 3. +;; Empty/null remains a distinct and groupable key, matching other typed nulls. (set Tcd (table [s] (list (as 'SYM ['a ' 'a ' 'b])))) -;; distinct count: {a, ', b} = 3 distinct values (not 2) +;; distinct count: {a, ', b} = 3 distinct values (count (distinct (at Tcd 's))) -- 3 ;; group-by produces 3 groups (one per distinct key) (count (select {c: (count s) by: s from: Tcd})) -- 3 -;; STR parity: empty STR "" and empty SYM ' are both values → same distinct count +;; STR parity: canonical empty STR/SYM nulls give the same distinct count (count (distinct (list "a" "" "a" "" "b"))) -- 3 ;; explicitly assert STR and SYM give the same answer (== (count (distinct (at Tcd 's))) (count (distinct (list "a" "" "a" "" "b")))) -- true diff --git a/test/rfl/null/sym_str_null_compare.rfl b/test/rfl/null/sym_str_null_compare.rfl new file mode 100644 index 000000000..40a13b4fc --- /dev/null +++ b/test/rfl/null/sym_str_null_compare.rfl @@ -0,0 +1,226 @@ +;; Equality comparison on NULLABLE SYM / STR columns — fused path vs unfused. +;; +;; A SYM null is sym id 0 and a STR null is a zero-length descriptor: both are +;; IN-BAND ordinary values, unlike a numeric null which is an out-of-band +;; sentinel. That is what lets the fused per-row predicate evaluator compare +;; them for equality on raw payloads (fused_pred.c fp_col_supported_op) once +;; HAS_NULLS started reaching such columns (#416). The property under test is +;; that the fused and unfused kernels give the SAME answer. +;; +;; ── What THIS section does and does NOT cover ────────────────────────────── +;; The pairs below are a plain-filter differential: `where:` with no +;; sort+take, so NEITHER arm reaches the fused evaluator. The fused predicate +;; path is only entered from the fused filter+top-K shape in query.c +;; (`where:` + `asc:/desc:` + `take:`, no `by:`/`nearest:`) — see +;; `ray_fused_topk_supported`. So the `(and … (== f 1.5))` twin here forces +;; nothing: the F64 term does decline the fused compiler, but its partner runs +;; unfused too, and both arms are the same FILTER kernel. +;; +;; What these pairs are still worth: they pin the null-aware FILTER kernel's +;; answers for every literal shape, and every count is asserted against its +;; value by construction, so a pair that agreed on a wrong answer still fails. +;; The real fused-vs-unfused differential — the one that actually exercises +;; fp_col_supported_op's relaxation — is the FUSED TOP-K section at the bottom +;; of this file, and it is the section to extend when that gate moves. +;; +;; Fixture: a 6-row block doubled 12 times = 24576 rows (past any per-row +;; fused threshold), with column `s` empty in the block's FIRST, MIDDLE and +;; LAST rows, `z` empty everywhere, `u` the STR twin of `s`. +;; block rows: (s,z,u,f,n) = ("",_,"",_,null) (b,_,b,_,5) ("",_,"",_,null) +;; (c,_,c,_,7) (b,_,b,_,5) ("",_,"",_,null) +;; per block: 3 empty s, 2 "b", 1 "c" => x4096 = 12288 / 8192 / 4096 +;; `n` is a NULLABLE I64 — the other side of the gate, kept for contrast. + +;; ── scrub stale state ─────────────────────────────────────────────────────── +(.sys.exec "rm -f rf_test_nullcmp.csv rf_test_nullcmp_blk") -- 0 + +(.sys.exec "printf 's,z,u,f,n\n' > rf_test_nullcmp.csv; printf ',,,1.5,\nb,,b,1.5,5\n,,,1.5,\nc,,c,1.5,7\nb,,b,1.5,5\n,,,1.5,\n' > rf_test_nullcmp_blk; i=0; while [ $i -lt 12 ]; do cat rf_test_nullcmp_blk rf_test_nullcmp_blk > rf_test_nullcmp_blk2; mv rf_test_nullcmp_blk2 rf_test_nullcmp_blk; i=$((i+1)); done; cat rf_test_nullcmp_blk >> rf_test_nullcmp.csv; rm -f rf_test_nullcmp_blk") -- 0 + +(set T (.csv.read [SYMBOL SYMBOL STR F64 I64] "rf_test_nullcmp.csv")) +(count T) -- 24576 + +;; ── SYM: != "" — the ClickBench q24/q25/q26 shape ─────────────────────────── +(count (select {from: T where: (!= s "")})) -- 12288 +(count (select {from: T where: (and (!= s "") (== f 1.5))})) -- 12288 + +;; ── SYM: == "" — nulls are matched, not skipped ───────────────────────────── +(count (select {from: T where: (== s "")})) -- 12288 +(count (select {from: T where: (and (== s "") (== f 1.5))})) -- 12288 + +;; ── SYM: a non-empty literal. != "b" must still count the nulls in, the +;; same way the unfused kernel does. ──────────────────────────────────────── +(count (select {from: T where: (== s "b")})) -- 8192 +(count (select {from: T where: (and (== s "b") (== f 1.5))})) -- 8192 +(count (select {from: T where: (!= s "b")})) -- 16384 +(count (select {from: T where: (and (!= s "b") (== f 1.5))})) -- 16384 + +;; ── all-empty SYM column: every row is null ──────────────────────────────── +(count (select {from: T where: (== z "")})) -- 24576 +(count (select {from: T where: (and (== z "") (== f 1.5))})) -- 24576 +(count (select {from: T where: (!= z "")})) -- 0 +(count (select {from: T where: (and (!= z "") (== f 1.5))})) -- 0 + +;; ── STR twin: same answers as the SYM column it mirrors ──────────────────── +(count (select {from: T where: (== u "")})) -- 12288 +(count (select {from: T where: (and (== u "") (== f 1.5))})) -- 12288 +(count (select {from: T where: (!= u "")})) -- 12288 +(count (select {from: T where: (and (!= u "") (== f 1.5))})) -- 12288 + +;; ── NULLABLE I64: the OTHER side of the gate. A numeric null is an +;; out-of-band sentinel, so fp_col_supported_op still rejects the column and +;; both forms run unfused. Asserted so the boundary is covered: if someone +;; admits numeric columns, these must keep agreeing (they do for a constant +;; that is not itself the sentinel — which is exactly why the numeric arm +;; needs more than this test before it could ever be relaxed). +(count (select {from: T where: (!= n 5)})) -- 16384 +(count (select {from: T where: (and (!= n 5) (== f 1.5))})) -- 16384 +(count (select {from: T where: (== n 5)})) -- 8192 +(count (select {from: T where: (and (== n 5) (== f 1.5))})) -- 8192 + +;; ════════════════════════════════════════════════════════════════════════════ +;; ORDERING is deliberately NOT covered by the in-band argument, and is NOT +;; asserted here — because it is not currently a spec. Measured on this very +;; fixture (and identical on the pre-relaxation build, so pre-existing): +;; +;; 24576 rows 6 rows +;; SYM asc: nulls FIRST nulls LAST +;; SYM desc: nulls LAST +;; STR asc: nulls LAST +;; STR desc: nulls FIRST +;; +;; So SYM and STR place nulls at OPPOSITE ends for the same direction, and SYM +;; flips with row count (the small-array path and the radix/parallel path +;; disagree: sort_cmp defaults nulls_first to `desc`, sort_indices_ex to +;; `!desc`). Pinning any of that would freeze accidental behaviour. +;; +;; What matters for the relaxation in fused_pred.c is only that ordering was +;; left alone: ray_key_cols_sorted still rejects HAS_NULLS keys for SYM/STR, so +;; the parted ORDER BY shortcut never assumes sym 0 ranks as the empty string. +;; Settle the placement question first; then this section can assert it. +;; ════════════════════════════════════════════════════════════════════════════ + +(.sys.exec "rm -f rf_test_nullcmp.csv") -- 0 + +;; ════════════════════════════════════════════════════════════════════════════ +;; FUSED TOP-K DIFFERENTIAL — the section that actually reaches +;; fp_col_supported_op's relaxation. +;; +;; Routing: `(select {cols… from: T where: asc/desc: take: K})` +;; with no by:/nearest: and every output column a plain source-column name is +;; the ONLY shape that enters ray_fused_topk_select -> fp_compile_pred -> +;; fp_col_supported_op. Each `…_F` binding below was confirmed to fuse under +;; temporary instrumentation in ray_fused_topk_select; each `…_U` twin adds an +;; `(or … (== n -1))` term, which `ray_fused_group_supported` rejects outright +;; (no `or` in its grammar), so the twin never even reaches the executor and +;; runs the FILTER -> SORT_TAKE pipeline instead. `(== n -1)` matches nothing +;; (n = til N), so the two arms describe the SAME row set. +;; +;; `n` is a distinct row id AND the sort key, so the emitted `n` column pins +;; row selection and order together, and its golden is derivable by hand: +;; e.g. `!= s ""` keeps n % 6 in {1,2,4}, so descending from N-1 (≡ 5, empty) +;; the first five keepers are N-2, N-4, N-5, N-8, N-10. +;; +;; The key column itself is checked with literal "" filters rather than `==` +;; on the SYM column, so no assertion depends on null-vs-null comparison +;; semantics. +;; +;; Size: 3 145 728 rows (2^19 x the same 6-row pattern), built in-language so +;; the ≥2.5M scale costs no CSV. Well past every morsel/parallel threshold on +;; the fused scan. +;; ════════════════════════════════════════════════════════════════════════════ + +(set FN 3145728) +(set fs (as 'SYM (at ["" "b" "c" "" "b" ""] (% (til FN) 6)))) +(set fz (as 'SYM (at [""] (* 0 (til FN))))) +(set fn_ (til FN)) +(set FT (table [s z n] (list fs fz fn_))) +(count FT) -- 3145728 + +;; ── != "" (the ClickBench q24/q25/q26 predicate) ─────────────────────────── +(set FA_F (select {s: s n: n from: FT where: (!= s "") desc: n take: 5})) +(set FA_U (select {s: s n: n from: FT where: (or (!= s "") (== n -1)) desc: n take: 5})) +(at FA_F 'n) -- [3145726 3145724 3145723 3145720 3145718] +(at FA_U 'n) -- [3145726 3145724 3145723 3145720 3145718] +(count (select {from: FA_F where: (== s "")})) -- 0 +(count (select {from: FA_U where: (== s "")})) -- 0 + +;; ── == "" : the nulls are the match, and every emitted key must BE null ──── +(set FB_F (select {s: s n: n from: FT where: (== s "") desc: n take: 5})) +(set FB_U (select {s: s n: n from: FT where: (or (== s "") (== n -1)) desc: n take: 5})) +(at FB_F 'n) -- [3145727 3145725 3145722 3145721 3145719] +(at FB_U 'n) -- [3145727 3145725 3145722 3145721 3145719] +(count (select {from: FB_F where: (== s "")})) -- 5 +(count (select {from: FB_U where: (== s "")})) -- 5 + +;; ── non-empty literal, == : nulls must NOT be swept in ───────────────────── +(set FC_F (select {s: s n: n from: FT where: (== s "b") desc: n take: 5})) +(set FC_U (select {s: s n: n from: FT where: (or (== s "b") (== n -1)) desc: n take: 5})) +(at FC_F 'n) -- [3145726 3145723 3145720 3145717 3145714] +(at FC_U 'n) -- [3145726 3145723 3145720 3145717 3145714] +(count (select {from: FC_F where: (== s "")})) -- 0 + +;; ── non-empty literal, != : nulls must be counted IN (asc, so from row 0) ── +(set FD_F (select {s: s n: n from: FT where: (!= s "b") asc: n take: 5})) +(set FD_U (select {s: s n: n from: FT where: (or (!= s "b") (== n -1)) asc: n take: 5})) +(at FD_F 'n) -- [0 2 3 5 6] +(at FD_U 'n) -- [0 2 3 5 6] +;; of [0 2 3 5 6], only n=2 ("c") is non-empty — 0/3/5/6 are all empty +(count (select {from: FD_F where: (== s "")})) -- 4 + +;; ── all-empty column: every row null. != "" selects nothing, == "" all. ─── +(count (select {z: z n: n from: FT where: (!= z "") desc: n take: 5})) -- 0 +(count (select {z: z n: n from: FT where: (or (!= z "") (== n -1)) desc: n take: 5})) -- 0 +(set FE_F (select {z: z n: n from: FT where: (== z "") desc: n take: 5})) +(set FE_U (select {z: z n: n from: FT where: (or (== z "") (== n -1)) desc: n take: 5})) +(at FE_F 'n) -- [3145727 3145726 3145725 3145724 3145723] +(at FE_U 'n) -- [3145727 3145726 3145725 3145724 3145723] +(count (select {from: FE_F where: (== z "")})) -- 5 + +;; ── STR twin ─────────────────────────────────────────────────────────────── +;; A nullable STR column reaches the fused evaluator ONLY through its +;; RAY_IDX_DICT (fp_check_simple_cmp / fp_compile_cmp both require it: the +;; comparison is driven on the int32 dict-code vector, not the descriptors). +;; There is no language verb that builds one — `.idx.dict` does not exist and +;; dict conversion is a splayed-storage attribute (splay.c only computes it for +;; STR columns of >= 65536 rows). So the twin needs a converted store, and it +;; is deliberately smaller than the SYM fixture: 131072 rows is the smallest +;; power of two that clears splay.c's dict threshold. Confirmed fused under +;; the same instrumentation; the `.idx.info` assertion below is what keeps the +;; shape honest — if a future change stops attaching the dict, the kind flips +;; and this test says so instead of silently measuring the unfused path twice. +(.sys.exec "rm -rf rf_test_nullcmp_store") -- 0 +(set SN 98304) +(set SU (table [u n] (list (at ["" "b" "c" "" "b" ""] (% (til SN) 6)) (til SN)))) +(count (.db.splayed.set "rf_test_nullcmp_store" SU)) -- 98304 +(set ST (.db.splayed.get "rf_test_nullcmp_store" 'SU)) +(count ST) -- 98304 +(.idx.info (at ST 'u)) -- {kind:dict length:98304 parent_type:13 saved_attrs:64 n_distinct:3} + +(set SA_F (select {u: u n: n from: ST where: (!= u "") desc: n take: 5})) +(set SA_U (select {u: u n: n from: ST where: (or (!= u "") (== n -1)) desc: n take: 5})) +(at SA_F 'n) -- [98302 98300 98299 98296 98294] +(at SA_U 'n) -- [98302 98300 98299 98296 98294] +(count (select {from: SA_F where: (== u "")})) -- 0 + +(set SB_F (select {u: u n: n from: ST where: (== u "") desc: n take: 5})) +(set SB_U (select {u: u n: n from: ST where: (or (== u "") (== n -1)) desc: n take: 5})) +(at SB_F 'n) -- [98303 98301 98298 98297 98295] +(at SB_U 'n) -- [98303 98301 98298 98297 98295] +(count (select {from: SB_F where: (== u "")})) -- 5 + +(set SC_F (select {u: u n: n from: ST where: (== u "b") desc: n take: 5})) +(set SC_U (select {u: u n: n from: ST where: (or (== u "b") (== n -1)) desc: n take: 5})) +(at SC_F 'n) -- [98302 98299 98296 98293 98290] +(at SC_U 'n) -- [98302 98299 98296 98293 98290] + +;; ── the boundary: ops the relaxation deliberately does NOT admit ─────────── +;; LIKE keeps the strict gate (fp_col_supported_op is called with eq_or_ne=0), +;; and ordering ops on SYM are rejected before the gate is even consulted. +;; Both must keep agreeing with their unfused twins — this is where a future +;; loosening of the gate would first have to prove itself. +(set FL_F (select {s: s n: n from: FT where: (like s "*b*") desc: n take: 5})) +(set FL_U (select {s: s n: n from: FT where: (or (like s "*b*") (== n -1)) desc: n take: 5})) +(at FL_F 'n) -- [3145726 3145723 3145720 3145717 3145714] +(at FL_U 'n) -- [3145726 3145723 3145720 3145717 3145714] + +(.sys.exec "rm -rf rf_test_nullcmp_store") -- 0 diff --git a/test/rfl/ops/builtins_branch_cov.rfl b/test/rfl/ops/builtins_branch_cov.rfl index 241477e9a..ecd7ef0eb 100644 --- a/test/rfl/ops/builtins_branch_cov.rfl +++ b/test/rfl/ops/builtins_branch_cov.rfl @@ -150,8 +150,8 @@ ;; null → BOOL — produces null BOOL sentinel (nil? (as 'BOOL 0Nl)) -- true -;; empty sym → SYMBOL (SYM has no null; ' is a value) -(nil? (as 'SYMBOL ')) -- false +;; empty sym → canonical SYMBOL null +(nil? (as 'SYMBOL ')) -- true ;; null → DATE (nil? (as 'DATE 0Nd)) -- true @@ -218,7 +218,7 @@ (as 'BOOL 1.0) -- true ;; F64 → BOOL (as 'BOOL 0.0) -- false ;; F64 → BOOL (zero) (as 'BOOL "hi") -- true ;; STR → BOOL (non-empty) -(nil? (as 'BOOL "")) -- false +(nil? (as 'BOOL "")) -- true ;; --- Cast to STR --- (as 'STR "hi") -- "hi" ;; already STR diff --git a/test/rfl/ops/internal_coverage.rfl b/test/rfl/ops/internal_coverage.rfl index 7a44b8b25..15633da0c 100644 --- a/test/rfl/ops/internal_coverage.rfl +++ b/test/rfl/ops/internal_coverage.rfl @@ -115,7 +115,7 @@ (.sys.exec "printf 'id,name\n1,alice\n2,\n3,charlie\n' > /tmp/rfl_int_cov_null_str.csv") -- 0 (set SN_A (.csv.read [I64 STR] "/tmp/rfl_int_cov_null_str.csv")) (count SN_A) -- 3 -(nil? (at (at SN_A 'name) 1)) -- false +(nil? (at (at SN_A 'name) 1)) -- true (.db.splayed.set "/tmp/rfl_int_cov_null/2024.01.01/t/" SN_A) (set SN_B (table [id name] (list [4 5] (list "dave" "eve")))) @@ -128,14 +128,14 @@ ;; HEAD includes null element at position 1 → parted_head_str calls ;; parted_str_append_elem(seg, 1, pool) → null path lines 287-290. (count (select {from: PN take: 3})) -- 3 -(nil? (at (at (select {from: PN take: 3}) 'name) 1)) -- false +(nil? (at (at (select {from: PN take: 3}) 'name) 1)) -- true (at (at (select {from: PN take: 3}) 'name) 0) -- "alice" (at (at (select {from: PN take: 3}) 'name) 2) -- "charlie" ;; FILTER via exec_filter_head: HEAD(FILTER) fused path calls ;; parted_gather_str_rows → parted_str_append_elem on null element. (count (select {from: PN where: (< id 4) take: 3})) -- 3 -(nil? (at (at (select {from: PN where: (< id 4) take: 3}) 'name) 1)) -- false +(nil? (at (at (select {from: PN where: (< id 4) take: 3}) 'name) 1)) -- true ;; ── 1h. Parted STR with missing column in second partition ───────────── ;; segs[1] = NULL for the STR column when partition 2 lacks the column. @@ -162,8 +162,8 @@ ;; Value-check: partition 1 supplies "alpha","beta"; partition 2 lacks the ;; 'name column so its rows come back as null from the null-segment branch. (first (at (select {from: PNS where: (> id 0) take: 4}) 'name)) -- "alpha" -(nil? (at (at (select {from: PNS where: (> id 0) take: 4}) 'name) 2)) -- false -(nil? (at (at (select {from: PNS where: (> id 0) take: 4}) 'name) 3)) -- false +(nil? (at (at (select {from: PNS where: (> id 0) take: 4}) 'name) 2)) -- true +(nil? (at (at (select {from: PNS where: (> id 0) take: 4}) 'name) 3)) -- true ;; ====================================================================== diff --git a/test/rfl/ops/join_branch_cov.rfl b/test/rfl/ops/join_branch_cov.rfl index c6f26031f..19984fc16 100644 --- a/test/rfl/ops/join_branch_cov.rfl +++ b/test/rfl/ops/join_branch_cov.rfl @@ -9,25 +9,26 @@ ;; ────────────────────────────────────────────────────────────────── ;; L35: hash_row_keys — NULL values in join key column -;; NULL keys should produce unique hashes, so NULLs never match. +;; NULL keys hash to one canonical value: a null matches another null and +;; nothing else. See test/rfl/join/null_key_equality.rfl for the semantics. ;; ────────────────────────────────────────────────────────────────── -;; inner-join with null keys in left — nulls don't match +;; inner-join with a null key on the left only — nothing on the right to match (set jL (table [id val] (list [1 0Nl 3] [10 20 30]))) (set jR (table [id val2] (list [1 3] [100 300]))) (count (inner-join [id] jL jR)) -- 2 (at (inner-join [id] jL jR) 'val) -- [10 30] -;; inner-join with null keys in right — nulls don't match +;; inner-join with a null key on the right only — nothing on the left to match (set jL2 (table [id val] (list [1 2 3] [10 20 30]))) (set jR2 (table [id val2] (list [1 0Nl 3] [100 200 300]))) (count (inner-join [id] jL2 jR2)) -- 2 (at (inner-join [id] jL2 jR2) 'val2) -- [100 300] -;; inner-join with null keys in both sides — nulls never match nulls +;; inner-join with a null key on BOTH sides — null == null, so it matches (set jL3 (table [id val] (list [0Nl 2 3] [10 20 30]))) (set jR3 (table [id val2] (list [0Nl 2 3] [100 200 300]))) -(count (inner-join [id] jL3 jR3)) -- 2 +(count (inner-join [id] jL3 jR3)) -- 3 ;; left-join with null keys — unmatched left rows preserved with null right (set jL4 (table [id val] (list [1 0Nl 3] [10 20 30]))) @@ -68,10 +69,10 @@ (count (inner-join [k1 k2] mkL mkR)) -- 2 (at (inner-join [k1 k2] mkL mkR) 'val2) -- [1000 3000] -;; Multi-key with both nulls — no match +;; Multi-key with a null on both sides of k1 — null == null, so it matches (set mkL2 (table [k1 k2 val] (list [0Nl] [10.0] [100]))) (set mkR2 (table [k1 k2 val2] (list [0Nl] [10.0] [1000]))) -(count (inner-join [k1 k2] mkL2 mkR2)) -- 0 +(count (inner-join [k1 k2] mkL2 mkR2)) -- 1 ;; ────────────────────────────────────────────────────────────────── ;; anti-join with null keys @@ -117,7 +118,7 @@ ;; asof-join: empty-symbol eq key in left → no match (left-outer: row preserved) ;; Row 0 (a, 10:00:01) → quote @10:00:00 = 99 ; Row 1 (', 10:00:03): the empty -;; symbol is a value that doesn't equal 'a → no match (not a null key). +;; symbol is the canonical null key and is skipped → no match. (set ajL3 (table [Sym Time Price] (list [a '] [10:00:01.000 10:00:03.000] [100.0 200.0]))) (set ajR3 (table [Sym Time Bid] (list [a a] [10:00:00.000 10:00:02.000] [99.0 100.0]))) (set ajN3 (asof-join [Sym Time] ajL3 ajR3)) @@ -126,7 +127,7 @@ (nil? (at (at ajN3 'Bid) 1)) -- true ;; asof-join: empty-symbol eq key in right → not matched -;; Right quotes keyed by the empty symbol ' (a value ≠ 'a) match nothing; +;; Right quotes keyed by the canonical empty/null symbol ' match nothing; ;; (a,10:00:01)→99, (a,10:00:03)→100. (set ajL4 (table [Sym Time Price] (list [a a] [10:00:01.000 10:00:03.000] [100.0 200.0]))) (set ajR4 (table [Sym Time Bid] (list [a ' a] [10:00:00.000 10:00:01.500 10:00:02.000] [99.0 50.0 100.0]))) diff --git a/test/rfl/query/guid_like_predicates.rfl b/test/rfl/query/guid_like_predicates.rfl new file mode 100644 index 000000000..061356c46 --- /dev/null +++ b/test/rfl/query/guid_like_predicates.rfl @@ -0,0 +1,82 @@ +;; select-where predicates that used to fail silently. +;; +;; GUID: the fused expression program has no 16-byte loads, and the +;; elementwise fallback routed guid cells through the numeric loops — +;; both silently matched nothing. The compiler now bails GUID columns +;; (EXPR_BAIL_GUID) and the fallback has a memcmp branch, so a guid +;; equality predicate returns the matching rows. +;; +;; like: an unsupported input type in exec_like memset the result to +;; all-false. A list column (splayed string load shape) now delegates +;; to the builtin's list branch; a non-string column raises. + +(set gs (guid 3)) +(set t (table [g v] (list gs [10 20 30]))) +(set g1 (at gs 1)) + +;; guid equality predicate finds its row +(get (select {from: t where: (== g g1)}) 'v) -- [20] +(count (get (select {from: t where: (!= g g1)}) 'v)) -- 2 + +;; guid predicate composes with aggregation +(at (get (select {from: t where: (== g g1) s: (sum v)}) 's) 0) -- 20 + +;; ordering on guid operands is undefined — loud, not silent +(select {from: t where: (< g g1)}) !- type + +;; GUID membership: the typed `in` kernel read guid cells at the wrong width +;; (every cell decoded to 0), so `in`/`not-in` silently matched everything. +;; The kernel now bails guid to the guid-aware hashset path. +(set gsub (at gs [0 2])) +(in gs gsub) -- [true false true] +(not (in gs gsub)) -- [false true false] +(get (select {from: t where: (in g gsub)}) 'v) -- [10 30] +(get (select {from: t where: (not (in g gsub))}) 'v) -- [20] +(at (get (select {from: t where: (in g gsub) s: (sum v)}) 's) 0) -- 40 +;; membership against an empty set matches nothing (no all-true collapse) +(in gs (at gs [])) -- [false false false] +;; Scalar subjects retain builtin scalar semantics; query predicates normalize +;; their result to a row-aligned BOOL vector and keep nulls false. +(set gn (as 'guid "00000000-0000-0000-0000-000000000000")) +(in gn gs) -- false +(not (in gn gs)) -- true +(set gns (list gn (at gs 0))) +(in gns gs) -- [false true] +(not (in gns gs)) -- [true false] + +;; like over a string column inside select-where (table construction +;; normalizes the list to a STR column; the real list-of-atoms shape — +;; a legacy STRL splayed load — is covered by legacy_strl_predicates.rfl) +(set ts (table [s v] (list (list "keep me" "drop" "also keep") [1 2 3]))) +(get (select {from: ts where: (like s "*keep*")}) 'v) -- [1 3] + +;; like over a non-string column raises instead of matching nothing +(select {from: ts where: (like v "*1*")}) !- type + +;; ────────────── partitioned table: parted guid columns ────────────── +;; A parted column carries RAY_PARTED_BASE + base, which sailed past a +;; bail testing col->type == RAY_GUID — the fused program then zero- +;; filled every guid lane, so col-vs-col == matched ALL rows (zeros +;; compared equal to zeros). The bail now tests the element type. +(.sys.exec "rm -rf /tmp/rfl_guid_parted") +(set PG1 (guid 3)) +(set PG2 (guid 2)) +(set PT1 (table [g h v] (list PG1 (guid 3) [10 20 30]))) +(set PT2 (table [g h v] (list PG2 PG2 [40 50]))) +(.db.splayed.set "/tmp/rfl_guid_parted/1/t/" PT1) +(.db.splayed.set "/tmp/rfl_guid_parted/2/t/" PT2) +(set PT (.db.parted.get "/tmp/rfl_guid_parted/" 't)) +(set pg1 (at PG1 1)) + +;; col-vs-col matches exactly the partition where g and h coincide — +;; not all 5 rows (the parted zero-fill bug), not zero +(get (select {from: PT where: (== g h)}) 'v) -- [40 50] +;; col-vs-const finds its row across partitions +(get (select {from: PT where: (== g pg1)}) 'v) -- [20] +(count (get (select {from: PT where: (!= g pg1)}) 'v)) -- 4 +;; ordering stays loud on parted guids too +(select {from: PT where: (< g pg1)}) !- type + +;; partitioned guid columns take the same in/not-in fallback +(get (select {from: PT where: (in g (at PG1 [0 1]))}) 'v) -- [10 20] +(get (select {from: PT where: (not (in g (at PG1 [0 1])))}) 'v) -- [30 40 50] diff --git a/test/rfl/query/insert_inplace.rfl b/test/rfl/query/insert_inplace.rfl new file mode 100644 index 000000000..ecd8cb187 --- /dev/null +++ b/test/rfl/query/insert_inplace.rfl @@ -0,0 +1,99 @@ +;; #455: (insert 't batch) into a named global appends into the existing +;; columns in place when the binding is the sole owner — O(rows appended) +;; instead of a full O(rows present) rebuild per call. These tests pin +;; that the fast path and the rebuild produce identical tables, that the +;; rebuild still runs when the fast path's gates miss, and that a failed +;; insert leaves the binding untouched. + +;; ── fast path equals the rebuild, batch shapes ────────────────────────── +(set t1 (table [a b s] (list [1 2] (as 'F64 [1.5 2.5]) ['x 'y]))) +(insert 't1 (table [a b s] (list [3 4] (as 'F64 [3.5 4.5]) ['z 'w]))) -- 't1 +(count t1) -- 4 +(get t1 'a) -- [1 2 3 4] +(get t1 'b) -- [1.5 2.5 3.5 4.5] +(get t1 's) -- ['x 'y 'z 'w] + +;; list row of atoms +(insert 't1 (list 5 5.5 'v)) -- 't1 +(count t1) -- 5 +(get (select {from: t1 where: (== a 5)}) 's) -- ['v] + +;; dict row (column order independent) +(insert 't1 {s: 'q b: 6.5 a: 6}) -- 't1 +(get (select {from: t1 where: (== a 6)}) 'b) -- [6.5] + +;; repeated batch inserts stay identical to one big functional insert +(set t2 (table [a b s] (list [1 2] (as 'F64 [1.5 2.5]) ['x 'y]))) +(set t2b (insert t2 (table [a b s] (list [3 4 5 6] (as 'F64 [3.5 4.5 5.5 6.5]) ['z 'w 'v 'q])))) +(set t3 (table [a b s] (list [1 2] (as 'F64 [1.5 2.5]) ['x 'y]))) +(insert 't3 (table [a b s] (list [3 4] (as 'F64 [3.5 4.5]) ['z 'w]))) +(insert 't3 (table [a b s] (list [5 6] (as 'F64 [5.5 6.5]) ['v 'q]))) +(== (get t2b 'a) (get t3 'a)) -- [true true true true true true] +(== (get t2b 's) (get t3 's)) -- [true true true true true true] + +;; ── nulls survive the in-place append ─────────────────────────────────── +(set tn (table [a b] (list [1] (as 'F64 [1.0])))) +(insert 'tn (table [a b] (list [0N 3] [0Nf 3.0]))) +(count tn) -- 3 +(sum (map nil? (get tn 'a))) -- 1 +(sum (map nil? (get tn 'b))) -- 1 + +;; ── shared table falls back to the rebuild, alias keeps the old value ─── +(set ts (table [a] (list [1 2]))) +(set alias ts) +(insert 'ts (list 3)) -- 'ts +(count ts) -- 3 +(count alias) -- 2 + +;; a shared column also forces the rebuild; the held column is unchanged +(set tc (table [a] (list [1 2]))) +(set held (get tc 'a)) +(insert 'tc (list 3)) -- 'tc +(count tc) -- 3 +(count held) -- 2 + +;; ── a failed insert leaves the binding untouched ──────────────────────── +(set tf (table [a b] (list [1 2] [10 20]))) +(insert 'tf (list 3 'oops)) !- type +(count tf) -- 2 +(get tf 'b) -- [10 20] + +;; type error in the SECOND column after the first column already accepted +;; its cells: the in-place path must roll the first column back +(set tg (table [a b] (list [1 2] ['x 'y]))) +(insert 'tg (table [a b] (list [3 4] [7 8]))) !- type +(count tg) -- 2 +(get tg 'a) -- [1 2] + +;; ── boxed LIST columns append in place too: pointer cells, retained ───── +(set tb (table [a l] (list [1 2] (list [10 20] 'x)))) +(insert 'tb (list 3 [30 40])) -- 'tb +(count tb) -- 3 +(at (get tb 'l) 2) -- [30 40] +(insert 'tb (list 4 'y)) -- 'tb +(at (get tb 'l) 3) -- 'y + +;; a table batch must supply a LIST payload for a boxed column (its own +;; normalization turns uniform cells into a typed vector) — the error rolls +;; the whole insert back, boxed retains included +(insert 'tb (table [a l] (list [5] (list 'z)))) !- type +(count tb) -- 4 +(at (get tb 'l) 0) -- [10 20] + +;; typeless empty LIST column still adopts a concrete type via the rebuild +(set ta (table [a l] (list (til 0) (list)))) +(insert 'ta (list 1 2)) -- 'ta +(insert 'ta (list 3 4)) -- 'ta +(get ta 'l) -- [2 4] + +;; ── functional form is unchanged: value in, new value out ─────────────── +(set tv (table [a] (list [1]))) +(set tw (insert tv (list 2))) +(count tv) -- 1 +(count tw) -- 2 + +;; ── ingest loop: many small batches into one named table ──────────────── +(set big (table [a b] (list (til 0) (as 'F64 (til 0))))) +(map (fn [i] (insert 'big (table [a b] (list (til 100) (as 'F64 (til 100)))))) (til 50)) +(count big) -- 5000 +(sum (get big 'a)) -- 247500 diff --git a/test/rfl/query/legacy_strl_predicates.rfl b/test/rfl/query/legacy_strl_predicates.rfl new file mode 100644 index 000000000..f0cb2fbf2 --- /dev/null +++ b/test/rfl/query/legacy_strl_predicates.rfl @@ -0,0 +1,31 @@ +;; Legacy STRL string columns load as a list of string atoms +;; (col_load_str_list), a shape the current writer never produces — so +;; the RAY_LIST branches in like/ilike were unreachable from any test +;; that builds its table in-memory (table construction normalizes a +;; list of strings to a STR column). Build the on-disk file by hand, +;; the way col_format_generation.rfl stamps the generation byte. +;; Format: [4B magic "STRL"][8B count][per string: 4B len + bytes]. +(.sys.exec "rm -rf /tmp/rfl_strl_pred") +(set T-Strl (table [s v] (list (list "aaa" "bbb" "ccc") [1 2 3]))) +(.db.splayed.set "/tmp/rfl_strl_pred/" T-Strl) +(.sys.exec "printf 'STRL\\003\\000\\000\\000\\000\\000\\000\\000\\007\\000\\000\\000keep me\\004\\000\\000\\000drop\\011\\000\\000\\000also KEEP' > /tmp/rfl_strl_pred/s") -- 0 +(set TS (.db.splayed.get "/tmp/rfl_strl_pred/")) + +;; the legacy file loads as a LIST column +(type (get TS 's)) -- 'LIST + +;; like/ilike predicates reach the list branches in select-where +(get (select {from: TS where: (like s "*keep*")}) 'v) -- [1] +(get (select {from: TS where: (ilike s "*keep*")}) 'v) -- [1 3] + +;; direct builtin over the loaded list column +(like (get TS 's) "*keep*") -- [true false false] + +;; == over the list column raises instead of silently matching nothing +(select {from: TS where: (== s "keep me")}) !- type + +;; scalar subject in where: loud length error, not an aliased-length oom +(select {from: TS where: (like "keep me" "*keep*")}) !- length + +;; ilike over a numeric column raises instead of matching nothing +(select {from: TS where: (ilike v "*1*")}) !- type diff --git a/test/rfl/query/literal_col_ref.rfl b/test/rfl/query/literal_col_ref.rfl index 8ec8c755b..6b9f5c810 100644 --- a/test/rfl/query/literal_col_ref.rfl +++ b/test/rfl/query/literal_col_ref.rfl @@ -52,8 +52,8 @@ ;; --- regression: a literal `by:` symbol naming NO column must produce a ;; clean column-not-found error (domain) — the SAME as a bare `by: nonexistent` ;; — never a UBSan crash from ray_elem_size on a literal symbol. -(select {n: (count price) from: Tlit by: 'nope}) !- domain -(select {n: (count price) from: Tlit by: nope}) !- domain +(select {n: (count price) from: Tlit by: 'nope}) !- schema +(select {n: (count price) from: Tlit by: nope}) !- schema ;; --- AST-shape boundary: `(quote x)` is value-equivalent to the tick form ;; `'x` (both literal symbols), but the two are different AST SHAPES — `'x` is diff --git a/test/rfl/query/query_evalgroup_coverage.rfl b/test/rfl/query/query_evalgroup_coverage.rfl index abc979d2d..ed136ae6f 100644 --- a/test/rfl/query/query_evalgroup_coverage.rfl +++ b/test/rfl/query/query_evalgroup_coverage.rfl @@ -275,25 +275,25 @@ ;; ;; ' has sym id=0 → sym_w = RAY_SYM_W8 (id ≤ 0xFF) ;; → line 3081: memset(dst, 0, n) for W8 -;; RAY_ATOM_IS_NULL(') → case RAY_SYM → false (SYM has no null; ' is a value) -;; → no HAS_NULLS set; the broadcast cells are the empty symbol ', not null +;; RAY_ATOM_IS_NULL(') → case RAY_SYM → true (canonical null, id 0) +;; → HAS_NULLS is set on the broadcast vector ;; ──────────────────────────────────────────────────────────────────── (set Tbcast_null (table [k v] (list ['X 'Y 'Z] [10 20 30]))) -;; extra: ' (empty SYM ', id=0) → W8 memset, broadcast as a value (no null) +;; extra: ' (empty/null SYM, id=0) → W8 memset plus HAS_NULLS ;; can_atom_broadcast(')=1 → atom_broadcast_vec(', 3) -;; After broadcast: all 3 cells are the empty symbol ' (sym-id=0), not null +;; After broadcast: all 3 cells are canonical empty/null SYM values (count (select {s: (sum v) extra: ' by: k from: Tbcast_null})) -- 3 -(nil? (at (at (select {s: (sum v) extra: ' by: k from: Tbcast_null}) 'extra) 0)) -- false +(nil? (at (at (select {s: (sum v) extra: ' by: k from: Tbcast_null}) 'extra) 0)) -- true ;; Order-independent: mask to one SYM key. X→v=[10]→sum=10, extra is empty '. (set Gbn_X (select {s: (sum v) extra: ' by: k from: Tbcast_null where: (== k 'X)})) (count Gbn_X) -- 1 (at (at Gbn_X 'k) 0) -- 'X (at (at Gbn_X 's) 0) -- 10 -(nil? (at (at Gbn_X 'extra) 0)) -- false +(nil? (at (at Gbn_X 'extra) 0)) -- true (set Gbn_Z (select {s: (sum v) extra: ' by: k from: Tbcast_null where: (== k 'Z)})) (at (at Gbn_Z 'k) 0) -- 'Z (at (at Gbn_Z 's) 0) -- 30 -(nil? (at (at Gbn_Z 'extra) 0)) -- false +(nil? (at (at Gbn_Z 'extra) 0)) -- true ;; Order-independent multiset of all 3 group sums: {10,20,30} (asc (at (select {s: (sum v) extra: ' by: k from: Tbcast_null}) 's)) -- [10 20 30] @@ -397,7 +397,7 @@ (at (at (at Gsn_a 'n) 0) 0) -- "x" (set Gsn_b (select {n: name by: k from: Tstr_null_grp where: (== k "b")})) (at (at Gsn_b 'k) 0) -- "b" -(nil? (at (at (at Gsn_b 'n) 0) 0)) -- false +(nil? (at (at (at Gsn_b 'n) 0) 0)) -- true ;; NOTE: aggr_unary_per_group_buf (lines 2256-2337) is unreachable from RFL: ;; It requires n_aggs >= 16 for a streaming-aggr-unary to overflow into diff --git a/test/rfl/query/query_update_coverage.rfl b/test/rfl/query/query_update_coverage.rfl index cb3dc397f..4e6a3d0d1 100644 --- a/test/rfl/query/query_update_coverage.rfl +++ b/test/rfl/query/query_update_coverage.rfl @@ -508,7 +508,7 @@ ;; WHERE k>0: k=[1,2,3] all>0, so all rows are masked. ;; Row 0: src_vec=expr_vec, expr_vec[0]=null SYM → line 8707 fires! (count (update {sym: sym from: Tsymwhn where: (> k 0)})) -- 3 -(nil? (at (at (update {sym: sym from: Tsymwhn where: (> k 0)}) 'sym) 0)) -- false +(nil? (at (at (update {sym: sym from: Tsymwhn where: (> k 0)}) 'sym) 0)) -- true ;; ──────────────────────────────────────────────────────────────────── ;; WHERE-update STR column with null in expr_vec (line 8698) @@ -524,7 +524,7 @@ (set strnv (as 'STR (list "x" 0Ni "z"))) ;; WHERE k>0 masks rows 1,2; strnv[1]=null → line 8698 fires for row 1 (count (update {name: strnv from: Tupd_str3 where: (> k 0)})) -- 3 -(nil? (at (at (update {name: strnv from: Tupd_str3 where: (> k 0)}) 'name) 1)) -- false +(nil? (at (at (update {name: strnv from: Tupd_str3 where: (> k 0)}) 'name) 1)) -- true ;; ──────────────────────────────────────────────────────────────────── ;; insert into table with null STR column (lines 9333-9335) @@ -536,7 +536,7 @@ ;; Insert new row (k=4, name="d"): copies existing rows including null ;; → line 9333 fires for row 1 (null STR element) (count (insert Tstr_null_ins (list 4 "d"))) -- 4 -(nil? (at (at (insert Tstr_null_ins (list 4 "d")) 'name) 1)) -- false +(nil? (at (at (insert Tstr_null_ins (list 4 "d")) 'name) 1)) -- true ;; ──────────────────────────────────────────────────────────────────── ;; insert into table with null SYM column (line 9349) @@ -549,7 +549,7 @@ ;; Insert new row: copies existing rows; row 0 has null SYM ;; → line 9349 fires when copying row 0 (null SYM) (count (insert Tsym_n_ins (list 3 'c))) -- 3 -(nil? (at (at (insert Tsym_n_ins (list 3 'c)) 'sym) 0)) -- false +(nil? (at (at (insert Tsym_n_ins (list 3 'c)) 'sym) 0)) -- true ;; ──────────────────────────────────────────────────────────────────── ;; BUG: WHERE-branch update with a null I32 atom (`0Ni`) corrupts the diff --git a/test/rfl/regress/issue_411.rfl b/test/rfl/regress/issue_411.rfl new file mode 100644 index 000000000..9a4a73f00 --- /dev/null +++ b/test/rfl/regress/issue_411.rfl @@ -0,0 +1,11 @@ +;; Issue #411 — update-by sub-table gathers must retain null metadata. + +(set I411 (table [k v] (list [1 2 1 2] (as 'I64 [10 0N 30 40])))) +(set I411U (update {mn:(min v) sm:(sum v) by:k from:I411})) +(at I411U 'mn) -- [10 40 10 40] +(at I411U 'sm) -- [40 40 40 40] + +;; The broadcast update must agree with the corresponding grouped select. +(set I411S (select {mn:(min v) sm:(sum v) from:I411 by:k})) +(distinct (at I411U 'mn)) -- (at I411S 'mn) +(distinct (at I411U 'sm)) -- [40] diff --git a/test/rfl/regress/issue_414.rfl b/test/rfl/regress/issue_414.rfl new file mode 100644 index 000000000..d684d2014 --- /dev/null +++ b/test/rfl/regress/issue_414.rfl @@ -0,0 +1,17 @@ +;; Issue #414 — an unknown query column is always a schema error. `i` is +;; not a virtual row-index column; arbitrary missing names follow the same rule. + +(set I414 (table [g d v] (list ['a 'a 'b 'b] [2026.01.01 2026.01.02 2026.01.01 2026.01.02] [10 20 30 40]))) + +(select {x:i from:I414}) !- schema +(select {n:(count i) from:I414}) !- schema +(select {n:(count i) from:I414 by:d}) !- schema +(select {n:(max i) from:I414 by:d}) !- schema +(select {n:(count i) from:I414 where:(== g 'a) by:d}) !- schema +(select {from:I414 where:(< i 2)}) !- schema + +(select {n:(count missing) from:I414 by:d}) !- schema +(select {n:(max missing) from:I414 by:d}) !- schema + +;; Existing columns remain valid across the same planner paths. +(at (select {n:(count v) from:I414 where:(== g 'a) by:d}) 'n) -- [1 1] diff --git a/test/rfl/regress/issue_415.rfl b/test/rfl/regress/issue_415.rfl new file mode 100644 index 000000000..cc3f62dd3 --- /dev/null +++ b/test/rfl/regress/issue_415.rfl @@ -0,0 +1,22 @@ +;; Issue #415 — empty STR/SYM are their canonical in-band null values. + +(nil? "") -- true +(nil? ') -- true +(nil? "present") -- false +(nil? 'present) -- false + +(set I415S (as 'STR ["" "present"])) +(nil? (at I415S 0)) -- true +(nil? (at I415S 1)) -- false +(set I415Y (as 'SYM [' 'present])) +(nil? (at I415Y 0)) -- true +(nil? (at I415Y 1)) -- false + +;; A left-join miss uses the same canonical empty/null representation. A real +;; matched empty value is intentionally indistinguishable under this model. +(set I415R (table [k s] (list (list "a" "b") (list "" "present")))) +(set I415J (left-join [k] (table [k] (list (list "a" "b" "missing"))) I415R)) +(nil? (at (at I415J 's) 0)) -- true +(nil? (at (at I415J 's) 1)) -- false +(nil? (at (at I415J 's) 2)) -- true +(at (select {missing:(nil? s) from:I415J}) 'missing) -- [true false true] diff --git a/test/rfl/regress/issue_428.rfl b/test/rfl/regress/issue_428.rfl new file mode 100644 index 000000000..bb34c6469 --- /dev/null +++ b/test/rfl/regress/issue_428.rfl @@ -0,0 +1,43 @@ +;; A name a select cannot resolve must raise, and every clause keyword must +;; be skipped when the outputs are named. +;; +;; The general case was fixed with #414: an unknown column reference gets an +;; invalid-scan marker that ray_execute rejects. Two ways around it +;; survived, and both produced the #428 report — a projection under the +;; wrong label, and an aggregate answering its neutral element. +;; +;; 1. `_dist` was exempt from the marker unconditionally. The exemption is +;; needed, because a rerank produces that column during execution and it +;; is genuinely absent when the query compiles — but it applied just as +;; well to a query with no nearest: clause, where nothing will ever +;; produce it. +;; +;; 2. `nearest:` was missing from the skip list in the loop that names the +;; output columns. That walk is positional, so a keyword it fails to +;; skip eats an output slot and every name after it lands one column +;; early. It is counted out where the outputs are counted, which is why +;; only the naming disagreed. + +(set _T (table [a b] (list [1 2 3] [4 5 6]))) + +;; ── 1. `_dist` with no rerank to produce it: an ordinary unknown name ──── +(select {x: a d: _dist z: b from: _T}) !- schema +(select {d: _dist from: _T}) !- schema +(select {s: (sum _dist) from: _T}) !- schema +(select {c: (count _dist) from: _T}) !- schema +(select {m: (max _dist) from: _T}) !- schema +(select {f: (first _dist) from: _T}) !- schema +(select {s: (sum _dist) by: a from: _T}) !- schema +;; and the plain unknown name it used to be exempt from behaving like +(select {x: a y: nosuch z: b from: _T}) !- schema + +;; ── 2. `_dist` where a rerank does produce it — still resolves, still +;; correct. The nearest row is id 1 at distance 0. ─────────────────── +(set _TN (table [id Vec] (list [1 2 3 4] (list [1.0 0.0] [0.0 1.0] [1.0 1.0] [0.5 0.5])))) +(at (select {i: id d: _dist from: _TN nearest: (knn Vec [1.0 0.0]) take: 2}) 'i) -- [1 3] +(at (select {i: id d: _dist from: _TN nearest: (knn Vec [1.0 0.0]) take: 2}) 'd) -- [0.0 0.29] + +;; ── 3. the same query with nearest: written BEFORE the outputs. Same +;; columns, same names — the keyword must not take one of the slots. ── +(at (select {from: _TN nearest: (knn Vec [1.0 0.0]) i: id d: _dist take: 2}) 'i) -- [1 3] +(at (select {from: _TN nearest: (knn Vec [1.0 0.0]) i: id d: _dist take: 2}) 'd) -- [0.0 0.29] diff --git a/test/rfl/regress/load_select_isnull_mask.rfl b/test/rfl/regress/load_select_isnull_mask.rfl new file mode 100644 index 000000000..d0fffb148 --- /dev/null +++ b/test/rfl/regress/load_select_isnull_mask.rfl @@ -0,0 +1,51 @@ +;; Regression: load → select ISNULL WHERE-mask corruption. +;; +;; exec_elementwise_unary once had dedicated ISNULL kernels for only some +;; input types; every other type fell through the typed morsel dispatch +;; without writing a byte, so the BOOL result buffer came back as whatever +;; the allocator recycled. Trigger: a splayed table with a file .sym +;; domain, queried after a `load` interned new symbols — the FILE-domain +;; SYM column then bails from the fused expression path +;; (EXPR_BAIL_SYM_DOMAIN) into the typed fallback, and +;; `(select {where: (nil? sym)})` over 1000 rows returned 0, 539, 570 or +;; 1000 rows depending only on the size of the previously loaded file. +;; +;; OP_ISNULL is now answered for every input type before the typed +;; dispatch (expr.c exec_elementwise_unary); this file pins the original +;; end-to-end symptom. + +(.sys.exec "rm -rf /tmp/rfl_isnull_mask") -- 0 +(.sys.exec "mkdir -p /tmp/rfl_isnull_mask") -- 0 + +;; 1000-row table: SYM column cycling aa..dd (never null), I64 column with +;; nulls at rows 0 and 999, F64 column with a null at row 500. +(set SymM (at [aa bb cc dd] (% (til 1000) 4))) +(set QtyM (concat (concat [0N] (+ 1 (til 998))) [0N])) +(set PxM (as 'F64 (concat (concat (til 500) [0N]) (+ 501 (til 499))))) +(set T-Mask (table [sym qty px] (list SymM QtyM PxM))) +(.db.splayed.set "/tmp/rfl_isnull_mask/t" T-Mask "/tmp/rfl_isnull_mask/sym") + +;; Pad script: 60 `(set padN 1)` lines. Loading it interns 60 symbols the +;; file .sym domain doesn't have, reproducing the original trigger. +(.sys.exec "awk 'BEGIN{for(i=1;i<=60;i++) printf \"(set pad%d 1)\\n\", i}' > /tmp/rfl_isnull_mask/pad.rfl") -- 0 +(load "/tmp/rfl_isnull_mask/pad.rfl") +pad60 -- 1 + +(set S-Mask (.db.splayed.get "/tmp/rfl_isnull_mask/t" "/tmp/rfl_isnull_mask/sym")) +(count S-Mask) -- 1000 + +;; SYM: no null syms, so the mask must be all-false — every row survives +;; `not nil?` and none survives `nil?`. Pre-fix this pair was the garbage +;; readout (0 / 539 / 570 of 1000). +(count (select {from: S-Mask where: (not (nil? sym))})) -- 1000 +(count (select {from: S-Mask where: (nil? sym)})) -- 0 + +;; Sentinel nulls survive the round trip and drive the mask exactly. +(count (select {from: S-Mask where: (nil? qty)})) -- 2 +(count (select {from: S-Mask where: (not (nil? qty))})) -- 998 +(count (select {from: S-Mask where: (nil? px)})) -- 1 + +;; The WHERE mask agrees with per-element evaluation of the same predicate. +(sum (map nil? (at S-Mask 'sym))) -- 0 +(sum (map nil? (at S-Mask 'qty))) -- 2 +(sum (map nil? (at S-Mask 'px))) -- 1 diff --git a/test/rfl/sort/sort_coverage2.rfl b/test/rfl/sort/sort_coverage2.rfl index ffe0fb8b8..3d1dec16f 100644 --- a/test/rfl/sort/sort_coverage2.rfl +++ b/test/rfl/sort/sort_coverage2.rfl @@ -313,11 +313,11 @@ (set Tnull (table [k v] (list (as 'I64 [3 0Nl 1 0Nl 2]) (as 'F64 [30.0 0.0 10.0 0.0 20.0])))) (count (at (select {from: Tnull asc: k}) 'k)) -- 5 -;; Order: this exec_sort (select asc) path sorts NON-null ascending first -;; (1,2,3) with nulls at the TAIL. -(at (at (select {from: Tnull asc: k}) 'k) 0) -- 1 -(at (at (select {from: Tnull asc: k}) 'k) 2) -- 3 -(nil? (at (at (select {from: Tnull asc: k}) 'k) 4)) -- true +;; Order: a null is the smallest value, so the two nulls lead and the +;; non-nulls follow ascending. +(nil? (at (at (select {from: Tnull asc: k}) 'k) 0)) -- true +(at (at (select {from: Tnull asc: k}) 'k) 2) -- 1 +(at (at (select {from: Tnull asc: k}) 'k) 4) -- 3 ;; sort_table_by_keys (xasc) with a null column. (set Tnullxasc (table [k v] (list (as 'I64 [3 0Nl 1 0Nl 2]) (as 'F64 [30.0 0.0 10.0 0.0 20.0])))) @@ -415,7 +415,7 @@ (set Tstrwnull (table [s v] (list (as 'STR (take [1 0Nl 3 0Nl 5] 200)) (take [10 20 30 40 50] 200)))) (count (xasc Tstrwnull 's)) -- 200 ;; asc: 80 nulls sort FIRST, then "1","3","5"; last element is the max "5". -(nil? (at (at (xasc Tstrwnull 's) 's) 0)) -- false +(nil? (at (at (xasc Tstrwnull 's) 's) 0)) -- true (at (at (xasc Tstrwnull 's) 's) 80) -- "1" (at (at (xasc Tstrwnull 's) 's) 199) -- "5" ;; desc: hits lines 1809-1815 (reverse the null rotation for desc order). diff --git a/test/rfl/sort/sort_parted_topk.rfl b/test/rfl/sort/sort_parted_topk.rfl index ceb755864..856dffdb2 100644 --- a/test/rfl/sort/sort_parted_topk.rfl +++ b/test/rfl/sort/sort_parted_topk.rfl @@ -124,9 +124,10 @@ (at RSm 'Seq) -- [0 1 3] ;; ══════════════════════════════════════════════════════════════════════════ -;; POSITIVE 6 — NULL in the key. Nulls sort LAST for asc, so a small k never -;; selects a null unless there are < k non-null rows. Parity with flat proves -;; the streamed null handling matches. +;; POSITIVE 6 — NULL in the key. A null is the smallest value, so a small k +;; selects the nulls first and only then real values. Parity with flat proves +;; the streamed null handling matches — and it is what caught the streamed +;; path keeping its own null policy after the shared one changed (#417). ;; ══════════════════════════════════════════════════════════════════════════ (.sys.exec "rm -rf /tmp/rfl_tk6") (set N1 (table [v Seq] (list [7 0N 3] [0 1 2]))) @@ -142,8 +143,8 @@ (set RFn (select {v: v Seq: Seq from: NF asc: v take: 3})) (at RSn 'v) -- (at RFn 'v) (at RSn 'Seq) -- (at RFn 'Seq) -;; smallest three non-null: 1(Seq4),3(Seq2),7(Seq0) -(at RSn 'Seq) -- [4 2 0] +;; smallest three: null(Seq1), null(Seq3), then 1(Seq4) +(at RSn 'Seq) -- [1 3 4] ;; ══════════════════════════════════════════════════════════════════════════ ;; POSITIVE 7 — WHERE + asc + take streaming (filter THEN top-k), == flat oracle. diff --git a/test/rfl/store/indexed_col_aux_refs.rfl b/test/rfl/store/indexed_col_aux_refs.rfl new file mode 100644 index 000000000..962539ea1 --- /dev/null +++ b/test/rfl/store/indexed_col_aux_refs.rfl @@ -0,0 +1,49 @@ +;; An indexed column still owns what sits at aux bytes 8-15. +;; +;; A SYM column keeps its resolution domain there, a STR column its pool. +;; Attaching an index takes bytes 0-7 for the index pointer and LEAVES 8-15 +;; alone (ops/idxop.c attach_finalize, and the layout note in rayforce.h), +;; and ray_index_release_saved is a no-op — so the reference taken when that +;; domain or pool was attached is still the column's to hold and to drop. +;; +;; Both refcount hooks used to return early for an indexed column, before +;; reaching that field. A copy therefore took no reference, and the moment +;; that copy shed its index — which restores aux and makes it an ordinary +;; owner again — freeing it released a reference it never held. The +;; domain's count reached zero while the store's own column was still using +;; it, its symbol file was unmapped, and every symbol in that column read +;; back as nothing. No crash and no error: just a wrong answer. +;; +;; WHY A CHILD PROCESS. The imbalance is invisible unless the column +;; resolves through a FILE domain, and retain/release are no-ops on the +;; immortal runtime one. A process that has interned these symbols — which +;; writing the store does — reads its own store back on the runtime domain +;; and cannot see the bug. Only a process that has never seen them attaches +;; the file's domain, so the check runs in a freshly spawned rayforce and +;; this file asserts the answer it prints. + +(.sys.exec "rm -rf rf_idxaux rf_idxaux_child.rfl") -- 0 + +;; Four distinct symbols and their string twins over many rows, with a hash +;; index on the SYM column that survives the save. +(set _K (at ['aa 'bb 'cc 'dd] (% (til 4096) 4))) +(set _S (at ["aa" "bb" "cc" "dd"] (% (til 4096) 4))) +(.db.splayed.set "rf_idxaux/" (table [k s v] (list (.idx.hash _K) _S (til 4096)))) +(.idx.has? (at (.db.splayed.get "rf_idxaux/") 'k)) -- true + +;; The child: shed the index on a copy of the column, free the copy, then +;; read the symbols through the column that is still open. Prints the +;; number of distinct symbols, which must still be 4. +(.sys.exec "printf '%s\n' '(set T (.db.splayed.get \"rf_idxaux/\"))' '(set c (at T (quote k)))' '(set d (.idx.drop c))' '(set c 0)' '(set d 0)' '(count (distinct (at T (quote k))))' > rf_idxaux_child.rfl") -- 0 +(.sys.exec "./rayforce -f rf_idxaux_child.rfl 2>/dev/null | tail -1 | grep -qx 4") -- 0 + +;; Twice over: the second shed is what turns an unbalanced pair into a +;; second release of the same reference. +(.sys.exec "printf '%s\n' '(set T (.db.splayed.get \"rf_idxaux/\"))' '(set c1 (at T (quote k)))' '(set c2 (at T (quote k)))' '(set d1 (.idx.drop c1))' '(set d2 (.idx.drop c2))' '(set c1 0)' '(set c2 0)' '(set d1 0)' '(set d2 0)' '(count (distinct (at T (quote k))))' > rf_idxaux_child.rfl") -- 0 +(.sys.exec "./rayforce -f rf_idxaux_child.rfl 2>/dev/null | tail -1 | grep -qx 4") -- 0 + +;; And the group-by whose key column adopts that same domain. +(.sys.exec "printf '%s\n' '(set T (.db.splayed.get \"rf_idxaux/\"))' '(set c (at T (quote k)))' '(set d (.idx.drop c))' '(set c 0)' '(set d 0)' '(count (select {n: (count v) by: {kk: k} from: T}))' > rf_idxaux_child.rfl") -- 0 +(.sys.exec "./rayforce -f rf_idxaux_child.rfl 2>/dev/null | tail -1 | grep -qx 4") -- 0 + +(.sys.exec "rm -rf rf_idxaux rf_idxaux_child.rfl") -- 0 diff --git a/test/rfl/store/splayed_str_pool_lifetime.rfl b/test/rfl/store/splayed_str_pool_lifetime.rfl new file mode 100644 index 000000000..223b30c7e --- /dev/null +++ b/test/rfl/store/splayed_str_pool_lifetime.rfl @@ -0,0 +1,109 @@ +;; A result gathered from a mapped string column outlives that column. +;; +;; A splayed string column and its pool are written contiguously and mapped +;; together. Any result gathered from such a column shares the pool by +;; reference — filter, take, join and the head/tail slices all go through +;; col_propagate_str_pool, which retains it. That retain used to be a +;; promise the memory could not keep: the region belonged to the COLUMN, so +;; freeing the column unmapped the pool out from under every result still +;; holding it. The pool now owns the region and the column references it. +;; +;; Each shape runs in its own process because the second symptom only +;; appears at teardown: with both the loaded table and the result still +;; bound, every read is correct and the fault lands in the environment's +;; final release. A test that only read the values would pass on the +;; broken build — the reporter's own case 2 printed the right answer first. +;; +;; The exit status is the assertion. A crash cannot be observed from +;; inside the process that has it. +;; +;; Each child command is guarded on ./rayforce existing. The sanitiser +;; flavours build only their own test runner, so the plain interpreter this +;; needs is absent there and these shapes stand down rather than fail on a +;; missing binary — the debug and release runs, which do build it, are where +;; they carry their weight. + +(.sys.exec "rm -rf rf_strpool rf_strpool_child.rfl") -- 0 + +(set _T (table [id note] (list [1 2 3] ["one" "two" "three"]))) +(.db.splayed.set "rf_strpool/" _T) + +;; ── 1. where over a proper subset, the loaded table then dropped: the +;; original reproducer, which faulted before printing anything. ──────── +(.sys.exec "printf '%s\n' '(set u (.db.splayed.get \"rf_strpool/\"))' '(set u (select {from: u where: (not (== id 1))}))' '(insert (quote u) (table [id note] (list [9] [\"nine\"])))' '(print (at u (quote note)))' > rf_strpool_child.rfl") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; ./rayforce -f rf_strpool_child.rfl > rf_strpool_out 2>&1") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; grep -qxF '[\"two\" \"three\" \"nine\"]' rf_strpool_out") -- 0 + +;; ── 2. selection kept beside the loaded table: reads fine either way, so +;; only the exit status tells the two builds apart. ────────────────────── +(.sys.exec "printf '%s\n' '(set u (.db.splayed.get \"rf_strpool/\"))' '(set v (select {from: u where: (not (== id 1))}))' '(print (at v (quote note)))' > rf_strpool_child.rfl") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; ./rayforce -f rf_strpool_child.rfl > rf_strpool_out 2>&1") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; grep -q 'SIGSEGV' rf_strpool_out; test $? -ne 0") -- 0 + +;; ── The rest of the family. Everything that SHARES the pool belongs here; +;; operations that build their strings afresh (asc, distinct, group-by) +;; were checked and are unaffected, so they are not repeated. The result +;; is bound to a name in every case: a temporary dies before the column +;; it came from and never sees the dangling pool, which is why an +;; inline (print (take …)) passes on the broken build too. ───────────── +(.sys.exec "printf '%s\n' '(set u (.db.splayed.get \"rf_strpool/\"))' '(set v (take (at u (quote note)) 2))' '(print v)' > rf_strpool_child.rfl") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; ./rayforce -f rf_strpool_child.rfl > rf_strpool_out 2>&1") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; grep -qxF '[\"one\" \"two\"]' rf_strpool_out") -- 0 + +(.sys.exec "printf '%s\n' '(set u (.db.splayed.get \"rf_strpool/\"))' '(set v (drop (at u (quote note)) 1))' '(print v)' > rf_strpool_child.rfl") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; ./rayforce -f rf_strpool_child.rfl > rf_strpool_out 2>&1") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; grep -qxF '[\"two\" \"three\"]' rf_strpool_out") -- 0 + +(.sys.exec "printf '%s\n' '(set u (.db.splayed.get \"rf_strpool/\"))' '(set v (select {note: note from: u take: 2}))' '(print (at v (quote note)))' > rf_strpool_child.rfl") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; ./rayforce -f rf_strpool_child.rfl > rf_strpool_out 2>&1") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; grep -qxF '[\"one\" \"two\"]' rf_strpool_out") -- 0 + +;; All four join flavours share the pool through the same helper. +(.sys.exec "printf '%s\n' '(set u (.db.splayed.get \"rf_strpool/\"))' '(set r (table [id tag] (list [1 2] (list \"x\" \"y\"))))' '(set j (inner-join [id] r u))' '(print (at j (quote note)))' > rf_strpool_child.rfl") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; ./rayforce -f rf_strpool_child.rfl > rf_strpool_out 2>&1") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; grep -qxF '[\"one\" \"two\"]' rf_strpool_out") -- 0 + +(.sys.exec "printf '%s\n' '(set u (.db.splayed.get \"rf_strpool/\"))' '(set r (table [id tag] (list [1 2] (list \"x\" \"y\"))))' '(set j (left-join [id] r u))' '(print (at j (quote note)))' > rf_strpool_child.rfl") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; ./rayforce -f rf_strpool_child.rfl > rf_strpool_out 2>&1") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; grep -qxF '[\"one\" \"two\"]' rf_strpool_out") -- 0 + +(.sys.exec "printf '%s\n' '(set u (.db.splayed.get \"rf_strpool/\"))' '(set r (table [id tag] (list [1 2] (list \"x\" \"y\"))))' '(set j (full-join [id] r u))' '(print (at j (quote note)))' > rf_strpool_child.rfl") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; ./rayforce -f rf_strpool_child.rfl > rf_strpool_out 2>&1") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; grep -qxF '[\"one\" \"two\" \"three\"]' rf_strpool_out") -- 0 + +(.sys.exec "printf '%s\n' '(set u (.db.splayed.get \"rf_strpool/\"))' '(set r (table [id tag] (list [1 2] (list \"x\" \"y\"))))' '(set j (asof-join [id] r u))' '(print (at j (quote note)))' > rf_strpool_child.rfl") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; ./rayforce -f rf_strpool_child.rfl > rf_strpool_out 2>&1") -- 0 +(.sys.exec "test -x ./rayforce || exit 0; grep -qxF '[\"one\" \"two\"]' rf_strpool_out") -- 0 + +(.sys.exec "rm -rf rf_strpool rf_strpool_child.rfl rf_strpool_out") -- 0 + +;; ── A large string column carries an index, and that changes the release +;; path. .db.splayed.set attaches a dict index to any string column of +;; 65536 rows or more, so the mapped column comes back with a passenger +;; index — and the arm that handles an indexed column used to return +;; before it reached the pool. While the column still unmapped the +;; region itself that cost one reference; once the pool owns the region +;; it costs the whole mapping, every load. +;; +;; Measured rather than asserted structurally: five load-and-drop cycles +;; must leave the mapped-byte count where they found it. Before the fix +;; this grew by the size of the file each time round. ───────────────── +(.sys.exec "rm -rf rf_bigstr") -- 0 +(set _N 70000) +(set _BT (table [id note] (list (til _N) (at (list "alpha" "beta" "gamma" "delta") (% (til _N) 4))))) +(.db.splayed.set "rf_bigstr/" _BT) +(set _BT 0) +(.idx.has? (at (.db.splayed.get "rf_bigstr/") 'note)) -- true + +(set _m0 (at (.sys.mem) 'sys-mapped)) +(set u (.db.splayed.get "rf_bigstr/")) (set v (take (at u 'note) 3)) (set u 0) (set v 0) +(set u (.db.splayed.get "rf_bigstr/")) (set v (take (at u 'note) 3)) (set u 0) (set v 0) +(set u (.db.splayed.get "rf_bigstr/")) (set v (take (at u 'note) 3)) (set u 0) (set v 0) +(set u (.db.splayed.get "rf_bigstr/")) (set v (take (at u 'note) 3)) (set u 0) (set v 0) +(set u (.db.splayed.get "rf_bigstr/")) (set v (take (at u 'note) 3)) (set u 0) (set v 0) +;; One file's worth of growth would be over a million bytes; the small +;; negative drift is the release path rounding to whole pages while the +;; map counted the file, and predates this change. +(< (- (at (.sys.mem) 'sys-mapped) _m0) 4096) -- true + +(.sys.exec "rm -rf rf_bigstr") -- 0 diff --git a/test/rfl/strop/like.rfl b/test/rfl/strop/like.rfl index 6b57a98dd..1232612f9 100644 --- a/test/rfl/strop/like.rfl +++ b/test/rfl/strop/like.rfl @@ -180,3 +180,11 @@ ;; SHAPE_PREFIX with empty lit ("`*`" alone is SHAPE_ANY, not PREFIX, so use trailing only) ;; — covered by `(like "" "*")` above (SHAPE_ANY). + +;; ────────────── list of string/symbol atoms ────────────── +;; The shape splayed string columns load as (col_load_str_list) — like +;; used to reject it with a type error while str-find accepted it. +(like (list "abc" "has Pending mark" "xyz") "*Pending*") -- [false true false] +(like (list "alpha" "beta") "a*") -- [true false] +(like (list 'alpha 'beta) "a*") -- [true false] +(like (list "a" 1 "b") "a*") !- type diff --git a/test/rfl/strop/null_propagation.rfl b/test/rfl/strop/null_propagation.rfl index acfe97412..53b7e117f 100644 --- a/test/rfl/strop/null_propagation.rfl +++ b/test/rfl/strop/null_propagation.rfl @@ -28,43 +28,43 @@ ;; Helper: build 3-row STR col with null at index 1. (set sv3 (as 'STR [1 0Nl 2])) -(nil? (at sv3 1)) -- false +(nil? (at sv3 1)) -- true ;; ─── exec_string_unary: upper — STR null at index 1 ────────────────── (set Tn (table [s] (list sv3))) (set Ru (at (select {r: (upper s) from: Tn}) 'r)) (at Ru 0) -- "1" -(nil? (at Ru 1)) -- false +(nil? (at Ru 1)) -- true (at Ru 2) -- "2" ;; ─── exec_string_unary: lower — STR null at index 1 ────────────────── (set Rl (at (select {r: (lower s) from: Tn}) 'r)) (at Rl 0) -- "1" -(nil? (at Rl 1)) -- false +(nil? (at Rl 1)) -- true (at Rl 2) -- "2" ;; ─── exec_string_unary: trim — STR null at index 1 ─────────────────── (set Rt (at (select {r: (trim s) from: Tn}) 'r)) (at Rt 0) -- "1" -(nil? (at Rt 1)) -- false +(nil? (at Rt 1)) -- true (at Rt 2) -- "2" ;; ─── exec_strlen: STR null produces NULL_I64 (lines 891-894) ───────── (set Rslen (at (select {r: (strlen s) from: Tn}) 'r)) (at Rslen 0) -- 1 -(nil? (at Rslen 1)) -- false +(nil? (at Rslen 1)) -- true (at Rslen 2) -- 1 ;; ─── exec_substr: STR null at input (lines 978-984) ────────────────── (set Rss (at (select {r: (substr s 1 1) from: Tn}) 'r)) (at Rss 0) -- "1" -(nil? (at Rss 1)) -- false +(nil? (at Rss 1)) -- true (at Rss 2) -- "2" ;; ─── exec_replace: STR null (lines 1058-1062) ───────────────────────── (set Rr (at (select {r: (replace s "1" "X") from: Tn}) 'r)) (at Rr 0) -- "X" -(nil? (at Rr 1)) -- false +(nil? (at Rr 1)) -- true (at Rr 2) -- "2" ;; ─── exec_concat: STR null (line 1185) ─────────────────────────────── @@ -73,21 +73,21 @@ (set Tc (table [a b] (list sv3 sv3b))) (set Rcat (at (select {r: (concat a b) from: Tc}) 'r)) (at Rcat 0) -- "110" -(nil? (at Rcat 1)) -- false +(nil? (at Rcat 1)) -- true ;; ─── verify HAS_NULLS on result from exec_string_unary ─────────────── ;; Applying upper to a null-bearing STR vec should preserve the null bit. -(nil? (at (as 'STR [0Nl]) 0)) -- false +(nil? (at (as 'STR [0Nl]) 0)) -- true ;; ─── null at first and last positions ──────────────────────────────── (set sv5 (as 'STR [0Nl 2 0Nl])) (set Tn2 (table [s] (list sv5))) (set Ru2 (at (select {r: (upper s) from: Tn2}) 'r)) -(nil? (at Ru2 0)) -- false +(nil? (at Ru2 0)) -- true (at Ru2 1) -- "2" -(nil? (at Ru2 2)) -- false +(nil? (at Ru2 2)) -- true (set Rslen2 (at (select {r: (strlen s) from: Tn2}) 'r)) -(nil? (at Rslen2 0)) -- false +(nil? (at Rslen2 0)) -- true (at Rslen2 1) -- 1 -(nil? (at Rslen2 2)) -- false +(nil? (at Rslen2 2)) -- true diff --git a/test/rfl/strop/split.rfl b/test/rfl/strop/split.rfl index 29797c683..06d41baa8 100644 --- a/test/rfl/strop/split.rfl +++ b/test/rfl/strop/split.rfl @@ -4,7 +4,7 @@ ;; Empty string is an ordinary STR value, so split-of-"" yields a ;; one-element vector whose only element is not null. (count (split "" ",")) -- 1 -(nil? (at (split "" ",") 0)) -- false +(nil? (at (split "" ",") 0)) -- true (split "abc" ",") -- ["abc"] ;; joining splits back equals input (when separator present) diff --git a/test/rfl/strop/string_branch_cov.rfl b/test/rfl/strop/string_branch_cov.rfl index 6dd08dfb9..24838bfb4 100644 --- a/test/rfl/strop/string_branch_cov.rfl +++ b/test/rfl/strop/string_branch_cov.rfl @@ -465,13 +465,13 @@ ;; null in START vector → row 1 is null (set RSubNs (at (select {r: (substr s st 3) from: TSubNull}) 'r)) (at RSubNs 0) -- "alp" -(nil? (at RSubNs 1)) -- false +(nil? (at RSubNs 1)) -- true (at RSubNs 2) -- "har" ;; null in LENGTH vector → row 2 is null (set RSubNl (at (select {r: (substr s 1 ln) from: TSubNull}) 'r)) (at RSubNl 0) -- "alp" (at RSubNl 1) -- "br" -(nil? (at RSubNl 2)) -- false +(nil? (at RSubNl 2)) -- true ;; The no-null per-row start/len vector path (covers s_data line 962, ;; l_data line 974, and the s_data/l_data ternaries at 998-999): diff --git a/test/rfl/strop/string_manipulation.rfl b/test/rfl/strop/string_manipulation.rfl index 6444e7304..f9dcf5e66 100644 --- a/test/rfl/strop/string_manipulation.rfl +++ b/test/rfl/strop/string_manipulation.rfl @@ -212,7 +212,7 @@ (set TLen (table [s] (list ["" "a" "abcdefg" "abcdefghijkl" "abcdefghijklm" "abcdefghijklmnopqrst" "aaaaabbbbbcccccdddddeeeeefffffggggghhhhh" "aaaaabbbbbcccccdddddeeeeefffffggggghhhhhiiii" "xy" "wxyz"]))) (set RLen (at (select {r: (strlen s) from: TLen}) 'r)) (count RLen) -- 10 -(at RLen 0) -- 0 +(at RLen 0) -- 0Nl (at RLen 1) -- 1 (at RLen 2) -- 7 (at RLen 3) -- 12 @@ -222,7 +222,7 @@ (at RLen 7) -- 44 (at RLen 8) -- 2 (at RLen 9) -- 4 -(sum (== RLen [0 1 7 12 13 20 40 44 2 4])) -- 10 +(sum (== RLen [0 1 7 12 13 20 40 44 2 4])) -- 9 (sum RLen) -- 143 ;; ════════════════════════════════════════════════════════════════════ @@ -476,6 +476,6 @@ (concat (concat "hello" " ") "world") -- "hello world" (strlen "abcdefghijkl") -- 12 (strlen "abcdefghijklm") -- 13 -(strlen "") -- 0 +(strlen "") -- 0Nl (strlen 'abcdefghijkl) -- 12 (strlen 'abcdefghijklm) -- 13 diff --git a/test/rfl/strop/strlen.rfl b/test/rfl/strop/strlen.rfl index 815b42b20..22d422525 100644 --- a/test/rfl/strop/strlen.rfl +++ b/test/rfl/strop/strlen.rfl @@ -1,5 +1,5 @@ (strlen "abc") -- 3 -(strlen "") -- 0 +(strlen "") -- 0Nl (strlen 'alpha) -- 5 (sum (strlen ["aa" "bbb" ""])) -- 5 diff --git a/test/rfl/strop/strop_branch_cov.rfl b/test/rfl/strop/strop_branch_cov.rfl index 53be45b80..3720a2c92 100644 --- a/test/rfl/strop/strop_branch_cov.rfl +++ b/test/rfl/strop/strop_branch_cov.rfl @@ -207,7 +207,7 @@ ;; Build a STR vec with null via cast: (as 'STR [1 0Nl 3]). ;; ════════════════════════════════════════════════════════════════════ (at (strlen (as 'STR [1 0Nl 3])) 0) -- 1 -(nil? (at (strlen (as 'STR [1 0Nl 3])) 1)) -- false +(nil? (at (strlen (as 'STR [1 0Nl 3])) 1)) -- true (at (strlen (as 'STR [1 0Nl 3])) 2) -- 1 ;; ════════════════════════════════════════════════════════════════════ diff --git a/test/rfl/system/read_csv.rfl b/test/rfl/system/read_csv.rfl index c8d632296..5ecd1080e 100644 --- a/test/rfl/system/read_csv.rfl +++ b/test/rfl/system/read_csv.rfl @@ -71,7 +71,7 @@ (.sys.exec "test $(find rf_test_csv_parted_rows -mindepth 1 -maxdepth 1 -type d | wc -l) -eq 3") -- 0 (.sys.exec "rm -rf rf_test_csv_parted_rows rf_test_csv_rows.csv") -- 0 -;; ── R6 regression: empty TSV/CSV fields → empty SYM (not null sentinel) ── +;; ── R6 regression: empty TSV/CSV fields → canonical empty/null SYM ── ;; CSV format conflates "missing" and "empty"; the loader treats empty ;; SYM cells as the interned empty string so SQL-style `(!= col "")` ;; filters work consistently with the row-level semantics most CSV @@ -80,10 +80,9 @@ (.sys.exec "printf 'name\\nalice\\n\\nbob\\n\\ncarol\\n' > rf_test_empty.csv") -- 0 (set _t (.csv.read [SYMBOL] "rf_test_empty.csv")) (count _t) -- 5 -;; The empty SYM cell is the interned empty string (sym id 0), a real -;; comparable value — SQL-style filtering on SYM columns compares by -;; value, not by null. `(!= name "")` therefore excludes the two empty -;; rows (alice, bob, carol survive) and `(== name "")` selects them. +;; The empty SYM cell is canonical null (sym id 0). Equality remains an +;; in-band id comparison, so `(!= name "")` excludes the two empty rows +;; (alice, bob, carol survive) and `(== name "")` selects them. ;; (See the str-resolved comparison path in src/ops/expr.c, which skips ;; the null-comparison fixup once a string constant resolves to a sym id.) (count (select {x: name from: _t where: (!= name "")})) -- 3 diff --git a/test/rfl/system/repl_complete.rfl b/test/rfl/system/repl_complete.rfl new file mode 100644 index 000000000..48cd154c5 --- /dev/null +++ b/test/rfl/system/repl_complete.rfl @@ -0,0 +1,32 @@ +;; .repl.complete — prefix completion over the live namespace (issue #441). +;; +;; Wraps ray_env_lookup_prefix (builtins + keywords + user bindings), +;; sorts, and returns a sym vector. This is the engine side of "what the +;; REPL does", now reachable over IPC so editor tooling (tree-sitter / +;; LSP-style clients) can offer semantic completion of names the engine +;; knows at runtime — not just static keywords. + +;; ── user bindings are completed, and the result is sorted ── +(set zzq_alpha 1) +(set zzq_gamma 3) +(set zzq_beta 2) +(.repl.complete "zzq_") -- ['zzq_alpha 'zzq_beta 'zzq_gamma] + +;; ── a narrower prefix narrows the candidate set ── +(.repl.complete "zzq_a") -- ['zzq_alpha] + +;; ── no match → empty vector ── +(count (.repl.complete "zzq_no_such_prefix_xyzzy")) -- 0 + +;; ── the set includes builtins/keywords, not just user names +;; (membership so the assertion survives future additions) ── +(in 'take (.repl.complete "take")) -- true +(in 'select (.repl.complete "sel")) -- true + +;; ── the verb is self-discoverable, and dotted names round-trip ── +(in '.repl.complete (.repl.complete ".repl.")) -- true + +;; ── type errors: the argument must be a string atom ── +(.repl.complete 42) !- type +(.repl.complete 'zzq_) !- type +(.repl.complete [1 2]) !- type diff --git a/test/rfl/system/serde.rfl b/test/rfl/system/serde.rfl index 227b4ca2e..ba45f7d27 100644 --- a/test/rfl/system/serde.rfl +++ b/test/rfl/system/serde.rfl @@ -28,3 +28,8 @@ ;; Both the value bits AND the null mask must survive serialize/deser. (count (de (ser [1 0N 3]))) -- 3 (sum (de (ser [1 0N 3]))) -- 4 + +;; Container-frame count/length validation (table schema-vs-columns, ragged +;; columns, dict keys-vs-values) is covered in test/test_store.c +;; (store/serde_container_count_mismatch), which builds frames via +;; sizeof(ray_ipc_header_t) rather than hard-coding the wire layout. diff --git a/test/rfl/system/syscmd_coverage.rfl b/test/rfl/system/syscmd_coverage.rfl index 025dc37cb..8a0a18fe8 100644 --- a/test/rfl/system/syscmd_coverage.rfl +++ b/test/rfl/system/syscmd_coverage.rfl @@ -78,6 +78,14 @@ (.sys.timeit 3.14) !- type (.sys.listen 1.5) !- type (.sys.listen 3.14) !- type + +;; ────────────── listen "HOST:PORT" form (#427): argument guards ───── +;; All of these fail before any socket is touched. +(.sys.listen ":123") !- type +(.sys.listen "127.0.0.1:") !- domain +(.sys.listen "127.0.0.1:1abc") !- domain +(.sys.listen "127.0.0.1:70000") !- domain +(.sys.listen "127.0.0.1:0") !- domain ;; State should be untouched by the failed timeit calls above (the ;; type guard runs before the profiler flag is poked). Confirm by ;; toggling and reading back. diff --git a/test/rfl/system/system_branch_cov2.rfl b/test/rfl/system/system_branch_cov2.rfl index 3fad0955b..d1a1c3eec 100644 --- a/test/rfl/system/system_branch_cov2.rfl +++ b/test/rfl/system/system_branch_cov2.rfl @@ -130,6 +130,11 @@ (.ipc.open "localhost:-1") !- domain (.ipc.open "localhost:65536") !- domain (.ipc.open "localhost:abc") !- domain +;; Partial-numeric ports must be rejected, not truncated by atoi to their +;; numeric prefix ("1abc" -> 1). strtol requires the whole field to be digits, +;; so these are a domain error at parse time — never a connection attempt. +(.ipc.open "localhost:1abc") !- domain +(.ipc.open "localhost:19876x") !- domain (.ipc.open "127.0.0.1:19876") !- io (.ipc.open "127.0.0.1:19876:user:pass") !- io (.ipc.open "127.0.0.1:19876:extra") !- io diff --git a/test/rfl/table/select.rfl b/test/rfl/table/select.rfl index 2b57cc332..a335255d7 100644 --- a/test/rfl/table/select.rfl +++ b/test/rfl/table/select.rfl @@ -121,6 +121,16 @@ (count (select {from: trades-15 take: 0})) -- 0 (count (select {from: trades-15 take: 15})) -- 15 (sum (at (select {from: trades-15 take: 15}) 'size)) -- 1765 +;; negative take: (from the end), clamped to the row count +(count (select {from: trades-15 take: -5})) -- 5 +(count (select {from: trades-15 take: -20})) -- 15 +(sum (at (select {from: trades-15 take: -15}) 'size)) -- 1765 +;; INT64_MIN take count is the i64 null sentinel (0N); negating it is signed- +;; overflow UB. Every select take: path — DAG tail-pushdown, sorted +;; apply_sort_take, grouped — must reject it as a type error rather than trap. +(select {from: trades-15 take: -9223372036854775808}) !- type +(select {from: trades-15 asc: size take: -9223372036854775808}) !- type +(select {c: (count size) from: trades-15 by: sym take: -9223372036854775808}) !- type ;; ── edge cases: all-pass / none-pass / single-row / by-distinct-time (count (select {from: trades-15 where: (> size -1)})) -- 15 diff --git a/test/rfl/type/as.rfl b/test/rfl/type/as.rfl index 15c98ad15..dd6d5e8d4 100644 --- a/test/rfl/type/as.rfl +++ b/test/rfl/type/as.rfl @@ -517,24 +517,36 @@ (as 'f64 "0.0") -- 0.0 (as 'f64 "100") -- 100.0 -;; INT16/INT32 boundary parses — negative-extreme literals can't be written -;; (parser tokenises positive then negates), so verify via i64 round-trip. -;; INT16_MIN / INT32_MIN / INT64_MIN are the respective NULL_* -;; sentinels. Casting these boundary literals round-trips as the -;; typed null of the wider type. -(as 'i64 (as 'i16 "-32768")) -- 0Nl -(as 'i64 (as 'i16 "32767")) -- 32767 -(as 'i64 (as 'i32 "-2147483648")) -- 0Nl -(as 'i64 (as 'i32 "2147483647")) -- 2147483647 +;; INT16/INT32/INT64 boundary string casts. INT16_MIN / INT32_MIN / INT64_MIN +;; are the respective NULL_* sentinels, so a non-null ATOM cannot represent the +;; exact minimum: the scalar string cast rejects it with a domain error rather +;; than silently yielding the typed null (0Nh / 0Ni / 0Nl). MIN+1 and MAX parse. +(as 'i16 "-32768") !- domain +(as 'i16 "-32767") -- -32767h +(as 'i16 "32767") -- 32767h +(as 'i32 "-2147483648") !- domain +(as 'i32 "-2147483647") -- -2147483647i +(as 'i32 "2147483647") -- 2147483647i +(as 'i64 "-9223372036854775808") !- domain +(as 'i64 "-9223372036854775807") -- -9223372036854775807 +(as 'i64 "9223372036854775807") -- 9223372036854775807 +;; The string->vector cast routes each element through the same scalar cast, +;; so it rejects the sentinel consistently — no atom/vector divergence. (A +;; numeric-narrowing cast still nulls a produced sentinel; that's the +;; documented narrow-int rule. String ingest is loud.) +(as 'I16 (list "-32768" "1")) !- domain +(as 'I16 (list "-32767" "1")) -- [-32767h 1h] +(as 'I32 (list "-2147483648" "1")) !- domain +(as 'I32 (list "-2147483647" "1")) -- [-2147483647i 1i] ;; ========== STRING → NUMERIC: FULL CONSUMPTION + OVERFLOW ========== ;; The old strtoll/strtol/strtod path stopped at the first non-digit and ;; never checked the end pointer or ERANGE, so trailing garbage and true ;; overflow were silently accepted ("1e19" → 1, "9999...9" → INT64_MAX). ;; All of these must now REJECT with a domain error, matching the strict -;; DATE/TIME/TIMESTAMP string casts. Narrow-int truncation itself still -;; wraps (documented narrow-int rule); only unparseable/overflowing input -;; errors. +;; DATE/TIME/TIMESTAMP string casts. Non-string narrow-int truncation itself +;; still wraps (documented narrow-int rule); string ingest rejects clean +;; values outside the target type range rather than silently wrapping them. (as 'i64 "123abc") !- domain (as 'i64 "1e19") !- domain (as 'i64 "12.5") !- domain @@ -542,19 +554,28 @@ (as 'i64 "-999999999999999999999999") !- domain (as 'i32 "123x") !- domain (as 'i32 "1e9") !- domain +(as 'i32 "3000000000") !- domain +(as 'i32 "-3000000000") !- domain (as 'i16 "40000junk") !- domain +(as 'i16 "40000") !- domain +(as 'i16 "-40000") !- domain (as 'u8 "12zz") !- domain (as 'u8 "300abc") !- domain +(as 'u8 "256") !- domain +(as 'u8 "-1") !- domain (as 'f64 "1.5x") !- domain (as 'f64 "1.5e3junk") !- domain ;; Clean values still parse. (as 'i64 " 123") -- 123 (as 'i64 "-5") -- -5 +(as 'u8 "255") -- 0xFF (as 'f64 "0x10") -- 16.0 ;; The string-VECTOR cast routes through the same per-element parser: a ;; malformed element rejects the whole cast, clean elements parse. (as 'I64 (list "42" "-7" "100")) -- [42 -7 100] (as 'I64 (list "42" "123abc")) !- domain +(as 'I32 (list "42" "3000000000")) !- domain +(as 'U8 (list "42" "256")) !- domain (as 'F64 (list "3.14" "1.5x")) !- domain ;; ========== NULL PRESERVATION ACROSS CASTS ========== diff --git a/test/test_aof.c b/test/test_aof.c index 06df6b12f..4705436fc 100644 --- a/test/test_aof.c +++ b/test/test_aof.c @@ -82,7 +82,7 @@ static bool collect_cb(int64_t lsn, const void* payload, int64_t len, void* ctx) c->lsns[c->n] = lsn; c->lens[c->n] = len; size_t cp = len < 31 ? (size_t)len : 31; - memcpy(c->payloads[c->n], payload, cp); + if (cp) memcpy(c->payloads[c->n], payload, cp); c->payloads[c->n][cp] = '\0'; } c->n++; diff --git a/test/test_buddy.c b/test/test_buddy.c index f7a87d521..9a23cc643 100644 --- a/test/test_buddy.c +++ b/test/test_buddy.c @@ -404,12 +404,17 @@ static test_result_t test_cross_heap_free(void) { /* Switch to heap_a and free blocks from the wrong heap */ ray_tl_heap = heap_a; - ray_free(blk1); /* should go to heap_a->foreign */ + ray_free(blk1); /* routed to heap_b — the owner — not to heap_a */ ray_free(blk2); ray_free(blk3); + TEST_ASSERT_NULL(atomic_load(&heap_a->foreign)); + TEST_ASSERT_NOT_NULL(atomic_load(&heap_b->foreign)); - /* Flush foreign blocks back to their owning heap */ + /* heap_a has nothing of its own queued; heap_b takes its blocks back. */ ray_heap_flush_foreign(); + ray_tl_heap = heap_b; + ray_heap_flush_foreign(); + TEST_ASSERT_NULL(atomic_load(&heap_b->foreign)); /* Cleanup: destroy heap_b */ ray_tl_heap = heap_b; @@ -452,8 +457,8 @@ static test_result_t test_heap_pending_merge(void) { /* The block should still be accessible (pool transferred) */ TEST_ASSERT_EQ_U(blk->mmod, 0); - /* Free the block — goes via foreign path (heap_id mismatch) - * then flush reclaims it locally */ + /* Free the block — merge rewrote its pool header to heap_a, so this is + * an ordinary local free. */ ray_free(blk); ray_heap_flush_foreign(); diff --git a/test/test_compile.c b/test/test_compile.c index 6e12ad2a7..5d34a68d1 100644 --- a/test/test_compile.c +++ b/test/test_compile.c @@ -615,9 +615,9 @@ static test_result_t test_compile_strlen_null_slot_is_sentinel(void) { TEST_ASSERT(r->len == 3, "expected len 3"); int64_t* d = (int64_t*)ray_data(r); TEST_ASSERT_EQ_I(d[0], 5); - TEST_ASSERT_EQ_I(d[1], 0); /* strlen("") = 0 (STR has no null) */ + TEST_ASSERT_EQ_I(d[1], NULL_I64); /* canonical empty STR is null */ TEST_ASSERT_EQ_I(d[2], 1); - TEST_ASSERT_FALSE(ray_vec_is_null(r, 1)); + TEST_ASSERT_TRUE(ray_vec_is_null(r, 1)); ray_release(r); PASS(); } diff --git a/test/test_csv.c b/test/test_csv.c index c0f1bb615..9a964fc23 100644 --- a/test/test_csv.c +++ b/test/test_csv.c @@ -480,10 +480,7 @@ static test_result_t test_csv_null_bool(void) { static test_result_t test_csv_null_sym(void) { /* CSV format conflates "empty field" and "missing field" — both - * appear as a zero-length cell. The Rayforce loader interns empty - * SYM cells as the empty SYM (not the null sentinel) so SQL-style - * `(!= col "")` filters work the way users expect. RAY_STR columns - * and non-string types preserve the null distinction. */ + * appear as a zero-length cell. Empty SYM is the canonical null. */ ray_heap_init(); (void)ray_sym_init(); @@ -496,7 +493,7 @@ static test_result_t test_csv_null_sym(void) { ray_t* col = ray_table_get_col_idx(loaded, 0); TEST_ASSERT_FALSE(ray_vec_is_null(col, 0)); - TEST_ASSERT_FALSE(ray_vec_is_null(col, 1)); /* empty → empty SYM, not null */ + TEST_ASSERT_TRUE(ray_vec_is_null(col, 1)); /* empty → canonical SYM null */ TEST_ASSERT_FALSE(ray_vec_is_null(col, 2)); /* Row 1's SYM ID resolves to a zero-length string — the empty SYM. @@ -563,10 +560,9 @@ static test_result_t test_csv_null_mixed_columns(void) { TEST_ASSERT_FALSE(ray_vec_is_null(val_col, 1)); TEST_ASSERT_TRUE(ray_vec_is_null(val_col, 2)); - /* name column: alice, "", bob — empty SYM cell becomes the empty - * SYM (not null). See test_csv_null_sym for the rationale. */ + /* name column: alice, canonical empty/null SYM, bob. */ TEST_ASSERT_FALSE(ray_vec_is_null(name_col, 0)); - TEST_ASSERT_FALSE(ray_vec_is_null(name_col, 1)); + TEST_ASSERT_TRUE(ray_vec_is_null(name_col, 1)); TEST_ASSERT_FALSE(ray_vec_is_null(name_col, 2)); ray_release(loaded); @@ -608,9 +604,8 @@ static test_result_t test_csv_explicit_str_schema(void) { s = ray_str_vec_get(note, 1, &l); TEST_ASSERT_EQ_I((int)l, 35); TEST_ASSERT_MEM_EQ(35, s, "this-is-a-long-string-over-12-bytes"); - /* A blank CSV field for a STR column is the empty string "" (a value), - * not a null — consistent with SYM and the STR no-null model. */ - TEST_ASSERT_FALSE(ray_vec_is_null(note, 2)); + /* A blank CSV field is the canonical empty/null STR. */ + TEST_ASSERT_TRUE(ray_vec_is_null(note, 2)); s = ray_str_vec_get(note, 2, &l); TEST_ASSERT_EQ_I((int)l, 0); s = ray_str_vec_get(note, 3, &l); @@ -1643,6 +1638,227 @@ static test_result_t test_csv_progress_never_goes_backwards(void) { PASS(); } +/* -------------------------------------------------------------------------- + * Parallel row-offset scan — chunk-boundary stitching. + * + * build_row_offsets_par splits the file into chunks and reconciles quote + * parity across them, so its entire risk surface is what a boundary lands in + * the middle of: a quoted field carrying a newline, a "" escape run, or the + * two bytes of a "\r\n". A test build shrinks the chunking (see + * CSV_SCAN_CHUNKS in csv.c) to RAY_POOL_INIT_TASKS chunks, which over these + * ~20 KB fixtures puts a boundary every ~20 bytes — i.e. essentially every + * position in the file is tried as a split point across the matrix. + * + * The oracle is exact and catches all three failure modes at once: every row + * begins with its own index, so a dropped row, a duplicated row or a row + * split in the wrong place all show up as either a wrong row count or a gap + * in column 0. + * -------------------------------------------------------------------------- */ + +static uint32_t bmx_rand(uint32_t* s) { /* xorshift32, reproducible */ + uint32_t x = *s; + x ^= x << 13; x ^= x >> 17; x ^= x << 5; + return (*s = x); +} + +/* One randomized fixture + full verification. `quoted` picks the state + * machine under test: the quote-parity one, or the quote-free fast path + * (whose terminator grammar differs — only '\n' ends a row and a following + * '\r' is absorbed — so it gets its own terminator menu). */ +static bool bmx_one_case(uint32_t* seed, bool quoted, int n_rows) { + /* Hazards for the quoted machine. Odd and even "" runs both appear, so + * a boundary can land on either parity inside a run. */ + static const char* const q_fields[] = { + "\"a\nb\"", "\"a\r\nb\"", "\"a\rb\"", "\"x\"\"y\"", + "\"x\"\"\"\"y\"", "\"\"\"\"", "\"p,q\"", "\"\"", + "\"pad0123456789abcdef\"", "plain", "", "\"z\nz\r\nz\rz\"", + }; + static const char* const p_fields[] = { + "plain", "", "abc", "pad0123456789", "0", "-12", "long_field_value", + }; + static const char* const q_terms[] = { "\n", "\r\n", "\r" }; + static const char* const p_terms[] = { "\n", "\n\r" }; + + FILE* f = fopen(TMP_CSV, "wb"); + if (!f) return false; + fputs("i,a,b\n", f); + for (int r = 0; r < n_rows; r++) { + const char* a; + const char* b; + const char* t; + if (quoted) { + a = q_fields[bmx_rand(seed) % (sizeof(q_fields) / sizeof(*q_fields))]; + b = q_fields[bmx_rand(seed) % (sizeof(q_fields) / sizeof(*q_fields))]; + t = q_terms[bmx_rand(seed) % (sizeof(q_terms) / sizeof(*q_terms))]; + } else { + a = p_fields[bmx_rand(seed) % (sizeof(p_fields) / sizeof(*p_fields))]; + b = p_fields[bmx_rand(seed) % (sizeof(p_fields) / sizeof(*p_fields))]; + t = p_terms[bmx_rand(seed) % (sizeof(p_terms) / sizeof(*p_terms))]; + } + fprintf(f, "%d,%s,%s%s", r, a, b, t); + } + fclose(f); + + int8_t schema[] = {RAY_I64, RAY_STR, RAY_STR}; + ray_t* t = ray_read_csv_opts(TMP_CSV, ',', true, schema, 3); + bool ok = t && !RAY_IS_ERR(t) && t->type == RAY_TABLE && + ray_table_nrows(t) == n_rows; + if (ok) { + /* Column 0 must be exactly 0..n_rows-1: any mis-stitch either shifts + * a row start into the middle of a field (index parses as null) or + * changes how many rows there are. */ + const int64_t* idx = (const int64_t*)ray_data(ray_table_get_col_idx(t, 0)); + for (int r = 0; r < n_rows; r++) + if (idx[r] != r) { ok = false; break; } + } + if (t) ray_release(t); + unlink(TMP_CSV); + return ok; +} + +static test_result_t test_csv_scan_boundary_matrix(void) { + ray_heap_init(); + (void)ray_sym_init(); + + uint32_t seed = 0x9e3779b9u; + bool ok = true; + /* ~700 rows keeps each fixture around 20 KB — comfortably past the test + * build's parallel-scan threshold, small enough that 120 of them cost a + * fraction of a second even under ASan. */ + for (int i = 0; i < 60 && ok; i++) ok = bmx_one_case(&seed, true, 700); + for (int i = 0; i < 60 && ok; i++) ok = bmx_one_case(&seed, false, 900); + + ray_sym_destroy(); + ray_heap_destroy(); + TEST_ASSERT_TRUE(ok); + PASS(); +} + +/* -------------------------------------------------------------------------- + * SYM interning — id assignment order. + * + * The intern is parallelized as: per-column local dedupe (threads) -> serial + * intern of only the distinct strings -> per-column code->id remap (threads). + * That is only sound because it reproduces the id assignment of a plain + * row-by-row walk, and a symbol's id IS its first-encounter order, so the + * property to pin is: ids are allocated column by column (ascending), and + * within a column row by row, first occurrence only. + * + * The fixture makes that order fully predictable and then reads the ids back + * with ray_sym_find: + * col a "a" for k = 0..NA-1, cycling -> first occurrences in k order + * col b the same vocabulary REVERSED -> must reuse col a's ids, not + * allocate new ones in b's order + * col c "c", one per row -> allocated after all of a's + * col d MIXED, cycling every 3 rows: + * r%3==0 "a<(7r) mod ND>" already interned by col a + * r%3==1 "d" NEW, must be allocated in d's ROW + * order, after every id col c allocated + * r%3==2 "" empty -> local code 0 -> empty sym id + * col d is the case the whole argument leans on hardest: one column that both + * reuses ids from an earlier column AND allocates its own, so a step that + * replayed dictionaries in the wrong order, or that mixed up which entries + * were new, would land visibly wrong ids. Its empties also cover the code-0 + * remap, which is the one value step C does not read out of the dictionary. + * + * Path coverage in the one fixture: cols a, b, d are under the test build's + * CSV_DEDUP_MAX_ENTS (8192) so they take the local-dictionary path; col c's + * distinct count is over it so it takes the overflow fallback. One expected + * id sequence spans both. + * -------------------------------------------------------------------------- */ +static test_result_t test_csv_sym_id_order(void) { + ray_heap_init(); + (void)ray_sym_init(); + + const int NA = 5000; /* col a distinct — under the dedupe ceiling */ + const int NROWS = 30000; /* col c distinct — over it */ + /* col d: ND reused strings + ND new ones = 8000 distinct, still under the + * ceiling. ND divides into NA and 7 is coprime with it, so (7r) mod ND + * scrambles the reuse order without ever naming a string col a missed. */ + const int ND = 4000; + const int NDNEW = 4000; /* "d0".."d3999", first seen at rows 1,4,7,... */ + + FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_NOT_NULL(f); + fputs("a,b,c,d\n", f); + for (int r = 0; r < NROWS; r++) { + char d[32]; + switch (r % 3) { + case 0: snprintf(d, sizeof(d), "a%d", (7 * r) % ND); break; + case 1: snprintf(d, sizeof(d), "d%d", (r / 3) % NDNEW); break; + default: d[0] = '\0'; break; /* empty field */ + } + fprintf(f, "a%d,a%d,c%d,%s\n", r % NA, NA - 1 - (r % NA), r, d); + } + fclose(f); + + int8_t schema[] = {RAY_SYM, RAY_SYM, RAY_SYM, RAY_SYM}; + ray_t* t = ray_read_csv_opts(TMP_CSV, ',', true, schema, 4); + bool ok = t && !RAY_IS_ERR(t) && t->type == RAY_TABLE && + ray_table_nrows(t) == NROWS; + + char buf[32]; + int64_t a0 = -1; + if (ok) { + int n = snprintf(buf, sizeof(buf), "a%d", 0); + a0 = ray_sym_find(buf, (size_t)n); + ok = a0 > 0; + } + /* col a: consecutive ids in first-occurrence (k ascending) order. */ + for (int k = 0; ok && k < NA; k++) { + int n = snprintf(buf, sizeof(buf), "a%d", k); + if (ray_sym_find(buf, (size_t)n) != a0 + k) ok = false; + } + /* col b reused those strings; had b been interned in ITS own order the + * "a" end of the range would hold the lower ids. */ + /* col c: allocated strictly after every a, in row order. */ + for (int r = 0; ok && r < NROWS; r++) { + int n = snprintf(buf, sizeof(buf), "c%d", r); + if (ray_sym_find(buf, (size_t)n) != a0 + NA + r) ok = false; + } + /* col d's NEW strings: allocated after every id col c allocated, and in + * d's own row order — "d" is first seen at row 3k+1, so k ascending. + * The reused "a<...>" values interleaved between them must have consumed + * no ids at all, or these would not be consecutive. */ + for (int k = 0; ok && k < NDNEW; k++) { + int n = snprintf(buf, sizeof(buf), "d%d", k); + if (ray_sym_find(buf, (size_t)n) != a0 + NA + NROWS + k) ok = false; + } + /* And the id actually STORED in a cell is that symbol's id — the remap + * step has to land the right value in the row, not just intern the right + * string. Row 0 of col b is "a", the LAST id col a allocated. */ + if (ok) { + ray_t* cb = ray_table_get_col_idx(t, 1); + int64_t pos = ray_read_sym(ray_data(cb), 0, RAY_SYM, cb->attrs); + int n = snprintf(buf, sizeof(buf), "a%d", NA - 1); + ok = (pos == a0 + NA - 1) && (ray_sym_find(buf, (size_t)n) == pos); + } + /* Col d's three row shapes, read out of the column: a reused id, a newly + * allocated one, and the empty-field code-0 remap (the only value step C + * does not take from the dictionary). */ + if (ok) { + ray_t* cd = ray_table_get_col_idx(t, 3); + const void* dd = ray_data(cd); + int64_t empty_id = ray_sym_find("", 0); + int64_t p0 = ray_read_sym(dd, 0, RAY_SYM, cd->attrs); /* "a0" */ + int64_t p1 = ray_read_sym(dd, 1, RAY_SYM, cd->attrs); /* "d0" */ + int64_t p2 = ray_read_sym(dd, 2, RAY_SYM, cd->attrs); /* "" */ + int64_t p3 = ray_read_sym(dd, 3, RAY_SYM, cd->attrs); /* "a21" */ + ok = empty_id >= 0 && + p0 == a0 && + p1 == a0 + NA + NROWS && + p2 == empty_id && + p3 == a0 + ((7 * 3) % ND); + } + + if (t) ray_release(t); + unlink(TMP_CSV); + ray_sym_destroy(); + ray_heap_destroy(); + TEST_ASSERT_TRUE(ok); + 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 }, @@ -1697,5 +1913,7 @@ const test_entry_t csv_entries[] = { { "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 }, + { "csv/scan_boundary_matrix", test_csv_scan_boundary_matrix, NULL, NULL }, + { "csv/sym_id_order", test_csv_sym_id_order, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_dict.c b/test/test_dict.c index a868b6d86..7d97a1074 100644 --- a/test/test_dict.c +++ b/test/test_dict.c @@ -1174,8 +1174,8 @@ static test_result_t test_dict_find_idx_str_with_nulls(void) { TEST_ASSERT_EQ_I(ray_dict_find_idx(d, ka), 2); ray_release(ka); - /* STR has no distinct null. ray_vec_set_null above collapses slot 1 to - * the ordinary empty string, so lookup resolves by ordinary equality. */ + /* STR's canonical null is empty. Dictionary lookup still resolves that + * in-band key by ordinary equality. */ ka = ray_str("", 0); TEST_ASSERT_EQ_I(ray_dict_find_idx(d, ka), 1); ray_release(ka); diff --git a/test/test_exec.c b/test/test_exec.c index 199e2e6cb..52c346358 100644 --- a/test/test_exec.c +++ b/test/test_exec.c @@ -2105,7 +2105,8 @@ static test_result_t test_exec_strlen(void) { TEST_ASSERT_EQ_I(rdata[1], 5); /* "WORLD" */ TEST_ASSERT_EQ_I(rdata[2], 7); /* " foo " */ TEST_ASSERT_EQ_I(rdata[3], 7); /* "bar_baz" */ - TEST_ASSERT_EQ_I(rdata[4], 0); /* "" */ + TEST_ASSERT_EQ_I(rdata[4], NULL_I64); /* canonical empty STR is null */ + TEST_ASSERT_TRUE(ray_vec_is_null(result, 4)); ray_release(result); ray_graph_free(g); @@ -2775,7 +2776,8 @@ static test_result_t test_exec_str_strlen(void) { TEST_ASSERT_EQ_I(d[1], 5); /* "WORLD" */ TEST_ASSERT_EQ_I(d[2], 7); /* " foo " */ TEST_ASSERT_EQ_I(d[3], 7); /* "bar_baz" */ - TEST_ASSERT_EQ_I(d[4], 0); /* "" */ + TEST_ASSERT_EQ_I(d[4], NULL_I64); /* canonical empty STR is null */ + TEST_ASSERT_TRUE(ray_vec_is_null(result, 4)); ray_release(result); ray_graph_free(g); @@ -3286,8 +3288,8 @@ static test_result_t test_exec_str_upper_null(void) { TEST_ASSERT_EQ_U(len, 5); TEST_ASSERT_MEM_EQ(5, s0, "HELLO"); - /* Row 1: empty -> empty (STR has no null) */ - TEST_ASSERT_FALSE(ray_vec_is_null(result, 1)); + /* Row 1: canonical empty/null propagates. */ + TEST_ASSERT_TRUE(ray_vec_is_null(result, 1)); (void)ray_str_vec_get(result, 1, &len); TEST_ASSERT_EQ_U(len, 0); @@ -3329,7 +3331,8 @@ static test_result_t test_exec_str_strlen_null(void) { TEST_ASSERT_EQ_I(result->type, RAY_I64); int64_t* d = (int64_t*)ray_data(result); TEST_ASSERT_EQ_I(d[0], 5); - TEST_ASSERT_EQ_I(d[1], 0); /* empty string -> length 0 (STR has no null) */ + TEST_ASSERT_EQ_I(d[1], NULL_I64); /* canonical empty STR is null */ + TEST_ASSERT_TRUE(ray_vec_is_null(result, 1)); TEST_ASSERT_EQ_I(d[2], 3); ray_release(result); @@ -3372,8 +3375,8 @@ static test_result_t test_exec_str_substr_null(void) { TEST_ASSERT_EQ_U(len, 3); TEST_ASSERT_MEM_EQ(3, s0, "hel"); - /* Row 1: empty in -> empty out (STR has no null) */ - TEST_ASSERT_FALSE(ray_vec_is_null(result, 1)); + /* Row 1: canonical empty/null propagates. */ + TEST_ASSERT_TRUE(ray_vec_is_null(result, 1)); (void)ray_str_vec_get(result, 1, &len); TEST_ASSERT_EQ_U(len, 0); @@ -3421,8 +3424,8 @@ static test_result_t test_exec_str_replace_null(void) { TEST_ASSERT_EQ_U(len, 5); TEST_ASSERT_MEM_EQ(5, s0, "hell0"); - /* Row 1: empty in -> empty out (STR has no null) */ - TEST_ASSERT_FALSE(ray_vec_is_null(result, 1)); + /* Row 1: canonical empty/null propagates. */ + TEST_ASSERT_TRUE(ray_vec_is_null(result, 1)); (void)ray_str_vec_get(result, 1, &len); TEST_ASSERT_EQ_U(len, 0); @@ -3479,7 +3482,7 @@ static test_result_t test_exec_str_concat_null(void) { TEST_ASSERT_EQ_U(len, 8); TEST_ASSERT_MEM_EQ(8, s0, "John Doe"); - /* Row 1: empty first arg -> "" + " Smith" = " Smith" (STR has no null) */ + /* Row 1: canonical empty/null contributes zero bytes to concat. */ TEST_ASSERT_FALSE(ray_vec_is_null(result, 1)); const char* s1c = ray_str_vec_get(result, 1, &len); TEST_ASSERT_EQ_U(len, 6); @@ -9844,8 +9847,8 @@ static test_result_t test_expr_sym_w64_cmp(void) { cnt = ray_count(g, flt); result = ray_execute(g, cnt); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - /* id1 at positions 0 and 3 (null slot raw = id1 == id1 → true): 2 matches */ - TEST_ASSERT_EQ_I(result->i64, 2); + /* Only the non-null id1 at position 0 matches. */ + TEST_ASSERT_EQ_I(result->i64, 1); ray_release(result); ray_graph_free(g); @@ -15402,7 +15405,8 @@ static test_result_t test_expr_binary_bool_float_path_lhs(void) { op = ray_or(g, a, b); s = ray_sum(g, op); result = ray_execute(g, s); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->i64, 3); + /* The canonical empty/null SYM lane does not contribute. */ + TEST_ASSERT_EQ_I(result->i64, 2); ray_release(result); ray_graph_free(g); ray_release(tbl); @@ -16479,12 +16483,16 @@ static test_result_t test_expr_binary_range_f64_nan_branches(void) { ray_heap_init(); (void)ray_sym_init(); - /* F64 vectors WITHOUT HAS_NULLS — raw NaN values, no bitmap null. - * ray_vec_from_raw does NOT set HAS_NULLS; NaN is just a bit pattern. */ + /* F64 vectors WITHOUT HAS_NULLS. from_raw flags sentinel NaNs (#445), + * so strip the attr deliberately: this test pins the tolerance path for + * unflagged sentinels (legacy / flag-dropped vectors), where NaN is + * just a bit pattern. */ double rawa[] = {NAN, NAN, 1.0}; double rawb[] = {NAN, 1.0, NAN}; ray_t* va = ray_vec_from_raw(RAY_F64, rawa, 3); ray_t* vb = ray_vec_from_raw(RAY_F64, rawb, 3); + va->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + vb->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; /* Verify: no bitmap null set */ TEST_ASSERT_FALSE(va->attrs & RAY_ATTR_HAS_NULLS); TEST_ASSERT_FALSE(vb->attrs & RAY_ATTR_HAS_NULLS); diff --git a/test/test_format.c b/test/test_format.c index c9e70b080..5fe55af06 100644 --- a/test/test_format.c +++ b/test/test_format.c @@ -498,6 +498,91 @@ static test_result_t test_fmt_raw_elem_list_null(void) { } /* ---- Test: table with short col that triggers NA in head half ---- */ +/* #454: cell padding must use DISPLAY width, not byte length. A CJK char + * is 3 UTF-8 bytes but renders 2 terminal columns, so byte-based padding + * tore the table borders on any row holding a multi-byte symbol. */ +static test_result_t test_fmt_table_utf8_width(void) { + ray_t* tbl = ray_table_new(2); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); + + /* "ab牛来": 8 bytes, 6 display columns. "abcd": 4 bytes, 4 columns. */ + const char* wide_sym = "ab\xe7\x89\x9b\xe6\x9d\xa5"; + int64_t ids[] = { ray_sym_intern(wide_sym, 8), ray_sym_intern("abcd", 4) }; + int64_t vals[] = { 1, 2 }; + ray_t* col_s = ray_vec_from_raw(RAY_SYM, ids, 2); + ray_t* col_v = ray_vec_from_raw(RAY_I64, vals, 2); + TEST_ASSERT_FALSE(RAY_IS_ERR(col_s)); + TEST_ASSERT_FALSE(RAY_IS_ERR(col_v)); + tbl = ray_table_add_col(tbl, ray_sym_intern("s", 1), col_s); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); + tbl = ray_table_add_col(tbl, ray_sym_intern("v", 1), col_v); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); + + ray_t* result = ray_fmt(tbl, 1); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + const char* s = ray_str_ptr(result); + + const char* wide_line = strstr(s, wide_sym); + const char* ascii_line = strstr(s, "abcd"); + TEST_ASSERT_NOT_NULL(wide_line); + TEST_ASSERT_NOT_NULL(ascii_line); + while (wide_line > s && wide_line[-1] != '\n') wide_line--; + while (ascii_line > s && ascii_line[-1] != '\n') ascii_line--; + size_t wide_len = strcspn(wide_line, "\n"); + size_t ascii_len = strcspn(ascii_line, "\n"); + + /* Equal display width means the wide row carries exactly the byte + * surplus of its wide chars: 2 CJK chars x (3 bytes - 2 columns) + * = +2 bytes over the ASCII row. Byte-based padding rendered the + * two rows byte-EQUAL (and visually torn), which this catches. */ + TEST_ASSERT_EQ_I((int64_t)wide_len, (int64_t)ascii_len + 2); + + ray_release(result); + ray_release(col_s); + ray_release(col_v); + ray_release(tbl); + + /* Combining marks are width 0: bare and pointed Hebrew are the same + * four letters and must occupy the same four columns, so their data + * lines differ by exactly the marks' byte count. */ + const char* heb_bare = "\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d"; /* שלום */ + const char* heb_marked = "\xd7\xa9\xd7\x81\xd6\xb8" /* ש + dot + qamats */ + "\xd7\x9c\xd7\x95\xd6\xb9\xd7\x9d"; /* ל, ו + holam, ם */ + ray_t* tbl2 = ray_table_new(1); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl2)); + int64_t hids[] = { + ray_sym_intern(heb_bare, (int64_t)strlen(heb_bare)), + ray_sym_intern(heb_marked, (int64_t)strlen(heb_marked)), + }; + ray_t* col_h = ray_vec_from_raw(RAY_SYM, hids, 2); + TEST_ASSERT_FALSE(RAY_IS_ERR(col_h)); + tbl2 = ray_table_add_col(tbl2, ray_sym_intern("h", 1), col_h); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl2)); + + ray_t* result2 = ray_fmt(tbl2, 1); + TEST_ASSERT_FALSE(RAY_IS_ERR(result2)); + const char* s2 = ray_str_ptr(result2); + const char* bare_line = strstr(s2, heb_bare); + const char* marked_line = strstr(s2, heb_marked); + TEST_ASSERT_NOT_NULL(bare_line); + TEST_ASSERT_NOT_NULL(marked_line); + /* strstr(heb_bare) can land on the marked row if the marked bytes embed + * the bare sequence — they don't (marks interleave), but anchor to line + * starts to be safe. */ + while (bare_line > s2 && bare_line[-1] != '\n') bare_line--; + while (marked_line > s2 && marked_line[-1] != '\n') marked_line--; + TEST_ASSERT_TRUE(bare_line != marked_line); + size_t bare_len = strcspn(bare_line, "\n"); + size_t marked_len = strcspn(marked_line, "\n"); + int64_t mark_bytes = (int64_t)strlen(heb_marked) - (int64_t)strlen(heb_bare); + TEST_ASSERT_EQ_I((int64_t)marked_len, (int64_t)bare_len + mark_bytes); + + ray_release(result2); + ray_release(col_h); + ray_release(tbl2); + PASS(); +} + static test_result_t test_fmt_table_na_head(void) { /* With nrows=5 (half=2), a col of len=1 has ri=0 hit, ri=1 miss -> NA in head */ int64_t nrows = 5; @@ -745,9 +830,8 @@ static test_result_t test_fmt_null_date(void) { } static test_result_t test_fmt_null_str(void) { - /* A STR atom has no distinct null: ray_typed_null collapses to the - * ordinary empty string and renders as "" — never 0Nc (which the parser - * cannot even read back). */ + /* STR's canonical null is the empty string and renders as "" — never + * 0Nc, which the parser cannot even read back. */ ray_t* result = ray_fmt(ray_typed_null(-RAY_STR), 1); TEST_ASSERT_NOT_NULL(result); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); @@ -779,8 +863,8 @@ static test_result_t test_fmt_null_guid(void) { } static test_result_t test_fmt_null_sym(void) { - /* SYM has no null: ray_typed_null(-RAY_SYM) is sym 0 (the empty - * symbol), which renders as the bare quote literal '. */ + /* SYM's canonical null is sym 0 (the empty symbol), which renders as + * the bare quote literal '. */ ray_t* result = ray_fmt(ray_typed_null(-RAY_SYM), 1); TEST_ASSERT_NOT_NULL(result); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); @@ -943,8 +1027,8 @@ static test_result_t test_fmt_vec_str(void) { } static test_result_t test_fmt_vec_str_null(void) { - /* A requested null in a STR vector collapses to the ordinary empty - * string, so it renders as "" and its null predicate remains false. */ + /* A requested null in a STR vector uses the canonical empty string, so + * it renders as "" while its null predicate remains true. */ ray_t* vec = ray_vec_new(RAY_STR, 2); TEST_ASSERT_NOT_NULL(vec); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); @@ -1763,5 +1847,6 @@ const test_entry_t format_entries[] = { { "format/table/wide_tall", test_fmt_table_wide_and_tall, fmt_setup, fmt_teardown }, { "format/table/list_col_null", test_fmt_raw_elem_list_null, fmt_setup, fmt_teardown }, { "format/table/na_head", test_fmt_table_na_head, fmt_setup, fmt_teardown }, + { "format/table/utf8_width", test_fmt_table_utf8_width, fmt_setup, fmt_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_fused_topk.c b/test/test_fused_topk.c index 67efafc12..11a29d7ba 100644 --- a/test/test_fused_topk.c +++ b/test/test_fused_topk.c @@ -257,8 +257,8 @@ static test_result_t test_topk_sym_key(void) { PASS(); } -/* Chunk 9 part 3: nulls in sort key — exercises the has_nulls leg - * (lines 133-139). ASC: NULLS LAST; DESC: NULLS FIRST. */ +/* Chunk 9 part 3: nulls in sort key — exercises the has_nulls leg. + * A null is the smallest value: ASC puts nulls FIRST, DESC puts them LAST. */ static test_result_t test_topk_null_sort_key_asc(void) { int64_t N = 20; ray_t* kc = ray_vec_new(RAY_I64, N); kc->len = N; @@ -291,14 +291,16 @@ static test_result_t test_topk_null_sort_key_asc(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(res)); TEST_ASSERT_EQ_I(ray_table_nrows(res), k_pick); - /* ASC, NULLS LAST: K=5 smallest non-null k. Non-null rows have - * k ∈ {1,2,3,4,6,7,8,9,11,...19}. Top 5 ASC = {1,2,3,4,6}. */ + /* ASC, NULLS FIRST: the three null rows are the three smallest, in + * source order, and the two smallest non-nulls follow: 1, 2. */ ray_t* k_col = ray_table_get_col(res, s_k); TEST_ASSERT_NOT_NULL(k_col); - int64_t expected[5] = {1, 2, 3, 4, 6}; - for (int64_t i = 0; i < 5; i++) { - TEST_ASSERT_FALSE(ray_vec_is_null(k_col, i)); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(k_col))[i], expected[i]); + for (int64_t i = 0; i < 3; i++) + TEST_ASSERT_TRUE(ray_vec_is_null(k_col, i)); + int64_t expected[2] = {1, 2}; + for (int64_t i = 0; i < 2; i++) { + TEST_ASSERT_FALSE(ray_vec_is_null(k_col, 3 + i)); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(k_col))[3 + i], expected[i]); } ray_release(res); ray_release(where_expr); ray_release(tbl); @@ -326,7 +328,7 @@ static test_result_t test_topk_null_sort_key_desc(void) { ray_t* where_expr = ray_parse("(>= sel 0)"); int64_t sort_keys[1] = { s_k }; - uint8_t sort_descs[1] = { 1 }; /* DESC, NULLS FIRST */ + uint8_t sort_descs[1] = { 1 }; /* DESC, so NULLS LAST */ int64_t out_syms[2] = { s_k, s_sel }; int64_t k_pick = 5; ray_t* res = ray_fused_topk_select(tbl, where_expr, @@ -336,20 +338,66 @@ static test_result_t test_topk_null_sort_key_desc(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(res)); TEST_ASSERT_EQ_I(ray_table_nrows(res), k_pick); - /* DESC, NULLS FIRST: K=5 results — first 3 must be the null rows - * (rows 0, 5, 10) — followed by the 2 highest non-null values - * (k=19, k=18). */ + /* DESC, NULLS LAST: a null is the smallest value, so it never enters a + * DESC top-5 while five larger values exist. All five are the highest + * non-nulls: 19, 18, 17, 16, 15. */ ray_t* k_col = ray_table_get_col(res, s_k); TEST_ASSERT_NOT_NULL(k_col); - /* Check that the first 3 rows are null. */ - TEST_ASSERT_TRUE(ray_vec_is_null(k_col, 0)); - TEST_ASSERT_TRUE(ray_vec_is_null(k_col, 1)); - TEST_ASSERT_TRUE(ray_vec_is_null(k_col, 2)); - /* Slots 3 and 4 are non-null with k=19 and k=18 (DESC). */ - TEST_ASSERT_FALSE(ray_vec_is_null(k_col, 3)); - TEST_ASSERT_FALSE(ray_vec_is_null(k_col, 4)); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(k_col))[3], 19); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(k_col))[4], 18); + for (int64_t i = 0; i < 5; i++) { + TEST_ASSERT_FALSE(ray_vec_is_null(k_col, i)); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(k_col))[i], 19 - i); + } + + ray_release(res); ray_release(where_expr); ray_release(tbl); + PASS(); +} + +/* DESC top-k that has to reach past the non-nulls. With nulls last, a + * null enters the result only when there are fewer than k non-null rows — + * the back-fill leg of the bounded heap, which no other test exercises: + * every DESC case above has more non-nulls than k, so the null branch is + * only ever taken to REJECT. */ +static test_result_t test_topk_null_desc_backfill(void) { + int64_t N = 20; + ray_t* kc = ray_vec_new(RAY_I64, N); kc->len = N; + int64_t* kd = (int64_t*)ray_data(kc); + for (int64_t i = 0; i < N; i++) kd[i] = i; + /* Only rows 3, 11 and 17 are non-null: 3 values for a k of 5. */ + for (int64_t i = 0; i < N; i++) + if (i != 3 && i != 11 && i != 17) ray_vec_set_null(kc, i, true); + + ray_t* selc = ray_vec_new(RAY_I64, N); selc->len = N; + int64_t* sd = (int64_t*)ray_data(selc); + for (int64_t i = 0; i < N; i++) sd[i] = i; + + int64_t s_k = ray_sym_intern("k", 1); + int64_t s_sel = ray_sym_intern("sel", 3); + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, s_k, kc); ray_release(kc); + tbl = ray_table_add_col(tbl, s_sel, selc); ray_release(selc); + + ray_t* where_expr = ray_parse("(>= sel 0)"); + int64_t sort_keys[1] = { s_k }; + uint8_t sort_descs[1] = { 1 }; /* DESC, so NULLS LAST */ + int64_t out_syms[2] = { s_k, s_sel }; + int64_t k_pick = 5; + ray_t* res = ray_fused_topk_select(tbl, where_expr, + sort_keys, sort_descs, 1, k_pick, + out_syms, NULL, 2); + TEST_ASSERT_NOT_NULL(res); + TEST_ASSERT_FALSE(RAY_IS_ERR(res)); + TEST_ASSERT_EQ_I(ray_table_nrows(res), k_pick); + + /* 17, 11, 3, then two nulls in source order. */ + ray_t* k_col = ray_table_get_col(res, s_k); + TEST_ASSERT_NOT_NULL(k_col); + int64_t expect[3] = {17, 11, 3}; + for (int64_t i = 0; i < 3; i++) { + TEST_ASSERT_FALSE(ray_vec_is_null(k_col, i)); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(k_col))[i], expect[i]); + } + TEST_ASSERT_TRUE(ray_vec_is_null(k_col, 3)); + TEST_ASSERT_TRUE(ray_vec_is_null(k_col, 4)); ray_release(res); ray_release(where_expr); ray_release(tbl); PASS(); @@ -1100,7 +1148,7 @@ static test_result_t test_topk_both_nulls_tie(void) { tbl = ray_table_add_col(tbl, s_sel, sc); ray_release(sc); ray_t* where_expr = ray_parse("(>= sel 0)"); - /* Sort by k1 ASC (nulls last), then k2 ASC. */ + /* Sort by k1 ASC (a null is smallest, so nulls lead), then k2 ASC. */ int64_t sort_keys[2] = { s_k1, s_k2 }; uint8_t sort_descs[2] = { 0, 0 }; int64_t out_syms[2] = { s_k1, s_k2 }; @@ -1111,13 +1159,13 @@ static test_result_t test_topk_both_nulls_tie(void) { TEST_ASSERT_NOT_NULL(res); TEST_ASSERT_FALSE(RAY_IS_ERR(res)); TEST_ASSERT_EQ_I(ray_table_nrows(res), k_pick); - /* Non-null k1 values start at row 2 (k1=0). (k1 ASC, k2 ASC): - * k1=0: rows 4(k2=16), 3(k2=17), 2(k2=18). - * k1=1: rows 9(k2=11), 8(k2=12), 7(k2=13), 6(k2=14). - * Top 5 = {16, 17, 18, 11, 12}. */ + /* (k1 ASC, k2 ASC). The four k1-nulls are the smallest and lead; two + * nulls tie on k1, so k2 orders them: rows 10(k2=10), 5(k2=15), + * 1(k2=19), 0(k2=20). The fifth slot is the smallest k2 of the + * smallest non-null k1 group (k1=0: rows 2,3,4) — row 4, k2=16. */ ray_t* k2_col = ray_table_get_col(res, s_k2); TEST_ASSERT_NOT_NULL(k2_col); - int64_t expect_k2[] = {16, 17, 18, 11, 12}; + int64_t expect_k2[] = {10, 15, 19, 20, 16}; for (int64_t i = 0; i < k_pick; i++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(k2_col))[i], expect_k2[i]); ray_release(res); ray_release(where_expr); ray_release(tbl); @@ -1230,7 +1278,7 @@ static test_result_t test_topk_multi_key_null_tiebreak(void) { tbl = ray_table_add_col(tbl, s_sel, sc); ray_release(sc); ray_t* where_expr = ray_parse("(>= sel 0)"); - /* k1 ASC (nulls last), k2 DESC for tie-break. */ + /* k1 ASC (a null is smallest, so nulls lead), k2 DESC for tie-break. */ int64_t sort_keys[2] = { s_k1, s_k2 }; uint8_t sort_descs[2] = { 0, 1 }; int64_t out_syms[3] = { s_k1, s_k2, s_sel }; @@ -1241,12 +1289,12 @@ static test_result_t test_topk_multi_key_null_tiebreak(void) { TEST_ASSERT_NOT_NULL(res); TEST_ASSERT_FALSE(RAY_IS_ERR(res)); TEST_ASSERT_EQ_I(ray_table_nrows(res), k_pick); - /* Non-null k1: smallest k1=0 at rows 2,3; then k1=1 at rows 4,5,6,7. - * For k1=0: k2 DESC → row 3(k2=3), row 2(k2=2). - * For k1=1: k2 DESC → row 7(k2=3), row 6(k2=2), row 5(k2=1), row 4(k2=0). - * Top 6 = rows 3,2,7,6,5,4. */ + /* The four k1-nulls lead. They tie on k1, so k2 DESC orders them and + * the row index breaks the remaining ties: row 1(k2=1), row 9(k2=1), + * row 0(k2=0), row 8(k2=0). Then the smallest non-null k1 group + * (k1=0, rows 2,3) by k2 DESC: row 3(k2=3), row 2(k2=2). */ ray_t* sel_col = ray_table_get_col(res, s_sel); - int64_t expect_sel[] = {3, 2, 7, 6, 5, 4}; + int64_t expect_sel[] = {1, 9, 0, 8, 3, 2}; for (int64_t i = 0; i < k_pick; i++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(sel_col))[i], expect_sel[i]); ray_release(res); ray_release(where_expr); ray_release(tbl); @@ -1298,7 +1346,7 @@ static test_result_t test_topk_i16_with_nulls(void) { ray_t* where_expr = ray_parse("(>= sel 0)"); int64_t sort_keys[1] = { s_k }; - uint8_t sort_descs[1] = { 0 }; /* ASC, NULLS LAST */ + uint8_t sort_descs[1] = { 0 }; /* ASC, so NULLS FIRST */ int64_t out_syms[2] = { s_k, s_sel }; int64_t k_pick = 5; ray_t* res = ray_fused_topk_select(tbl, where_expr, @@ -1307,12 +1355,15 @@ static test_result_t test_topk_i16_with_nulls(void) { TEST_ASSERT_NOT_NULL(res); TEST_ASSERT_FALSE(RAY_IS_ERR(res)); TEST_ASSERT_EQ_I(ray_table_nrows(res), k_pick); - /* Non-null I16 ASC: 1,2,3,4,6 (skipping nulls at 0 and 5). */ + /* I16 ASC: the two nulls (rows 0 and 5) lead in source order, then + * the smallest non-nulls 1, 2, 3. */ ray_t* k_col = ray_table_get_col(res, s_k); - int16_t expect[] = {1, 2, 3, 4, 6}; - for (int64_t i = 0; i < k_pick; i++) { - TEST_ASSERT_FALSE(ray_vec_is_null(k_col, i)); - TEST_ASSERT_EQ_I((int64_t)((int16_t*)ray_data(k_col))[i], expect[i]); + TEST_ASSERT_TRUE(ray_vec_is_null(k_col, 0)); + TEST_ASSERT_TRUE(ray_vec_is_null(k_col, 1)); + int16_t expect[] = {1, 2, 3}; + for (int64_t i = 0; i < 3; i++) { + TEST_ASSERT_FALSE(ray_vec_is_null(k_col, 2 + i)); + TEST_ASSERT_EQ_I((int64_t)((int16_t*)ray_data(k_col))[2 + i], expect[i]); } ray_release(res); ray_release(where_expr); ray_release(tbl); PASS(); @@ -1545,6 +1596,7 @@ const test_entry_t fused_topk_entries[] = { { "fused_topk/sym_key_w32", test_topk_sym_key, topk_setup, topk_teardown }, { "fused_topk/null_sort_key_asc", test_topk_null_sort_key_asc, topk_setup, topk_teardown }, { "fused_topk/null_sort_key_desc", test_topk_null_sort_key_desc, topk_setup, topk_teardown }, + { "fused_topk/null_desc_backfill", test_topk_null_desc_backfill, topk_setup, topk_teardown }, /* Chunk 11 — gate rejections */ { "fused_topk/gate_null_tbl", test_topk_gate_null_tbl, topk_setup, topk_teardown }, { "fused_topk/gate_k_too_large", test_topk_gate_k_too_large, topk_setup, topk_teardown }, diff --git a/test/test_heap.c b/test/test_heap.c index af040c42e..fffc1b929 100644 --- a/test/test_heap.c +++ b/test/test_heap.c @@ -41,11 +41,17 @@ #include "test.h" #include #include "mem/heap.h" + +/* Restore the shipped policy after a test drives it. */ +#define RAY_HEAP_DECAY_MS_TEST_DEFAULT 10000 #include "ops/ops.h" #include #include +#include #include #include +#include +#include /* ---- Setup / Teardown -------------------------------------------------- */ @@ -289,6 +295,49 @@ static test_result_t test_scratch_arena_oversize(void) { PASS(); } +static test_result_t test_scratch_arena_direct_backing(void) { + /* A backing block at or above RAY_HEAP_POOL_ORDER is a DIRECT + * allocation: mapped at its exact page-rounded size and tagged with + * the RAY_ORDER_DIRECT sentinel instead of a real buddy order. The + * arena's window has to come from the block's true capacity — + * reading the sentinel as an order describes a 2^39-byte block, so + * every later push is bump-allocated past the end of the mapping and + * writes into unmapped address space. */ + ray_scratch_arena_t a; + ray_scratch_arena_init(&a); + + size_t big = ((size_t)1 << RAY_HEAP_POOL_ORDER) + (1u << 20); + unsigned char* p = (unsigned char*)ray_scratch_arena_push(&a, big); + TEST_ASSERT_NOT_NULL(p); + TEST_ASSERT_EQ_I(a.n_backing, 1); + TEST_ASSERT_TRUE(ray_is_direct(a.backing[0])); + + /* The window must stop at the backing's real capacity. */ + char* cap_end = (char*)ray_data(a.backing[0]) + + ray_block_data_bytes(a.backing[0]); + TEST_ASSERT_TRUE(a.end <= cap_end); + + /* Consequently the next push cannot be carved out of the leftover of + * a block that has none: it must take a backing of its own. */ + size_t follow = 4u << 20; + unsigned char* q = (unsigned char*)ray_scratch_arena_push(&a, follow); + TEST_ASSERT_NOT_NULL(q); + TEST_ASSERT_EQ_I(a.n_backing, 2); + TEST_ASSERT_TRUE((char*)q + follow <= (char*)ray_data(a.backing[1]) + + ray_block_data_bytes(a.backing[1])); + + /* Both regions must be writable end to end and must not overlap. */ + memset(p, 0x5A, big); + memset(q, 0xA5, follow); + TEST_ASSERT_EQ_U(p[0], 0x5A); + TEST_ASSERT_EQ_U(p[big - 1], 0x5A); + TEST_ASSERT_EQ_U(q[0], 0xA5); + TEST_ASSERT_EQ_U(q[follow - 1], 0xA5); + + ray_scratch_arena_reset(&a); + PASS(); +} + /* ---- ray_heap_release_pages -------------------------------------------- * * * Walks freelists at order >= 13 (8 KB+) and madvise-releases pages past @@ -319,6 +368,122 @@ static test_result_t test_release_pages(void) { PASS(); } +/* ---- Idle decay --------------------------------------------------------- * + * + * ray_heap_gc AGES a free block before releasing its pages: a block that was + * just freed keeps its footprint, which is what stops a repeated query from + * refaulting its own temporaries between iterations. The decay is the other + * half of that policy — once the process has been quiet for longer than + * threshold to zero, the same pages go back to the OS un-aged. + * + * Both halves are asserted here, on the same block, in the same test: one + * collector pass must NOT release it, and the decay immediately after must. + * The released-block count is asserted too, so the test cannot pass by + * sweeping nothing. */ + +/* Resident set in KB, or 0 where /proc is unavailable. */ +static size_t heap_rss_kb(void) { +#if defined(__linux__) + int fd = open("/proc/self/statm", O_RDONLY); + if (fd < 0) return 0; + char buf[128]; + ssize_t n = read(fd, buf, sizeof(buf) - 1); + close(fd); + if (n <= 0) return 0; + buf[n] = '\0'; + const char* p = buf; + while (*p && *p != ' ') p++; /* field 1 is total size */ + unsigned long long pages = strtoull(p, NULL, 10); + long pgsz = sysconf(_SC_PAGESIZE); + if (pgsz <= 0) return 0; + return (size_t)((pages * (unsigned long long)pgsz) / 1024); +#else + return 0; +#endif +} + +static test_result_t test_idle_decay_releases_pages(void) { + /* Threshold 0 means "release at the first maintenance point after any + * work", so the test asserts the mechanism without sleeping on a clock. */ + ray_heap_set_decay_ms(0); + + /* Order 24: comfortably above the order-13 sweep floor, and below + * RAY_HEAP_POOL_ORDER so it is a buddy block rather than a direct + * mapping that munmaps itself on free. */ + const size_t big = (16u << 20) - 4096; + ray_t* v = ray_alloc(big); + if (!v) { ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); SKIP("16 MB block unavailable"); } + memset(ray_data(v), 0xA5, big); /* fault every page in */ + + size_t rss_live = heap_rss_kb(); + ray_free(v); + + /* One collector pass can only age a freshly inserted block (attrs 0 -> 1), + * never release it. */ + ray_heap_gc(); + size_t rss_gc = heap_rss_kb(); + + ray_heap_note_activity(); + int64_t released = ray_heap_decay(); + size_t rss_decay = heap_rss_kb(); + + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + + TEST_ASSERT(released >= 1, "the decay sweep released at least one block"); + if (rss_live > 0) { + size_t half = (big / 1024) / 2; + TEST_ASSERT(rss_gc + half > rss_live, + "collector alone keeps the freed block resident"); + TEST_ASSERT(rss_decay + half < rss_live, + "decay handed most of the freed block back"); + } + + /* Disarmed: the sweep is triggered by work going quiet, not by asking. */ + TEST_ASSERT(ray_heap_decay() < 0, "a second decay with no work does nothing"); + + /* Released pages refault: the address space is untouched. */ + ray_t* w = ray_alloc(big); + TEST_ASSERT_NOT_NULL(w); + memset(ray_data(w), 0x5A, big); + ray_free(w); + PASS(); +} + +/* A decay that is not due must not sweep, however much free memory is + * lying around — that is the entire defence against releasing the pages a + * hot loop is about to reuse. */ +static test_result_t test_idle_decay_respects_threshold(void) { + ray_heap_set_decay_ms(600000); + + const size_t big = (16u << 20) - 4096; + ray_t* v = ray_alloc(big); + if (!v) { ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); SKIP("16 MB block unavailable"); } + memset(ray_data(v), 0xA5, big); + ray_free(v); + + ray_heap_note_activity(); + int64_t due = ray_heap_decay_due_ms(); + int64_t released = ray_heap_decay(); + + /* Negative threshold disables the decay outright. */ + ray_heap_set_decay_ms(-1); + int64_t due_off = ray_heap_decay_due_ms(); + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + + TEST_ASSERT(due > 0, "a sweep is pending but not yet due"); + TEST_ASSERT(released < 0, "nothing is swept before the threshold elapses"); + TEST_ASSERT(due_off < 0, "a negative threshold disables the decay"); + + /* Proof the block really was sweepable, i.e. the assertions above were + * not vacuous: with the threshold at 0 the same block goes. */ + ray_heap_set_decay_ms(0); + ray_heap_note_activity(); + int64_t swept = ray_heap_decay(); + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + TEST_ASSERT(swept >= 1, "the same block is released once the threshold is 0"); + PASS(); +} + /* ---- ray_heap_gc oversized-pool reclamation ---------------------------- * * * Allocate a block large enough to force a pool > 32 MB (pool_order > @@ -366,8 +531,8 @@ static test_result_t test_gc_reclaim_oversized_pool(void) { static test_result_t test_heap_gc_serial(void) { /* Build up some freelist activity, then call gc. No oversized pools - * are involved; gc should still run flush_foreign + flush_slabs + - * return_foreign_freelist without crashing. */ + * are involved; gc should still run its foreign drain + slab flush + * without crashing. */ ray_t* xs[64]; for (int i = 0; i < 64; i++) { xs[i] = ray_alloc(256 + i * 8); @@ -385,13 +550,12 @@ static test_result_t test_heap_gc_serial(void) { PASS(); } -/* ---- ray_heap_gc parallel path (foreign-flush no-op) ------------------- */ +/* ---- ray_heap_gc parallel path ---------------------------------------- */ static test_result_t test_heap_gc_parallel(void) { - /* When ray_parallel_flag != 0, heap_flush_foreign(false) is a no-op - * and gc must NOT touch worker heaps' state. We only need to - * verify that calling gc with the flag set doesn't crash and the - * heap remains consistent. */ + /* When ray_parallel_flag != 0, gc must NOT touch worker heaps' state. + * We only need to verify that calling gc with the flag set doesn't + * crash and the heap remains consistent. */ ray_t* a = ray_alloc(128); TEST_ASSERT_NOT_NULL(a); @@ -405,42 +569,150 @@ static test_result_t test_heap_gc_parallel(void) { PASS(); } -/* ---- ray_heap_flush_foreign while parallel (no-op early return) -------- */ - -static test_result_t test_flush_foreign_during_parallel(void) { - /* While ray_parallel_flag is set, ray_heap_flush_foreign() must not - * touch h->foreign — proves the early return path. */ +/* ---- Cross-thread free lands on the OWNER's list ------------------------ + * + * A block freed by a thread that does not own it goes onto the OWNING heap's + * list, never the freeing heap's. That is the whole point: the owner is the + * only heap that can reuse the memory, and it picks the block up on its own + * allocation path — nothing has to call a collector. Memory parked on the + * freeing heap was what let a served query grow a server without bound + * (issue #439). */ + +static test_result_t test_free_routes_to_owner_list(void) { ray_heap_t* heap_a = ray_tl_heap; - /* Build heap_b and free a block from it on heap_a so heap_a->foreign - * is non-empty. */ ray_tl_heap = NULL; ray_heap_init(); ray_heap_t* heap_b = ray_tl_heap; TEST_ASSERT_NOT_NULL(heap_b); + TEST_ASSERT(heap_b != heap_a, "distinct heaps"); ray_t* blk = ray_alloc(0); TEST_ASSERT_NOT_NULL(blk); ray_tl_heap = heap_a; - ray_free(blk); /* cross-thread free: enqueues onto heap_a->foreign */ - /* Foreign-list model: the cross-thread free sits on the freeing heap. */ - TEST_ASSERT_NOT_NULL(heap_a->foreign); + ray_free(blk); + TEST_ASSERT_NULL(atomic_load(&heap_a->foreign)); + TEST_ASSERT_EQ_U((uintptr_t)atomic_load(&heap_b->foreign), (uintptr_t)blk); + /* Draining heap_a leaves heap_b's list alone — and needs no idle-worker + * gate any more, because a heap only ever drains its own blocks. */ ray_parallel_begin(); ray_heap_flush_foreign(); - /* Foreign list should still be intact (not flushed). */ - TEST_ASSERT_NOT_NULL(heap_a->foreign); + TEST_ASSERT_EQ_U((uintptr_t)atomic_load(&heap_b->foreign), (uintptr_t)blk); ray_parallel_end(); - /* parallel_end -> ray_heap_gc which DOES flush foreign now safe. */ - /* Foreign list should be empty after end. */ - TEST_ASSERT_NULL(heap_a->foreign); + TEST_ASSERT_EQ_U((uintptr_t)atomic_load(&heap_b->foreign), (uintptr_t)blk); + + /* The owner takes it back. */ + ray_tl_heap = heap_b; + ray_heap_flush_foreign(); + TEST_ASSERT_NULL(atomic_load(&heap_b->foreign)); + ray_heap_destroy(); + ray_tl_heap = heap_a; + PASS(); +} + +/* ---- A cross-thread free cycle must not grow the owner's pools ---------- + * + * The regression for issue #439. Workers allocate per-group temporaries from + * their own heaps and the thread consuming the result frees them; before this + * change those blocks stayed on the consumer and only an explicit + * ray_heap_gc() ever moved them, so the owner started every round short by + * the volume the consumer was holding and mapped a fresh 32 MB pool to make + * up the difference — once per execution, until RAY_MAX_POOLS turned it into + * an OOM. Cycle far more bytes through the owner than one pool holds, + * always freeing from the other heap and never calling a collector: the + * owner's pool count must not move. */ + +static test_result_t test_cross_heap_cycle_bounds_pools(void) { + enum { WARMUP = 32, ROUNDS = 128, BLOCK = 1u << 20 }; /* 1 MB blocks */ + ray_heap_t* heap_a = ray_tl_heap; + + ray_tl_heap = NULL; + ray_heap_init(); + ray_heap_t* heap_b = ray_tl_heap; + TEST_ASSERT_NOT_NULL(heap_b); + + /* Warm-up: let heap_b map whatever pools its steady state needs. */ + for (int i = 0; i < WARMUP; i++) { + ray_tl_heap = heap_b; + ray_t* v = ray_alloc(BLOCK); + TEST_ASSERT_NOT_NULL(v); + ray_tl_heap = heap_a; + ray_free(v); + } + ray_tl_heap = heap_b; + uint32_t pools_before = heap_b->pool_count; + TEST_ASSERT((pools_before) > (0), "heap_b mapped a pool"); + + /* 128 MB more through a heap whose pools are 32 MB. */ + bool saw_queued = false; + for (int i = 0; i < ROUNDS; i++) { + ray_tl_heap = heap_b; + ray_t* v = ray_alloc(BLOCK); + TEST_ASSERT_NOT_NULL(v); + ray_tl_heap = heap_a; + ray_free(v); + if (atomic_load(&heap_b->foreign) != NULL) saw_queued = true; + } ray_tl_heap = heap_b; + + /* Guards the assertion below against passing vacuously: if the frees had + * never reached heap_b's list there would be nothing for it to take back + * and no reuse to prove. */ + TEST_ASSERT(saw_queued, "frees reached the owner's list"); + TEST_ASSERT_EQ_U(heap_b->pool_count, pools_before); + TEST_ASSERT_NULL(atomic_load(&heap_a->foreign)); + ray_heap_destroy(); ray_tl_heap = heap_a; PASS(); } +/* ---- A thread's heap outlives the thread ------------------------------- + * + * ray_free resolves the owning heap through ray_heap_registry and pushes the + * block onto it WITHOUT a lock. That is only sound while a registered heap + * outlives every block it owns, so a thread that exits abandons its heap — + * still registered, pools intact — instead of unregistering and munmapping + * it underneath a lookup already in flight. The next thread up adopts it. */ + +static test_result_t test_heap_abandon_is_adopted(void) { + ray_heap_t* heap_a = ray_tl_heap; + + ray_tl_heap = NULL; + ray_heap_init(); + ray_heap_t* heap_b = ray_tl_heap; + TEST_ASSERT_NOT_NULL(heap_b); + ray_t* blk = ray_alloc(4096); + TEST_ASSERT_NOT_NULL(blk); + uint16_t bid = heap_b->id; + uint32_t bpools = heap_b->pool_count; + TEST_ASSERT((bpools) > (0), "heap_b mapped a pool"); + + ray_heap_abandon(); + TEST_ASSERT_NULL(ray_tl_heap); + TEST_ASSERT_EQ_U((uintptr_t)ray_heap_registry[bid % RAY_HEAP_REGISTRY_SIZE], + (uintptr_t)heap_b); + /* The pool is still mapped and still names heap_b as its owner. */ + TEST_ASSERT_EQ_U(ray_pool_of(blk)->heap_id, bid); + + /* A block of the abandoned heap, freed from elsewhere, still finds it. */ + ray_tl_heap = heap_a; + ray_free(blk); + TEST_ASSERT_EQ_U((uintptr_t)atomic_load(&heap_b->foreign), (uintptr_t)blk); + + /* The next thread adopts it rather than mapping a new one. */ + ray_tl_heap = NULL; + ray_heap_init(); + TEST_ASSERT_EQ_U((uintptr_t)ray_tl_heap, (uintptr_t)heap_b); + TEST_ASSERT_EQ_U(ray_tl_heap->pool_count, bpools); + + ray_heap_destroy(); /* real teardown — no thread owns heap_b now */ + ray_tl_heap = heap_a; + PASS(); +} + /* ---- Owned-ref retain/release: LIST containing children ---------------- * * * ray_alloc_copy on a RAY_LIST exercises the LIST branch of both @@ -736,14 +1008,14 @@ static test_result_t test_merge_with_slabs_and_freelist(void) { uint32_t heap_b_pools = heap_b->pool_count; TEST_ASSERT((heap_b_pools) > (0), "heap_b_pools > 0"); - /* Drive a foreign block into heap_b->foreign by allocating on - * heap_a and freeing while heap_b is current. */ - ray_tl_heap = heap_a; + /* Drive a block onto heap_b->foreign: allocate it on heap_b and free it + * while heap_a is current — a cross-thread free goes to the owner. */ + ray_tl_heap = heap_b; ray_t* fblk = ray_alloc(0); TEST_ASSERT_NOT_NULL(fblk); - ray_tl_heap = heap_b; - ray_free(fblk); /* heap_b->foreign now contains fblk (foreign-list model) */ - TEST_ASSERT_NOT_NULL(heap_b->foreign); + ray_tl_heap = heap_a; + ray_free(fblk); + TEST_ASSERT_NOT_NULL(atomic_load(&heap_b->foreign)); /* Capture pool count AFTER any allocs heap_a has performed for fblk — * lazy heap_add_pool may have grown the count. */ @@ -1110,21 +1382,20 @@ static test_result_t test_release_lambda_owned_refs(void) { PASS(); } -/* ---- heap_flush_foreign "owner gone" branch ------------------------------- +/* ---- Cross-thread free with the owner unregistered ------------------------ * - * Allocate on heap_b, then destroy heap_b (unregisters it). Free the - * block while on heap_a — it lands in heap_a->foreign with a pool header - * whose heap_id no longer maps to a live heap. Calling ray_heap_gc() with - * return_to_owner=true triggers heap_flush_foreign which hits the "owner - * gone" else-branch and coalesces the block locally onto heap_a. + * If the owning heap is not in the registry its pools went with it, so there + * is nowhere to hand the block back to. The free must drop it — and in + * particular must NOT park it on the freeing heap, which cannot reuse + * another heap's memory and would only be accumulating it. * * NOTE: heap_b must NOT be destroyed via ray_heap_destroy (that munmaps its * pools). Instead we manually unregister it from the global registry so - * its pool remains mapped (and addressable) while the foreign-block walk - * proceeds. We then push_pending the hollow heap_b to let drain_pending - * transfer ownership properly and avoid leaking address space. */ + * its pool remains mapped (and the block addressable) for the assertions. + * We then push_pending the hollow heap_b to let drain_pending transfer + * ownership properly and avoid leaking address space. */ -static test_result_t test_flush_foreign_owner_gone(void) { +static test_result_t test_free_owner_unregistered(void) { ray_heap_t* heap_a = ray_tl_heap; TEST_ASSERT_NOT_NULL(heap_a); @@ -1138,21 +1409,23 @@ static test_result_t test_flush_foreign_owner_gone(void) { TEST_ASSERT_NOT_NULL(blk); /* Unregister heap_b from the global registry so it looks "gone" - * without munmapping its pool (the pool must stay valid for the - * owner-lookup walk). */ + * without munmapping its pool. */ uint16_t bid = heap_b->id; ray_heap_registry[bid % RAY_HEAP_REGISTRY_SIZE] = NULL; - /* Switch to heap_a and free blk — it goes onto heap_a->foreign because - * phdr->heap_id == bid which != heap_a->id. */ + /* Free blk from heap_a. The owner lookup on phdr->heap_id == bid finds + * nothing, and an unregistered heap is indistinguishable from one merely + * waiting to be merged — whose pools are still mapped. So the block is + * kept on the freeing heap's own list rather than dropped: dropping it + * would strand it and pin its pool against reclamation for good. */ ray_tl_heap = heap_a; ray_free(blk); - TEST_ASSERT_NOT_NULL(heap_a->foreign); + TEST_ASSERT_NOT_NULL(atomic_load(&heap_a->foreign)); + TEST_ASSERT_NULL(atomic_load(&heap_b->foreign)); - /* GC with safe=true triggers heap_flush_foreign(h, true). - * Owner lookup returns NULL → "owner gone" else-branch. */ + /* The drain adopts it against its own pool header. */ ray_heap_gc(); - TEST_ASSERT_NULL(heap_a->foreign); + TEST_ASSERT_NULL(atomic_load(&heap_a->foreign)); /* Re-register heap_b and clean up via push_pending/drain_pending so * its pools are properly transferred and no address space leaks. */ @@ -1221,30 +1494,15 @@ static test_result_t test_merge_slab_overflow(void) { PASS(); } -/* ---- heap_return_foreign_freelist path ------------------------------------ - * - * After ray_heap_merge, heap_a owns all of heap_b's pools. But the pool - * table of heap_b (now freed) tracked those pools. Allocating on the merged - * heap and freeing on a third heap inserts blocks with heap_b's (now - * heap_a's) heap_id into heap_c's freelists. GC on heap_c then calls - * heap_return_foreign_freelist which returns those blocks to heap_a. +/* ---- GC over a heap that absorbed another one's pools --------------------- * - * Simpler route that does NOT require a 3rd heap: after merging heap_b into - * heap_a, coalesce puts blocks back on heap_a's freelist — those blocks' - * pool_order matches heap_a's pools. heap_return_foreign_freelist walks - * heap_a's freelists; blocks that ARE in heap_a's pool table are local - * (pidx >= 0) and the inner if(pidx < 0) branch is skipped. To reach - * pidx < 0 we need a freelist entry whose pool is not in pool[]. - * - * Pragmatic approach: add enough blocks to freelist and call GC; even if - * the foreign-freelist inner body isn't hit, we still cover the outer loop - * and the pidx >= 0 early-continue path (which currently has 0 coverage). */ - -static test_result_t test_gc_return_foreign_freelist(void) { - /* Build heap_b, populate it, merge into heap_a, then run GC. - * heap_return_foreign_freelist walks freelists of heap_a and checks - * ownership of each block. At minimum, the outer for loop and the - * heap_find_pool call are covered. */ + * ray_heap_merge splices src's freelists into dst and transfers its pool + * entries. Run GC on the merged heap: every pass has to cope with freelist + * entries whose pool arrived from somewhere else, and with the pool table + * having grown underneath the avail bitmap. */ + +static test_result_t test_gc_after_merge(void) { + /* Build heap_b, populate it, merge into heap_a, then run GC. */ ray_heap_t* heap_a = ray_tl_heap; ray_tl_heap = NULL; @@ -1508,10 +1766,12 @@ static test_result_t test_merge_foreign_pool_fallback(void) { TEST_ASSERT_NOT_NULL(cblk); /* Manually enqueue cblk onto heap_b->foreign. - * heap_b doesn't own any of heap_c's pools. */ + * heap_b doesn't own any of heap_c's pools — a real cross-thread free + * would route the block to heap_c, so this shape has to be built by + * hand to reach the merge fallback. */ ray_tl_heap = heap_b; - cblk->fl_next = heap_b->foreign; - heap_b->foreign = cblk; + cblk->fl_next = NULL; + atomic_store(&heap_b->foreign, cblk); /* Now merge heap_b into heap_a. heap_a also doesn't know about * heap_c's pool, so heap_find_pool(heap_a, cblk) returns -1 → phdr. */ @@ -2421,11 +2681,14 @@ const test_entry_t heap_entries[] = { { "heap/scratch_arena_basic", test_scratch_arena_basic, heap_setup, heap_teardown }, { "heap/scratch_arena_multi", test_scratch_arena_multi_backing, heap_setup, heap_teardown }, { "heap/scratch_arena_oversize", test_scratch_arena_oversize, heap_setup, heap_teardown }, + { "heap/scratch_arena_direct", test_scratch_arena_direct_backing, heap_setup, heap_teardown }, { "heap/release_pages", test_release_pages, heap_setup, heap_teardown }, { "heap/gc_reclaim_oversized", test_gc_reclaim_oversized_pool, heap_setup, heap_teardown }, { "heap/gc_serial", test_heap_gc_serial, heap_setup, heap_teardown }, { "heap/gc_parallel", test_heap_gc_parallel, heap_setup, heap_teardown }, - { "heap/flush_foreign_parallel", test_flush_foreign_during_parallel, heap_setup, heap_teardown }, + { "heap/free_routes_to_owner", test_free_routes_to_owner_list, heap_setup, heap_teardown }, + { "heap/cross_heap_cycle_bounds", test_cross_heap_cycle_bounds_pools, heap_setup, heap_teardown }, + { "heap/abandon_is_adopted", test_heap_abandon_is_adopted, heap_setup, heap_teardown }, { "heap/alloc_copy_list", test_alloc_copy_list_retains, heap_setup, heap_teardown }, { "heap/str_pool_owned_ref", test_str_pool_owned_ref, heap_setup, heap_teardown }, { "heap/sentinel_null_release", test_sentinel_null_release, heap_setup, heap_teardown }, @@ -2445,9 +2708,9 @@ const test_entry_t heap_entries[] = { { "heap/scratch_realloc_mapcommon",test_scratch_realloc_mapcommon, heap_setup, heap_teardown }, { "heap/alloc_copy_dict", test_alloc_copy_dict_block, heap_setup, heap_teardown }, { "heap/release_lambda_owned_refs", test_release_lambda_owned_refs, heap_setup, heap_teardown }, - { "heap/flush_foreign_owner_gone", test_flush_foreign_owner_gone, heap_setup, heap_teardown }, + { "heap/free_owner_unregistered", test_free_owner_unregistered, heap_setup, heap_teardown }, { "heap/merge_slab_overflow", test_merge_slab_overflow, heap_setup, heap_teardown }, - { "heap/gc_return_foreign_fl", test_gc_return_foreign_freelist, heap_setup, heap_teardown }, + { "heap/gc_after_merge", test_gc_after_merge, heap_setup, heap_teardown }, { "heap/free_mmod1_atom", test_free_mmod1_atom, heap_setup, heap_teardown }, { "heap/order_for_size_pow2", test_order_for_size_pow2, heap_setup, heap_teardown }, { "heap/scratch_realloc_slice", test_scratch_realloc_slice, heap_setup, heap_teardown }, @@ -2483,5 +2746,7 @@ const test_entry_t heap_entries[] = { { "heap/retain_atom_obj", test_retain_owned_refs_atom_obj, heap_setup, heap_teardown }, { "heap/scratch_realloc_lazy", test_scratch_realloc_lazy_handle, heap_setup, heap_teardown }, { "heap/scratch_realloc_has_index", test_scratch_realloc_has_index_detach, heap_setup, heap_teardown }, + { "heap/idle_decay_releases", test_idle_decay_releases_pages, heap_setup, heap_teardown }, + { "heap/idle_decay_threshold", test_idle_decay_respects_threshold, heap_setup, heap_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_idx_route.c b/test/test_idx_route.c index ed205f804..7c8f5c5ad 100644 --- a/test/test_idx_route.c +++ b/test/test_idx_route.c @@ -2168,13 +2168,15 @@ static test_result_t test_distinct_f64_nan_no_null_attr(void) { ray_heap_init(); (void)ray_sym_init(); - /* Three rows of canonical NaN, no HAS_NULLS flag. */ + /* Three rows of canonical NaN, no HAS_NULLS flag. from_raw flags + * sentinel NaNs (#445), so strip the attr deliberately — this test pins + * distinct's behavior on an unflagged (legacy / flag-dropped) vector. */ double nan_val = __builtin_nan(""); double raw[5] = { 1.0, nan_val, nan_val, nan_val, 2.0 }; ray_t* v_no_idx = ray_vec_from_raw(RAY_F64, raw, 5); TEST_ASSERT_FALSE(RAY_IS_ERR(v_no_idx)); - /* Confirm HAS_NULLS is NOT set */ - TEST_ASSERT((v_no_idx->attrs & 0x40) == 0, "HAS_NULLS must not be set on raw-constructed vector"); + v_no_idx->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + TEST_ASSERT((v_no_idx->attrs & 0x40) == 0, "HAS_NULLS stripped for the unflagged-sentinel path"); ray_t* r_no_idx = distinct_vec_eager(v_no_idx); TEST_ASSERT_FALSE(RAY_IS_ERR(r_no_idx)); @@ -2182,6 +2184,7 @@ static test_result_t test_distinct_f64_nan_no_null_attr(void) { ray_t* v_idx = ray_vec_from_raw(RAY_F64, raw, 5); TEST_ASSERT_FALSE(RAY_IS_ERR(v_idx)); + v_idx->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_sort(&v_idx))); ray_t* r_idx = distinct_vec_eager(v_idx); diff --git a/test/test_ipc.c b/test/test_ipc.c index 1d7c7dd97..20e2e9b01 100644 --- a/test/test_ipc.c +++ b/test/test_ipc.c @@ -165,6 +165,27 @@ static void sleep_ms(long ms) { nanosleep(&ts, NULL); } +/* ---- bind address (#427) ------------------------------------------------- */ + +/* A listener confined to loopback binds and accepts a loopback connect; + * an unparseable host is a loud io failure, never a silent INADDR_ANY. */ +static test_result_t test_ipc_listen_bind_addr(void) { + ray_ipc_server_t srv; + TEST_ASSERT_EQ_I(ray_ipc_server_init_at(&srv, "127.0.0.1", 0), RAY_OK); + uint16_t port = get_listen_port(srv.listen_fd); + TEST_ASSERT(port > 0, "port > 0"); + ray_ipc_server_destroy(&srv); + + /* NULL host keeps the historical all-interfaces bind. */ + TEST_ASSERT_EQ_I(ray_ipc_server_init_at(&srv, NULL, 0), RAY_OK); + ray_ipc_server_destroy(&srv); + + ray_ipc_server_t bad; + TEST_ASSERT_EQ_I(ray_ipc_server_init_at(&bad, "not-an-address", 0), RAY_ERR_IO); + TEST_ASSERT_EQ_I(ray_ipc_server_init_at(&bad, "999.9.9.9", 0), RAY_ERR_IO); + PASS(); +} + /* ---- test_ipc_send_verbose ----------------------------------------------- */ /* * Exercise ray_ipc_send_verbose — covers the entire function (lines 1212-1274) @@ -2119,6 +2140,7 @@ static test_result_t test_ipc_server_push(void) { /* ---- Registry ------------------------------------------------------------ */ const test_entry_t ipc_entries[] = { + { "ipc/listen_bind_addr", test_ipc_listen_bind_addr, ipc_setup, ipc_teardown }, { "ipc/send_verbose", test_ipc_send_verbose, ipc_setup, ipc_teardown }, { "ipc/send_verbose_captures", test_ipc_send_verbose_captures_output, ipc_setup, ipc_teardown }, { "ipc/eval_non_string_msg", test_ipc_eval_non_string_msg, ipc_setup, ipc_teardown }, diff --git a/test/test_join_buildside.c b/test/test_join_buildside.c index 0cc93a3c0..30ebccaf6 100644 --- a/test/test_join_buildside.c +++ b/test/test_join_buildside.c @@ -928,6 +928,61 @@ static test_result_t test_jb_trip_boundary(void) { return rr; } +/* ── Null-run upfront fallback (#458) ────────────────────────────────────── + * Every null key cell hashes to one canonical value, so >RADIX_DUP_RUN_MAX + * build-side nulls used to START the radix build and then discard it on the + * dup-run abort. Now the null count routes the join to the chained path + * upfront: the null-fallback counter advances, the dup-abort counter does + * NOT (nothing was built and thrown away), and the answer still matches the + * forced-chained oracle — nulls pairing with nulls included. + * ──────────────────────────────────────────────────────────────────────── */ +static test_result_t test_jb_null_run_upfront_fallback(void) { + ray_heap_init(); + (void)ray_sym_init(); + + int64_t n_r = RAY_PARALLEL_THRESHOLD + 5000; + int64_t n_l = 4000; + int64_t* rv = malloc((size_t)n_r * sizeof(int64_t)); + int64_t* lv = malloc((size_t)n_l * sizeof(int64_t)); + TEST_ASSERT(rv && lv, "malloc key arrays"); + + /* Build side: low per-key duplication (~35/key, below the dup trip) plus + * 600 nulls — above RADIX_DUP_RUN_MAX, so only the null gate can fire. + * Probe side: a couple of nulls to exercise null==null output. */ + for (int64_t i = 0; i < n_r; i++) rv[i] = (i % 100 == 0 && i < 60000) ? NULL_I64 : i % 2000; + for (int64_t i = 0; i < n_l; i++) lv[i] = (i == 7 || i == 4001 - 2000) ? NULL_I64 : i % 2000; + + ray_join_no_build_swap = true; /* build = right */ + + uint64_t null_before = ray_join_null_fallbacks; + uint64_t dup_before = ray_join_dup_fallbacks; + ray_t* rt = jb_table1("rk", rv, n_r); + ray_t* lt = jb_table1("lk", lv, n_l); + test_result_t rr = jb_diff_dup(lt, "lk", rt, "rk", /*join_type=*/0, /*expect_trip=*/false); + if (rr.status == TEST_PASS && ray_join_null_fallbacks == null_before) + rr = (test_result_t){ TEST_FAIL, "expected the null-run upfront fallback to fire" }; + if (rr.status == TEST_PASS && ray_join_dup_fallbacks != dup_before) + rr = (test_result_t){ TEST_FAIL, "dup-run abort fired — radix work was built and discarded" }; + ray_release(lt); ray_release(rt); + + /* Few nulls (< RADIX_DUP_RUN_MAX): the gate must NOT fire. */ + if (rr.status == TEST_PASS) { + for (int64_t i = 0; i < n_r; i++) rv[i] = (i < 100) ? NULL_I64 : i % 2000; + uint64_t nb2 = ray_join_null_fallbacks; + ray_t* rt2 = jb_table1("rk", rv, n_r); + ray_t* lt2 = jb_table1("lk", lv, n_l); + rr = jb_diff_dup(lt2, "lk", rt2, "rk", /*join_type=*/0, /*expect_trip=*/false); + if (rr.status == TEST_PASS && ray_join_null_fallbacks != nb2) + rr = (test_result_t){ TEST_FAIL, "null gate fired below its threshold" }; + ray_release(lt2); ray_release(rt2); + } + + ray_join_no_build_swap = false; /* reset */ + free(lv); free(rv); + ray_sym_destroy(); ray_heap_destroy(); + return rr; +} + /* ── Not sticky ──────────────────────────────────────────────────────────── * The pathological flag is per-join (reset each exec_join), not a sticky * global. Run a tripping join then a non-tripping join in the SAME heap @@ -1037,5 +1092,6 @@ const test_entry_t join_buildside_entries[] = { { "join_buildside/trip_boundary", test_jb_trip_boundary, NULL, NULL }, { "join_buildside/not_sticky", test_jb_not_sticky, NULL, NULL }, { "join_buildside/mixed_type_radix", test_jb_mixed_type_radix, NULL, NULL }, + { "join_buildside/null_run_upfront_fallback", test_jb_null_run_upfront_fallback, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_journal.c b/test/test_journal.c index b5caa67cc..bd956828c 100644 --- a/test/test_journal.c +++ b/test/test_journal.c @@ -40,6 +40,7 @@ #include #include #include +#include /* ── Runtime fixture (same pattern as test_link.c) ─────────────────── */ @@ -997,6 +998,91 @@ static test_result_t test_journal_snapshot_when_closed(void) { PASS(); } +/* #420: a crash between the .qdb rename and the log roll leaves the + * fresh snapshot next to the OLD log whose entries it already contains. + * Recovery must not apply those entries a second time — and when more + * entries land on that log afterwards (the failed-roll append path), + * recovery must replay exactly the tail. */ +static test_result_t test_journal_crash_window_no_double_apply(void) { + char base[256]; make_base(base, sizeof(base), "cwin"); + char lpath[270]; log_path(lpath, sizeof(lpath), base); + + /* Session 1: journal an increment (non-idempotent on purpose) and + * apply it once, exactly like the IPC eval+log path. */ + char src[640]; + snprintf(src, sizeof(src), + "(set jw_x 0)" + "(.log.open 'async \"%s\")" + "(.log.write (quote (set jw_x (+ jw_x 1))))" + "(set jw_x (+ jw_x 1))", + base); + ray_t* a = ray_eval_str(src); + TEST_ASSERT_NOT_NULL(a); + TEST_ASSERT_FALSE(RAY_IS_ERR(a)); + if (a != RAY_NULL_OBJ) ray_release(a); + + /* Value the snapshot will hold. */ + ray_t* pre = ray_eval_str("jw_x"); + TEST_ASSERT_FALSE(RAY_IS_ERR(pre)); + int64_t v_pre = pre->i64; + ray_release(pre); + + /* Snapshot: writes .qdb (with the coverage marker), then rolls. */ + TEST_ASSERT_EQ_I(ray_journal_snapshot(), RAY_OK); + + /* Simulate the crash IN the window: put the just-archived log back + * under its live name, exactly the on-disk state a crash between + * the two renames leaves behind. */ + char pattern[300]; + snprintf(pattern, sizeof(pattern), "%s.*.log", base); + glob_t g; + TEST_ASSERT_EQ_I(glob(pattern, 0, NULL, &g), 0); + TEST_ASSERT_EQ_I((int64_t)g.gl_pathc, 1); + TEST_ASSERT_EQ_I(rename(g.gl_pathv[0], lpath), 0); + globfree(&g); + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + + /* Restart: clobber the binding, recover. The covered log must be + * skipped — jw_x comes back as the snapshot value, not value+1. */ + ray_t* c = ray_eval_str("(set jw_x 100)"); + if (c && !RAY_IS_ERR(c)) ray_release(c); + TEST_ASSERT_EQ_I(ray_journal_recover(base), RAY_OK); + ray_t* r1 = ray_eval_str("jw_x"); + TEST_ASSERT_FALSE(RAY_IS_ERR(r1)); + TEST_ASSERT_EQ_I(r1->i64, v_pre); + ray_release(r1); + + /* Failed-roll append path: more entries land on the covered log. + * Recovery must replay exactly that tail on top of the snapshot. */ + char more[640]; + snprintf(more, sizeof(more), + "(.log.open 'async \"%s\")" + "(.log.write (quote (set jw_x (+ jw_x 1))))" + "(.log.close)", + base); + ray_t* m = ray_eval_str(more); + TEST_ASSERT_NOT_NULL(m); + TEST_ASSERT_FALSE(RAY_IS_ERR(m)); + if (m != RAY_NULL_OBJ) ray_release(m); + + ray_t* c2 = ray_eval_str("(set jw_x 100)"); + if (c2 && !RAY_IS_ERR(c2)) ray_release(c2); + TEST_ASSERT_EQ_I(ray_journal_recover(base), RAY_OK); + ray_t* r2 = ray_eval_str("jw_x"); + TEST_ASSERT_FALSE(RAY_IS_ERR(r2)); + TEST_ASSERT_EQ_I(r2->i64, v_pre + 1); + ray_release(r2); + + /* The marker key must not leak into the env as a global. */ + ray_t* leak = ray_eval_str(".journal.covered"); + TEST_ASSERT_TRUE(!leak || RAY_IS_ERR(leak)); + if (leak && RAY_IS_ERR(leak)) ray_error_free(leak); + else if (leak && leak != RAY_NULL_OBJ) ray_release(leak); + + cleanup_base(base); + PASS(); +} + /* 7b. snapshot with bindings -> creates .qdb and rolls log. */ static test_result_t test_journal_snapshot_basic(void) { char base[256]; make_base(base, sizeof(base), "snap_basic"); @@ -1616,14 +1702,12 @@ static test_result_t test_journal_snapshot_rename_fails(void) { } /* ═══════════════════════════════════════════════════════════════════════ - * 20. Snapshot: .qdb dict with more keys than values (missing-val path). + * 20. Snapshot: .qdb dict cannot be built with more keys than values. * ═══════════════════════════════════════════════════════════════════════ */ static test_result_t test_journal_open_qdb_missing_val(void) { - char base[256]; make_base(base, sizeof(base), "oc_qdbmissing"); - char qpath[270]; qdb_path(qpath, sizeof(qpath), base); - - /* Build a dict: 2 sym keys, 1 value — second key has no corresponding val. */ + /* Build a dict: 2 sym keys, 1 value. Public construction rejects this + * before it can become a partially-loaded snapshot. */ int64_t s1 = ray_sym_intern("jrn_k1", 6); int64_t s2 = ray_sym_intern("jrn_k2", 6); ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 2); @@ -1638,24 +1722,10 @@ static test_result_t test_journal_open_qdb_missing_val(void) { ray_t* d = ray_dict_new(keys, vals); TEST_ASSERT_NOT_NULL(d); - TEST_ASSERT_FALSE(RAY_IS_ERR(d)); - - ray_err_t se = ray_obj_save(d, qpath); - ray_release(d); - TEST_ASSERT_EQ_I(se, RAY_OK); - - /* Open: should warn about missing val for sym jrn_k2, but succeed. */ - ray_err_t e = ray_journal_open(base, RAY_JOURNAL_ASYNC); - /* Partial load — bind_errs == 0 (we skipped, not failed), so OK. */ - if (e == RAY_OK) { - TEST_ASSERT_TRUE(ray_journal_is_open()); - TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); - } else { - /* If open returned domain, still OK for test purposes. */ - TEST_ASSERT_FALSE(ray_journal_is_open()); - } + TEST_ASSERT_TRUE(RAY_IS_ERR(d)); + TEST_ASSERT_STR_EQ(ray_err_code(d), "domain"); + ray_error_free(d); - cleanup_base(base); PASS(); } @@ -2348,5 +2418,7 @@ const test_entry_t journal_entries[] = { { "journal/purge_full", test_journal_purge_full, jrn_setup, jrn_teardown }, { "journal/purge_after_close", test_journal_purge_after_close, jrn_setup, jrn_teardown }, { "journal/purge_ops_wrapper", test_journal_purge_ops_wrapper, jrn_setup, jrn_teardown }, + /* #420: snapshot/roll crash window must not double-apply */ + { "journal/crash_window_no_double_apply", test_journal_crash_window_no_double_apply, jrn_setup, jrn_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_lang.c b/test/test_lang.c index b1272946e..c5dc22c30 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -870,6 +870,31 @@ static test_result_t test_eval_in(void) { PASS(); } +/* ---- Test: GUID OP_NOT_IN preserves null semantics ---------------------- */ +static test_result_t test_eval_select_where_in_guid_nulls(void) { + ray_t* table = ray_eval_str( + "(do (set g (guid 2)) " + "(set probe (as 'guid \"00000000-0000-0000-0000-000000000000\")) " + "(set t (table ['g 'v] (list g [10 20]))) t)"); + TEST_ASSERT_NOT_NULL(table); + TEST_ASSERT_FALSE(RAY_IS_ERR(table)); + + ray_t* col = ray_table_get_col(table, ray_sym_intern("g", 1)); + TEST_ASSERT_NOT_NULL(col); + TEST_ASSERT_EQ_I(col->type, RAY_GUID); + ray_vec_set_null(col, 0, true); + + ray_t* result = ray_eval_str( + "(select {from: t where: (not-in g probe)})"); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), 1); + + ray_release(result); + ray_release(table); + PASS(); +} + /* ---- Test: except ---- */ static test_result_t test_eval_except(void) { ray_t* result = ray_eval_str("(except [1 2 3] [2])"); @@ -8907,6 +8932,7 @@ const test_entry_t lang_entries[] = { { "lang/eval/apply", test_eval_apply, lang_setup, lang_teardown }, { "lang/eval/distinct", test_eval_distinct, lang_setup, lang_teardown }, { "lang/eval/in", test_eval_in, lang_setup, lang_teardown }, + { "lang/eval/select_where_in_guid_nulls", test_eval_select_where_in_guid_nulls, lang_setup, lang_teardown }, { "lang/eval/except", test_eval_except, lang_setup, lang_teardown }, { "lang/eval/union", test_eval_union, lang_setup, lang_teardown }, { "lang/eval/sect", test_eval_sect, lang_setup, lang_teardown }, diff --git a/test/test_public_api.c b/test/test_public_api.c index 13a40768c..af8201e72 100644 --- a/test/test_public_api.c +++ b/test/test_public_api.c @@ -661,12 +661,13 @@ static test_result_t test_public_nullability_matrix(void) { ray_typed_null(-RAY_U8), ray_typed_null(-RAY_F32), }; - const bool requested_is_null[] = { false, false, true, true, true }; + const bool ordinary_is_null[] = { true, true, false, false, false }; + const bool requested_is_null[] = { true, true, true, true, true }; for (size_t i = 0; i < sizeof(ordinary) / sizeof(ordinary[0]); i++) { TEST_ASSERT_NOT_NULL(ordinary[i]); TEST_ASSERT_FALSE(RAY_IS_ERR(ordinary[i])); - TEST_ASSERT_FALSE(RAY_ATOM_IS_NULL(ordinary[i])); + TEST_ASSERT_EQ_I(RAY_ATOM_IS_NULL(ordinary[i]), ordinary_is_null[i]); TEST_ASSERT_NOT_NULL(requested_null[i]); TEST_ASSERT_FALSE(RAY_IS_ERR(requested_null[i])); TEST_ASSERT_EQ_I(RAY_ATOM_IS_NULL(requested_null[i]), requested_is_null[i]); diff --git a/test/test_splay.c b/test/test_splay.c index 3ce7ae1fa..1137cbbd0 100644 --- a/test/test_splay.c +++ b/test/test_splay.c @@ -26,7 +26,7 @@ /* * test_splay.c — focused tests for src/store/splay.c paths not covered by * test_store.c. Targets: validate_sym_columns (empty sym table + I64 table, - * and RAY_SYM column detect), ray_splay_save bad-column-name skip, NULL-dir + * and RAY_SYM column detect), ray_splay_save unsafe-name rejection, NULL-dir * error paths, missing .d schema, corrupt schema (bad name_id), and * splay_load_impl range/corrupt/io error branches. */ @@ -101,82 +101,57 @@ static test_result_t test_save_null_tbl(void) { } /* ========================================================================= - * 3. ray_splay_save: column name starting with '.' is skipped silently. - * Verify: save succeeds, but the column file is NOT on disk. + * 3. ray_splay_save: unsafe column names are rejected before writing. * ========================================================================= */ -static test_result_t test_save_skips_dot_col_name(void) { - const char* dir = TMP_SPLAY_BASE "/dot_col"; +static test_result_t assert_save_rejects_unsafe_col_name(const char* dir, + const char* bad_name, + size_t bad_name_len) { rm_rf(dir); - /* Intern a name that starts with '.' */ - int64_t id_dot = ray_sym_intern(".hidden", 7); + int64_t id_bad = ray_sym_intern(bad_name, bad_name_len); int64_t id_ok = ray_sym_intern("good", 4); int64_t raw[] = {10, 20}; - ray_t* col_dot = ray_vec_from_raw(RAY_I64, raw, 2); - ray_t* col_ok = ray_vec_from_raw(RAY_I64, raw, 2); - TEST_ASSERT_NOT_NULL(col_dot); + ray_t* col_bad = ray_vec_from_raw(RAY_I64, raw, 2); + ray_t* col_ok = ray_vec_from_raw(RAY_I64, raw, 2); + TEST_ASSERT_NOT_NULL(col_bad); TEST_ASSERT_NOT_NULL(col_ok); ray_t* tbl = ray_table_new(3); - tbl = ray_table_add_col(tbl, id_ok, col_ok); - tbl = ray_table_add_col(tbl, id_dot, col_dot); + tbl = ray_table_add_col(tbl, id_ok, col_ok); + tbl = ray_table_add_col(tbl, id_bad, col_bad); TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); ray_err_t err = ray_splay_save(tbl, dir, NULL); - TEST_ASSERT_EQ_I(err, RAY_OK); - - /* ".hidden" column file must NOT exist */ - char bad_path[512]; - snprintf(bad_path, sizeof(bad_path), "%s/.hidden", dir); - TEST_ASSERT_EQ_I(access(bad_path, F_OK), -1); + TEST_ASSERT_EQ_I(err, RAY_ERR_DOMAIN); + TEST_ASSERT_EQ_I(access(dir, F_OK), -1); - /* "good" column file must exist */ - char good_path[512]; - snprintf(good_path, sizeof(good_path), "%s/good", dir); - TEST_ASSERT_EQ_I(access(good_path, F_OK), 0); - - ray_release(col_dot); + ray_release(col_bad); ray_release(col_ok); ray_release(tbl); rm_rf(dir); PASS(); } -/* ========================================================================= - * 4. ray_splay_save: column name containing '/' is skipped silently. - * ========================================================================= */ -static test_result_t test_save_skips_slash_col_name(void) { - const char* dir = TMP_SPLAY_BASE "/slash_col"; - rm_rf(dir); - - int64_t id_slash = ray_sym_intern("a/b", 3); - int64_t id_ok = ray_sym_intern("val", 3); - - int64_t raw[] = {1, 2}; - ray_t* col_slash = ray_vec_from_raw(RAY_I64, raw, 2); - ray_t* col_ok = ray_vec_from_raw(RAY_I64, raw, 2); - TEST_ASSERT_NOT_NULL(col_slash); - TEST_ASSERT_NOT_NULL(col_ok); - - ray_t* tbl = ray_table_new(3); - tbl = ray_table_add_col(tbl, id_ok, col_ok); - tbl = ray_table_add_col(tbl, id_slash, col_slash); - TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); +static test_result_t test_save_rejects_dot_col_name(void) { + return assert_save_rejects_unsafe_col_name( + TMP_SPLAY_BASE "/dot_col", ".hidden", 7); +} - ray_err_t err = ray_splay_save(tbl, dir, NULL); - TEST_ASSERT_EQ_I(err, RAY_OK); +static test_result_t test_save_rejects_slash_col_name(void) { + return assert_save_rejects_unsafe_col_name( + TMP_SPLAY_BASE "/slash_col", "a/b", 3); +} - /* "a/b" file must NOT exist (path traversal would create subdirs) */ - char bad_path[512]; - snprintf(bad_path, sizeof(bad_path), "%s/a", dir); - TEST_ASSERT_EQ_I(access(bad_path, F_OK), -1); +static test_result_t test_save_rejects_backslash_col_name(void) { + return assert_save_rejects_unsafe_col_name( + TMP_SPLAY_BASE "/backslash_col", "a\\b", 3); +} - ray_release(col_slash); - ray_release(col_ok); - ray_release(tbl); - rm_rf(dir); - PASS(); +static test_result_t test_save_rejects_nul_col_name(void) { + static const char bad_name[] = { 'a', '\0', 'b' }; + return assert_save_rejects_unsafe_col_name( + TMP_SPLAY_BASE "/nul_col", bad_name, sizeof(bad_name)); } /* ========================================================================= @@ -2191,11 +2166,88 @@ static test_result_t test_resolution_explicit_wins(void) { /* ---- Suite definition -------------------------------------------------- */ + +/* ========================================================================= + * HAS_NULLS must round-trip losslessly through a splayed store, for EVERY + * persisted type. + * + * ray_col_save_sym_encoded REBUILDS the on-disk attrs byte (the SYM width + * bits depend on the target domain's size), and it used to rebuild it as + * (width | SORTED) only — silently dropping HAS_NULLS on every splayed SYM + * column, so an all-sym-0 column came back as attrs 0 (issue #416). That + * also made the store a lying instrument for attrs comparisons. + * + * Each column below is built with a null in it, flagged HAS_NULLS, saved and + * reloaded; the reloaded attrs must still carry the bit. SYM is the case that + * regressed, but the loop covers the rest so the next writer that rebuilds an + * attrs byte is caught too. The SYM cell is sym 0 — the canonical SYM null, + * and position 0 of any symfile — so the value, not just the flag, survives + * re-encoding into the store's domain. + * ========================================================================= */ +static test_result_t test_splayed_has_nulls_roundtrip(void) { + static const int8_t types[] = { + RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_F32, RAY_F64, + RAY_DATE, RAY_TIME, RAY_TIMESTAMP, RAY_GUID, RAY_SYM, RAY_STR, + }; + const int n_types = (int)(sizeof(types) / sizeof(*types)); + + for (int i = 0; i < n_types; i++) { + int8_t t = types[i]; + const char* dir = TMP_SPLAY_BASE "/hasnulls_rt"; + rm_rf(dir); + + ray_t* col = (t == RAY_SYM) ? ray_sym_vec_new(RAY_SYM_W8, 4) + : ray_vec_new(t, 4); + TEST_ASSERT_NOT_NULL(col); + TEST_ASSERT_FALSE(RAY_IS_ERR(col)); + col->len = 4; + memset(ray_data(col), 0, 4 * (size_t)ray_type_sizes[(uint8_t)t]); + if (t == RAY_SYM) { + /* All four cells are sym 0 = the canonical SYM null. */ + memset(ray_data(col), 0, 4); + } + col->attrs |= RAY_ATTR_HAS_NULLS; + uint8_t want = (uint8_t)(col->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_EQ_I(want, RAY_ATTR_HAS_NULLS); + + int64_t cname = ray_sym_intern("c", 1); + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, cname, col); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); + + char sym_path[512]; + snprintf(sym_path, sizeof(sym_path), "%s/.sym", dir); + ray_err_t err = ray_splay_save(tbl, dir, sym_path); + TEST_ASSERT_EQ_I(err, RAY_OK); + + ray_t* loaded = ray_read_splayed(dir, sym_path); + TEST_ASSERT_NOT_NULL(loaded); + TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); + ray_t* rcol = ray_table_get_col_idx(loaded, 0); + TEST_ASSERT_NOT_NULL(rcol); + TEST_ASSERT_EQ_I(rcol->type, t); + /* The bit, and (for SYM) the null value it advertises. */ + TEST_ASSERT_EQ_I(rcol->attrs & RAY_ATTR_HAS_NULLS, RAY_ATTR_HAS_NULLS); + if (t == RAY_SYM) + TEST_ASSERT_EQ_I(ray_read_sym(ray_data(rcol), 0, RAY_SYM, + rcol->attrs), 0); + + ray_release(loaded); + ray_release(col); + ray_release(tbl); + rm_rf(dir); + } + PASS(); +} + const test_entry_t splay_entries[] = { + { "splay/has_nulls_roundtrip", test_splayed_has_nulls_roundtrip, splay_setup, splay_teardown }, { "splay/save_null_dir", test_save_null_dir, splay_setup, splay_teardown }, { "splay/save_null_tbl", test_save_null_tbl, splay_setup, splay_teardown }, - { "splay/save_skips_dot_col_name", test_save_skips_dot_col_name, splay_setup, splay_teardown }, - { "splay/save_skips_slash_col_name", test_save_skips_slash_col_name, splay_setup, splay_teardown }, + { "splay/save_rejects_dot_col_name", test_save_rejects_dot_col_name, splay_setup, splay_teardown }, + { "splay/save_rejects_slash_col_name", test_save_rejects_slash_col_name, splay_setup, splay_teardown }, + { "splay/save_rejects_backslash_col_name", test_save_rejects_backslash_col_name, splay_setup, splay_teardown }, + { "splay/save_rejects_nul_col_name", test_save_rejects_nul_col_name, splay_setup, splay_teardown }, { "splay/load_null_dir", test_load_null_dir, splay_setup, splay_teardown }, { "splay/load_missing_schema", test_load_missing_schema, splay_setup, splay_teardown }, { "splay/load_missing_col_file", test_load_missing_col_file, splay_setup, splay_teardown }, diff --git a/test/test_store.c b/test/test_store.c index 0903c56b5..2e13f2f68 100644 --- a/test/test_store.c +++ b/test/test_store.c @@ -407,10 +407,13 @@ static test_result_t test_splay_str_column_roundtrip(void) { TEST_ASSERT_EQ_U(loaded_names->mmod, 1); TEST_ASSERT_EQ_I(loaded_names->type, RAY_STR); TEST_ASSERT_NOT_NULL(loaded_names->str_pool); - TEST_ASSERT_EQ_U(loaded_names->str_pool->mmod, 2); - /* STR has no null: index 2 roundtrips as "", no HAS_NULLS */ - TEST_ASSERT_FALSE(loaded_names->attrs & RAY_ATTR_HAS_NULLS); - TEST_ASSERT_FALSE(ray_vec_is_null(loaded_names, 2)); + /* The pool owns the mapping it shares with the column (mmod 3), so a + * selection that keeps the pool keeps the region — the column's own + * free no longer takes the bytes with it. */ + TEST_ASSERT_EQ_U(loaded_names->str_pool->mmod, 3); + /* Empty STR roundtrips as the canonical null and retains metadata. */ + TEST_ASSERT_TRUE(loaded_names->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_TRUE(ray_vec_is_null(loaded_names, 2)); size_t slen = 0; const char* s0 = ray_str_vec_get(loaded_names, 0, &slen); @@ -640,7 +643,8 @@ static test_result_t test_splay_save_preflight_preserves_generation(void) { ray_vec_from_raw(RAY_I64, dv_raw, 2)); ray_t* bad = ray_table_new(2); bad = ray_table_add_col(bad, k_id, new_k); - bad = ray_table_add_col(bad, v_id, unsupported); + bad = ray_table_add_col(bad, v_id, old_v); + ray_table_set_col_idx(bad, 1, unsupported); TEST_ASSERT_FALSE(RAY_IS_ERR(bad)); TEST_ASSERT_EQ_I(ray_splay_save(bad, TMP_SPLAY_DIR, NULL), RAY_ERR_NYI); @@ -1895,10 +1899,10 @@ static test_result_t test_serde_null_roundtrip(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(back)); TEST_ASSERT_EQ_I(back->type, RAY_STR); TEST_ASSERT_EQ_I(back->len, 3); - /* STR has no null: the "" placeholder roundtrips as "", no HAS_NULLS */ - TEST_ASSERT_FALSE(back->attrs & RAY_ATTR_HAS_NULLS); + /* Empty STR roundtrips as the canonical null. */ + TEST_ASSERT_TRUE(back->attrs & RAY_ATTR_HAS_NULLS); TEST_ASSERT_FALSE(ray_vec_is_null(back, 0)); - TEST_ASSERT_FALSE(ray_vec_is_null(back, 1)); + TEST_ASSERT_TRUE(ray_vec_is_null(back, 1)); TEST_ASSERT_FALSE(ray_vec_is_null(back, 2)); /* Non-null elements must survive */ @@ -1964,7 +1968,7 @@ static test_result_t test_serde_typed_null_atoms(void) { const int8_t atom_types[] = { -RAY_I64, -RAY_F64, -RAY_DATE, -RAY_TIME, -RAY_TIMESTAMP, - -RAY_I32, -RAY_I16, -RAY_BOOL, -RAY_U8, /* STR and SYM have no null atom */ + -RAY_I32, -RAY_I16, -RAY_BOOL, -RAY_U8, /* STR/SYM need no wire null flag */ }; for (size_t i = 0; i < sizeof(atom_types)/sizeof(atom_types[0]); i++) { int8_t t = atom_types[i]; @@ -3177,6 +3181,128 @@ static test_result_t test_serde_table_dict_de_errors(void) { PASS(); } +/* Splice a container frame — [type][attrs] + payload(a) + payload(b) — from two + * real serialized sub-objects, wrapped in a fresh ipc header. Uses ray_ser and + * sizeof(ray_ipc_header_t), so it stays honest if the wire layout ever changes + * (rather than hard-coding the header size / field offsets). */ +#define TEST_ASSERT_ERR_CODE_MSG(r, code, needle) do { \ + TEST_ASSERT_NOT_NULL(r); \ + TEST_ASSERT_TRUE(RAY_IS_ERR(r)); \ + TEST_ASSERT_STR_EQ(ray_err_code(r), code); \ + const char* _msg = ray_error_msg(); \ + TEST_ASSERT_NOT_NULL(_msg); \ + TEST_ASSERT_FMT(strstr(_msg, needle) != NULL, \ + "error message \"%s\" does not contain \"%s\"", \ + _msg, needle); \ +} while (0) + +static ray_t* serde_splice_container(uint8_t type_byte, ray_t* a, ray_t* b) { + size_t hdrsz = sizeof(ray_ipc_header_t); + ray_t* fa = ray_ser(a); + ray_t* fb = ray_ser(b); + if (!fa || RAY_IS_ERR(fa) || !fb || RAY_IS_ERR(fb)) { + if (fa) ray_release(fa); + if (fb) ray_release(fb); + return NULL; + } + size_t pa = (size_t)fa->len - hdrsz; + size_t pb = (size_t)fb->len - hdrsz; + int64_t payload = 2 + (int64_t)pa + (int64_t)pb; + int64_t total = (int64_t)hdrsz + payload; + ray_t* buf = ray_vec_new(RAY_U8, total); + if (!buf || RAY_IS_ERR(buf)) { + ray_release(fa); + ray_release(fb); + return buf; + } + buf->len = total; + uint8_t* p = (uint8_t*)ray_data(buf); + ray_ipc_header_t* hdr = (ray_ipc_header_t*)p; + hdr->prefix = RAY_SERDE_PREFIX; + hdr->version = RAY_SERDE_WIRE_VERSION; + hdr->flags = 0; hdr->endian = RAY_SERDE_ENDIAN; hdr->msgtype = 0; + hdr->size = payload; + uint8_t* pl = p + hdrsz; + pl[0] = type_byte; + pl[1] = 0; + memcpy(pl + 2, (uint8_t*)ray_data(fa) + hdrsz, pa); + memcpy(pl + 2 + pa, (uint8_t*)ray_data(fb) + hdrsz, pb); + ray_release(fa); + ray_release(fb); + return buf; +} + +/* A container frame whose two counts disagree must be rejected, not silently + * accepted as the shorter of the two. */ +static test_result_t test_serde_container_count_mismatch(void) { + /* TABLE: 2 schema names, 1 column → rejected (not truncated to 1 column). */ + { + int64_t names[] = { 7, 7 }; + ray_t* schema = ray_vec_from_raw(RAY_I64, names, 2); + int64_t c0[] = { 1 }; + ray_t* cols = ray_list_new(1); + ray_t* col0 = ray_vec_from_raw(RAY_I64, c0, 1); + cols = ray_list_append(cols, col0); + ray_release(col0); + ray_t* frame = serde_splice_container((uint8_t)RAY_TABLE, schema, cols); + TEST_ASSERT_NOT_NULL(frame); + ray_t* r = ray_de(frame); + TEST_ASSERT_ERR_CODE_MSG(r, "domain", "schema/column count mismatch"); + ray_error_free(r); ray_release(frame); ray_release(schema); ray_release(cols); + } + /* TABLE: 2 columns of unequal length (2 and 1) → rejected (ragged rows). */ + { + int64_t names[] = { 7, 8 }; + ray_t* schema = ray_vec_from_raw(RAY_I64, names, 2); + int64_t c0[] = { 1, 2 }; + int64_t c1[] = { 3 }; + ray_t* cols = ray_list_new(2); + ray_t* col0 = ray_vec_from_raw(RAY_I64, c0, 2); + ray_t* col1 = ray_vec_from_raw(RAY_I64, c1, 1); + cols = ray_list_append(cols, col0); + cols = ray_list_append(cols, col1); + ray_release(col0); + ray_release(col1); + ray_t* frame = serde_splice_container((uint8_t)RAY_TABLE, schema, cols); + TEST_ASSERT_NOT_NULL(frame); + ray_t* r = ray_de(frame); + TEST_ASSERT_ERR_CODE_MSG(r, "domain", "ragged columns"); + ray_error_free(r); ray_release(frame); ray_release(schema); ray_release(cols); + } + /* TABLE: atom columns are not valid columns even when their scalar payloads + * match, because row-wise code would read from non-existent vector data. */ + { + int64_t names[] = { 7, 8 }; + ray_t* schema = ray_vec_from_raw(RAY_I64, names, 2); + ray_t* cols = ray_list_new(2); + ray_t* col0 = ray_i64(2); + ray_t* col1 = ray_i64(2); + cols = ray_list_append(cols, col0); + cols = ray_list_append(cols, col1); + ray_release(col0); + ray_release(col1); + ray_t* frame = serde_splice_container((uint8_t)RAY_TABLE, schema, cols); + TEST_ASSERT_NOT_NULL(frame); + ray_t* r = ray_de(frame); + TEST_ASSERT_ERR_CODE_MSG(r, "domain", "column must be list/vector-like"); + ray_error_free(r); ray_release(frame); ray_release(schema); ray_release(cols); + } + /* DICT: 2 keys, 1 value → rejected (a probe would index vals[idx] with + * idx < keys->len, an OOB read past the shorter value block). */ + { + int64_t keys[] = { 7, 8 }; + ray_t* k = ray_vec_from_raw(RAY_I64, keys, 2); + int64_t vals[] = { 1 }; + ray_t* v = ray_vec_from_raw(RAY_I64, vals, 1); + ray_t* frame = serde_splice_container((uint8_t)RAY_DICT, k, v); + TEST_ASSERT_NOT_NULL(frame); + ray_t* r = ray_de(frame); + TEST_ASSERT_ERR_CODE_MSG(r, "domain", "key/value count mismatch"); + ray_error_free(r); ray_release(frame); ray_release(k); ray_release(v); + } + PASS(); +} + /* ---- serde coverage: TABLE deser type-mismatch and more error paths ------ */ static test_result_t test_serde_table_de_type_mismatch(void) { @@ -5052,6 +5178,109 @@ static test_result_t test_col_recursive_table(void) { PASS(); } +static bool test_write_exact(FILE* f, const void* data, size_t n) { + return fwrite(data, 1, n, f) == n; +} + +static bool test_write_i8(FILE* f, int8_t v) { + return test_write_exact(f, &v, sizeof(v)); +} + +static bool test_write_u32(FILE* f, uint32_t v) { + return test_write_exact(f, &v, sizeof(v)); +} + +static bool test_write_i64(FILE* f, int64_t v) { + return test_write_exact(f, &v, sizeof(v)); +} + +static bool test_write_i64_vec(FILE* f, const int64_t* vals, int64_t len) { + return test_write_i8(f, (int8_t)RAY_I64) && + test_write_i64(f, len) && + test_write_exact(f, vals, (size_t)len * sizeof(vals[0])); +} + +/* ---- test_col_recursive_container_guards -------------------------------- */ +static test_result_t test_col_recursive_container_guards(void) { + enum { + TEST_COL_LIST_MAGIC = 0x4754534CU, /* "LSTG" */ + TEST_COL_TABLE_MAGIC = 0x4C425454U /* "TTBL" */ + }; + + /* TABLE with atom columns: recursive on-disk decoding must hit the same + * shared table invariant as the serde decoder. */ + { + FILE* f = fopen(TMP_COL_PATH, "wb"); + TEST_ASSERT_NOT_NULL(f); + int64_t name_a = ray_sym_intern("bad_a", 5); + int64_t name_b = ray_sym_intern("bad_b", 5); + bool ok = test_write_u32(f, TEST_COL_TABLE_MAGIC) && + test_write_i8(f, (int8_t)RAY_TABLE) && + test_write_i64(f, 2) && + test_write_i64(f, 2) && + test_write_i64(f, name_a) && + test_write_i8(f, (int8_t)-RAY_I64) && + test_write_i64(f, 2) && + test_write_i64(f, name_b) && + test_write_i8(f, (int8_t)-RAY_I64) && + test_write_i64(f, 2); + fclose(f); + TEST_ASSERT_TRUE(ok); + + ray_t* bad = ray_col_load(TMP_COL_PATH); + TEST_ASSERT_ERR_CODE_MSG(bad, "domain", "column must be list/vector-like"); + ray_error_free(bad); + } + + /* TABLE with ragged vector columns. */ + { + FILE* f = fopen(TMP_COL_PATH, "wb"); + TEST_ASSERT_NOT_NULL(f); + int64_t name_a = ray_sym_intern("bad_a", 5); + int64_t name_b = ray_sym_intern("bad_b", 5); + int64_t a[] = { 1, 2 }; + int64_t b[] = { 3 }; + bool ok = test_write_u32(f, TEST_COL_TABLE_MAGIC) && + test_write_i8(f, (int8_t)RAY_TABLE) && + test_write_i64(f, 2) && + test_write_i64(f, 2) && + test_write_i64(f, name_a) && + test_write_i64_vec(f, a, 2) && + test_write_i64(f, name_b) && + test_write_i64_vec(f, b, 1); + fclose(f); + TEST_ASSERT_TRUE(ok); + + ray_t* bad = ray_col_load(TMP_COL_PATH); + TEST_ASSERT_ERR_CODE_MSG(bad, "domain", "ragged columns"); + ray_error_free(bad); + } + + /* DICT with two keys and one value, nested inside a generic list so it is + * decoded by col_read_recursive. */ + { + FILE* f = fopen(TMP_COL_PATH, "wb"); + TEST_ASSERT_NOT_NULL(f); + int64_t keys[] = { 7, 8 }; + int64_t vals[] = { 1 }; + bool ok = test_write_u32(f, TEST_COL_LIST_MAGIC) && + test_write_i8(f, (int8_t)RAY_LIST) && + test_write_i64(f, 1) && + test_write_i8(f, (int8_t)RAY_DICT) && + test_write_i64_vec(f, keys, 2) && + test_write_i64_vec(f, vals, 1); + fclose(f); + TEST_ASSERT_TRUE(ok); + + ray_t* bad = ray_col_load(TMP_COL_PATH); + TEST_ASSERT_ERR_CODE_MSG(bad, "domain", "key/value count mismatch"); + ray_error_free(bad); + } + + unlink(TMP_COL_PATH); + PASS(); +} + /* ---- test_col_recursive_read_corrupt ------------------------------------ */ /* Covers col_read_recursive corruption guards: * line 398/402: LIST with truncated count / count < 0 => "corrupt" @@ -5249,6 +5478,7 @@ const test_entry_t store_entries[] = { { "store/col_str_validate_corrupt", test_col_str_validate_corrupt, store_setup, store_teardown }, { "store/col_recursive_list_in_list", test_col_recursive_list_in_list, store_setup, store_teardown }, { "store/col_recursive_table", test_col_recursive_table, store_setup, store_teardown }, + { "store/col_recursive_container_guards", test_col_recursive_container_guards, store_setup, store_teardown }, { "store/col_recursive_read_corrupt", test_col_recursive_read_corrupt, store_setup, store_teardown }, { "store/col_link_sidecar_whitespace", test_col_link_sidecar_whitespace, store_setup, store_teardown }, { "store/col_save_nyi_type", test_col_save_nyi_type, store_setup, store_teardown }, @@ -5286,6 +5516,7 @@ const test_entry_t store_entries[] = { { "store/serde_save_serde_error", test_serde_save_serde_error, store_setup, store_teardown }, { "store/serde_de_raw_default", test_serde_de_raw_default_and_errors, store_setup, store_teardown }, { "store/serde_table_dict_de_errors", test_serde_table_dict_de_errors, store_setup, store_teardown }, + { "store/serde_container_count_mismatch", test_serde_container_count_mismatch, store_setup, store_teardown }, { "store/serde_table_de_type_mismatch", test_serde_table_de_type_mismatch, store_setup, store_teardown }, { "store/serde_de_size_bounds", test_serde_de_size_bounds, store_setup, store_teardown }, { "store/total_ram", test_total_ram, NULL, NULL }, diff --git a/test/test_str.c b/test/test_str.c index b0e901c39..d5f8343d6 100644 --- a/test/test_str.c +++ b/test/test_str.c @@ -667,13 +667,13 @@ static test_result_t test_str_t_cmp_order(void) { static test_result_t test_str_vec_null(void) { ray_t* v = ray_vec_new(RAY_STR, 4); v = ray_str_vec_append(v, "hello", 5); - v = ray_str_vec_append(v, "", 0); /* empty, not null */ + v = ray_str_vec_append(v, "", 0); /* canonical empty/null */ v = ray_str_vec_append(v, "world", 5); TEST_ASSERT_EQ_I(ray_len(v), 3); - /* STR has no null: set_null writes "" — the cell is never null */ + /* STR null is represented by the empty string. */ ray_vec_set_null(v, 1, true); - TEST_ASSERT_FALSE(ray_vec_is_null(v, 1)); + TEST_ASSERT_TRUE(ray_vec_is_null(v, 1)); TEST_ASSERT_FALSE(ray_vec_is_null(v, 0)); TEST_ASSERT_FALSE(ray_vec_is_null(v, 2)); @@ -697,7 +697,7 @@ static test_result_t test_str_vec_null_pooled(void) { /* Set null on row 1 — must not corrupt str_pool */ ray_vec_set_null(v, 1, true); - TEST_ASSERT_FALSE(ray_vec_is_null(v, 1)); + TEST_ASSERT_TRUE(ray_vec_is_null(v, 1)); TEST_ASSERT_FALSE(ray_vec_is_null(v, 0)); TEST_ASSERT_FALSE(ray_vec_is_null(v, 2)); @@ -849,12 +849,12 @@ static ray_t* make_str_sym_table(void) { return tbl; } -/* exec_like: non-STR/non-SYM input → memset(dst,0) else-branch */ +/* exec_like: non-STR/non-SYM input → type error */ static test_result_t test_str_like_non_string_type(void) { ray_heap_init(); (void)ray_sym_init(); - /* Build an I64 column — exec_like's else branch fills with 0 */ + /* Build an I64 column — exec_like's else branch raises a type error */ ray_t* col = ray_vec_new(RAY_I64, 3); col->len = 3; int64_t* cd = (int64_t*)ray_data(col); @@ -871,16 +871,10 @@ static test_result_t test_str_like_non_string_type(void) { ray_op_t* lk = ray_like(g, val, pat); ray_t* result = ray_execute(g, lk); - TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->type, RAY_BOOL); - TEST_ASSERT_EQ_I(result->len, 3); - uint8_t* rd = (uint8_t*)ray_data(result); - /* All false — I64 is not a string type */ - TEST_ASSERT_EQ_I(rd[0], 0); - TEST_ASSERT_EQ_I(rd[1], 0); - TEST_ASSERT_EQ_I(rd[2], 0); + /* I64 is not a string type — loud, not a silently empty match */ + TEST_ASSERT_TRUE(RAY_IS_ERR(result)); - ray_release(result); + ray_error_free(result); /* ray_release is a no-op on errors */ ray_graph_free(g); ray_release(tbl); ray_sym_destroy(); @@ -888,7 +882,7 @@ static test_result_t test_str_like_non_string_type(void) { PASS(); } -/* exec_ilike: non-STR/non-SYM input → memset(dst,0) else-branch */ +/* exec_ilike: non-STR/non-SYM input → type error */ static test_result_t test_str_ilike_non_string_type(void) { ray_heap_init(); (void)ray_sym_init(); @@ -909,13 +903,10 @@ static test_result_t test_str_ilike_non_string_type(void) { ray_op_t* ilk = ray_ilike(g, val, pat); ray_t* result = ray_execute(g, ilk); - TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->type, RAY_BOOL); - uint8_t* rd = (uint8_t*)ray_data(result); - TEST_ASSERT_EQ_I(rd[0], 0); - TEST_ASSERT_EQ_I(rd[1], 0); + /* I64 is not a string type — loud, not a silently empty match */ + TEST_ASSERT_TRUE(RAY_IS_ERR(result)); - ray_release(result); + ray_error_free(result); /* ray_release is a no-op on errors */ ray_graph_free(g); ray_release(tbl); ray_sym_destroy(); @@ -1739,10 +1730,10 @@ static test_result_t test_str_vec_concat_nulls(void) { /* a's nulls preserved */ TEST_ASSERT_FALSE(ray_vec_is_null(c, 0)); - TEST_ASSERT_FALSE(ray_vec_is_null(c, 1)); /* a[1] was null */ + TEST_ASSERT_TRUE(ray_vec_is_null(c, 1)); /* a[1] was null */ TEST_ASSERT_FALSE(ray_vec_is_null(c, 2)); /* b's nulls preserved at offset a->len */ - TEST_ASSERT_FALSE(ray_vec_is_null(c, 3)); /* b[0] was null */ + TEST_ASSERT_TRUE(ray_vec_is_null(c, 3)); /* b[0] was null */ TEST_ASSERT_FALSE(ray_vec_is_null(c, 4)); ray_release(c); @@ -1768,7 +1759,7 @@ static test_result_t test_str_vec_slice_null(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(s)); /* Slice index 0 = parent index 1 = null */ - TEST_ASSERT_FALSE(ray_vec_is_null(s, 0)); + TEST_ASSERT_TRUE(ray_vec_is_null(s, 0)); /* Slice index 1 = parent index 2 = not null */ TEST_ASSERT_FALSE(ray_vec_is_null(s, 1)); @@ -1853,7 +1844,7 @@ static test_result_t test_str_vec_from_parts(void) { p = ray_str_vec_get(v, 1, &l); TEST_ASSERT_EQ_U(l, 3); TEST_ASSERT_EQ_I(memcmp(p,"abc",3), 0); p = ray_str_vec_get(v, 2, &l); TEST_ASSERT_EQ_U(l, 27); TEST_ASSERT_EQ_I(memcmp(p,"this_is_long_enough_to_pool",27), 0); p = ray_str_vec_get(v, 3, &l); TEST_ASSERT_EQ_U(l, 1); TEST_ASSERT_EQ_I(p[0],'x'); - /* Missing STR input collapses to the ordinary empty string. */ + /* Missing STR input uses the canonical empty/null string. */ p = ray_str_vec_get(v, 4, &l); TEST_ASSERT_EQ_U(l, 0); (void)p; ray_release(v); ray_heap_destroy(); diff --git a/test/test_table.c b/test/test_table.c index 1c7075f6a..97530cbe5 100644 --- a/test/test_table.c +++ b/test/test_table.c @@ -398,7 +398,7 @@ static test_result_t test_table_add_col_null_tbl(void) { PASS(); } -/* NULL/error col_vec yields a type error; table is left untouched (table.c:105). */ +/* NULL/error col_vec yields a domain error and consumes the input table. */ static test_result_t test_table_add_col_bad_colvec(void) { ray_t* tbl = ray_table_new(2); @@ -407,14 +407,13 @@ static test_result_t test_table_add_col_bad_colvec(void) { TEST_ASSERT_TRUE(RAY_IS_ERR(r)); ray_error_free(r); - /* tbl was not consumed on the NULL-col_vec early return */ + tbl = ray_table_new(2); ray_t* err = ray_error("test", NULL); r = ray_table_add_col(tbl, id, err); TEST_ASSERT_TRUE(RAY_IS_ERR(r)); ray_error_free(r); ray_error_free(err); - ray_release(tbl); PASS(); } @@ -621,4 +620,3 @@ const test_entry_t table_entries[] = { { NULL, NULL, NULL, NULL }, }; - diff --git a/test/test_vec.c b/test/test_vec.c index a0b8d1fd9..e331a3b5c 100644 --- a/test/test_vec.c +++ b/test/test_vec.c @@ -28,7 +28,9 @@ #include "vec/embedding.h" #include "table/sym.h" #include "core/platform.h" +#include "store/serde.h" #include +#include /* ---- Setup / Teardown -------------------------------------------------- */ @@ -983,12 +985,13 @@ static test_result_t test_str_vec_null_insert_compact(void) { ray_err_t err = ray_vec_set_null_checked(sv, 0, true); TEST_ASSERT_EQ_I(err, RAY_ERR_TYPE); /* slice → error */ ray_release(sv); - /* On the real vec, SYM is rejected (use U8 vec test) */ + /* On the real vec, SYM writes its canonical id-0 null. */ ray_t* sym_v = ray_sym_vec_new(RAY_SYM_W64, 2); uint64_t sid = 1; sym_v = ray_vec_append(sym_v, &sid); ray_err_t sym_err = ray_vec_set_null_checked(sym_v, 0, true); - TEST_ASSERT_EQ_I(sym_err, RAY_ERR_TYPE); + TEST_ASSERT_EQ_I(sym_err, RAY_OK); + TEST_ASSERT_TRUE(ray_vec_is_null(sym_v, 0)); ray_release(sym_v); /* insert_at: insert at end */ @@ -1167,11 +1170,11 @@ static test_result_t test_vec_sym_is_null_path(void) { w32 = ray_vec_append(w32, &id32); w64 = ray_vec_append(w64, &id64); - /* SYM never null via public API */ - TEST_ASSERT_FALSE(ray_vec_is_null(w8, 0)); - TEST_ASSERT_FALSE(ray_vec_is_null(w16, 0)); - TEST_ASSERT_FALSE(ray_vec_is_null(w32, 0)); - TEST_ASSERT_FALSE(ray_vec_is_null(w64, 0)); + /* Every adaptive width recognizes id 0 as canonical null. */ + TEST_ASSERT_TRUE(ray_vec_is_null(w8, 0)); + TEST_ASSERT_TRUE(ray_vec_is_null(w16, 0)); + TEST_ASSERT_TRUE(ray_vec_is_null(w32, 0)); + TEST_ASSERT_TRUE(ray_vec_is_null(w64, 0)); ray_release(w8); ray_release(w16); ray_release(w32); ray_release(w64); ray_sym_destroy(); @@ -1692,8 +1695,8 @@ static test_result_t test_vec_concat_str_null(void) { ray_t* a = ray_vec_new(RAY_STR, 2); a = ray_str_vec_append(a, "x", 1); a = ray_str_vec_append(a, "yy", 2); - ray_vec_set_null(a, 0, true); /* STR: set_null -> "" */ - TEST_ASSERT_FALSE(ray_vec_is_null(a, 0)); + ray_vec_set_null(a, 0, true); /* STR: set_null -> canonical "" */ + TEST_ASSERT_TRUE(ray_vec_is_null(a, 0)); ray_t* b = ray_vec_new(RAY_STR, 1); b = ray_str_vec_append(b, "zzz", 3); @@ -1703,9 +1706,9 @@ static test_result_t test_vec_concat_str_null(void) { TEST_ASSERT_NOT_NULL(c); TEST_ASSERT_FALSE(RAY_IS_ERR(c)); TEST_ASSERT_EQ_I(c->len, 3); - TEST_ASSERT_FALSE(ray_vec_is_null(c, 0)); /* a[0] -> "" (STR no-null) */ + TEST_ASSERT_TRUE(ray_vec_is_null(c, 0)); /* a[0] -> canonical null */ TEST_ASSERT_FALSE(ray_vec_is_null(c, 1)); /* a[1]=yy */ - TEST_ASSERT_FALSE(ray_vec_is_null(c, 2)); /* b[0] -> "" (STR no-null) */ + TEST_ASSERT_TRUE(ray_vec_is_null(c, 2)); /* b[0] -> canonical null */ ray_release(a); ray_release(b); @@ -1893,8 +1896,8 @@ static test_result_t test_str_vec_compact_paths(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(v)); /* set element 1 null (STR is nullable). */ - ray_vec_set_null(v, 1, true); /* STR: set_null -> "" */ - TEST_ASSERT_FALSE(ray_vec_is_null(v, 1)); + ray_vec_set_null(v, 1, true); /* STR: set_null -> canonical "" */ + TEST_ASSERT_TRUE(ray_vec_is_null(v, 1)); /* compact reclaims dead bytes; null + inline elements are skipped. */ v = ray_str_vec_compact(v); @@ -1906,8 +1909,8 @@ static test_result_t test_str_vec_compact_paths(void) { const char* s2 = ray_str_vec_get(v, 2, &l); TEST_ASSERT_EQ_I((int64_t)l, 32); TEST_ASSERT_MEM_EQ(32, s2, "pooled_gamma_string_three_here!!"); - /* element 1 is "" after compact (STR no-null). */ - TEST_ASSERT_FALSE(ray_vec_is_null(v, 1)); + /* element 1 remains the canonical empty/null after compact. */ + TEST_ASSERT_TRUE(ray_vec_is_null(v, 1)); /* compact with no dead bytes is a no-op early return (line 1182). */ ray_t* same = ray_str_vec_compact(v); @@ -2149,6 +2152,76 @@ static test_result_t test_vec_from_raw_sym(void) { PASS(); } +/* ---- from_raw: sentinel nulls in raw input must set HAS_NULLS ---------- */ + +static test_result_t test_vec_from_raw_sentinel_nulls(void) { + /* #445: a binding passing INT64_MIN through from_raw got a vector whose + * payload held the null sentinel while HAS_NULLS stayed clear, so + * ray_vec_is_null (gated on the attr for numeric types) denied the null + * and it rendered as -9223372036854775808 — including after an IPC + * round trip. Construction must scan the raw payload. */ + int64_t iv[] = { 1, NULL_I64, 3 }; + ray_t* v = ray_vec_from_raw(RAY_I64, iv, 3); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + TEST_ASSERT_TRUE(v->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_FALSE(ray_vec_is_null(v, 0)); + TEST_ASSERT_TRUE(ray_vec_is_null(v, 1)); + + /* Serialize/deserialize keeps both the flag and the null. */ + ray_t* wire = ray_ser(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(wire)); + ray_t* back = ray_de(wire); + TEST_ASSERT_FALSE(RAY_IS_ERR(back)); + TEST_ASSERT_TRUE(back->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_TRUE(ray_vec_is_null(back, 1)); + ray_release(back); + ray_release(wire); + ray_release(v); + + /* F64: any NaN bit pattern is the sentinel. */ + double fv[] = { 1.5, (double)NAN, 3.5 }; + ray_t* f = ray_vec_from_raw(RAY_F64, fv, 3); + TEST_ASSERT_FALSE(RAY_IS_ERR(f)); + TEST_ASSERT_TRUE(f->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_TRUE(ray_vec_is_null(f, 1)); + ray_t* fwire = ray_ser(f); + ray_t* fback = ray_de(fwire); + TEST_ASSERT_FALSE(RAY_IS_ERR(fback)); + TEST_ASSERT_TRUE(ray_vec_is_null(fback, 1)); + ray_release(fback); + ray_release(fwire); + ray_release(f); + + /* I32/DATE width, I16, and GUID all-zero sentinel. */ + int32_t dv[] = { 100, NULL_I32 }; + ray_t* d = ray_vec_from_raw(RAY_DATE, dv, 2); + TEST_ASSERT_TRUE(d->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_TRUE(ray_vec_is_null(d, 1)); + ray_release(d); + + int16_t sv[] = { 7, NULL_I16 }; + ray_t* s = ray_vec_from_raw(RAY_I16, sv, 2); + TEST_ASSERT_TRUE(s->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_TRUE(ray_vec_is_null(s, 1)); + ray_release(s); + + uint8_t gv[32]; + memset(gv, 0xAB, 16); + memset(gv + 16, 0, 16); + ray_t* g = ray_vec_from_raw(RAY_GUID, gv, 2); + TEST_ASSERT_TRUE(g->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_FALSE(ray_vec_is_null(g, 0)); + TEST_ASSERT_TRUE(ray_vec_is_null(g, 1)); + ray_release(g); + + /* Clean input must NOT pick up the flag. */ + int64_t cv[] = { 1, 2, 3 }; + ray_t* c = ray_vec_from_raw(RAY_I64, cv, 3); + TEST_ASSERT_FALSE(c->attrs & RAY_ATTR_HAS_NULLS); + ray_release(c); + PASS(); +} + /* ---- slice: NULL/error passthrough + zero-length ----------------------- */ static test_result_t test_vec_slice_guards(void) { @@ -2246,8 +2319,8 @@ const test_entry_t vec_entries[] = { { "vec/insert_many_atom", test_vec_insert_many_atom, vec_setup, vec_teardown }, { "vec/insert_many_guards", test_vec_insert_many_guards, vec_setup, vec_teardown }, { "vec/from_raw_sym", test_vec_from_raw_sym, vec_setup, vec_teardown }, + { "vec/from_raw_sentinel_nulls", test_vec_from_raw_sentinel_nulls, vec_setup, vec_teardown }, { "vec/slice_guards", test_vec_slice_guards, vec_setup, vec_teardown }, { NULL, NULL, NULL, NULL }, }; -