diff --git a/include/rayforce.h b/include/rayforce.h index b7d79c03c..efbfffc2b 100644 --- a/include/rayforce.h +++ b/include/rayforce.h @@ -675,6 +675,33 @@ ray_runtime_t* ray_runtime_create_with_sym_err(const char* sym_path, * exactly one ray_runtime_create* call. */ void ray_runtime_destroy(ray_runtime_t* rt); +/* ===== Host-Driven Event Loop API ===== + * + * Embedders that own the runtime thread can attach a poll to the runtime, + * create listeners from Rayfall (for example `(.sys.listen 7701)`), and + * service IPC and Rayfall timers in bounded slices. The runtime borrows + * the poll: detach and destroy it before destroying the runtime. */ + +typedef struct ray_poll ray_poll_t; + +ray_poll_t* ray_poll_create(void); +void ray_poll_destroy(ray_poll_t* poll); + +/* Run until ray_poll_exit is called. */ +int64_t ray_poll_run(ray_poll_t* poll); + +/* Serve events and timers for at most timeout_ms milliseconds. + * A negative timeout preserves ray_poll_run's blocking behavior; zero + * performs one non-blocking drain. Returns 0 (or an exit code) normally + * and -1 when poll is NULL or the platform event queue fails. */ +int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms); + +void ray_poll_exit(ray_poll_t* poll, int64_t code); + +/* The runtime borrows this pointer; pass NULL to detach it. */ +void ray_runtime_set_poll(void* poll); +void* ray_runtime_get_poll(void); + /* Parse and evaluate a Rayfall source string against the global env. * Returns RAY_NULL_OBJ for successful void / null results, an error ray_t* * on failure (test with RAY_IS_ERR and inspect with ray_err_code), or the diff --git a/src/core/epoll.c b/src/core/epoll.c index 848efc9ca..680e73f2a 100644 --- a/src/core/epoll.c +++ b/src/core/epoll.c @@ -156,14 +156,23 @@ void ray_poll_deregister(ray_poll_t* poll, int64_t id) poll->sels[id] = NULL; } -int64_t ray_poll_run(ray_poll_t* poll) +int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) { if (!poll) return -1; struct epoll_event events[RAY_POLL_MAX_EVENTS]; + bool bounded = timeout_ms >= 0; + int64_t end_ms = bounded ? ray_time_now_ms() + timeout_ms : INT64_MAX; while (poll->code < 0) { int wait_ms = -1; + if (bounded) { + int64_t remaining = end_ms - ray_time_now_ms(); + if (remaining < 0) remaining = 0; + if (remaining > INT_MAX) remaining = INT_MAX; + wait_ms = (int)remaining; + } + if (poll->timers) { int64_t deadline = ray_timers_next_deadline_ms( (ray_timers_t*)poll->timers); @@ -172,7 +181,8 @@ int64_t ray_poll_run(ray_poll_t* poll) int64_t delta = deadline - now; if (delta < 0) delta = 0; if (delta > INT_MAX) delta = INT_MAX; - wait_ms = (int)delta; + if (wait_ms < 0 || delta < wait_ms) + wait_ms = (int)delta; } } @@ -264,9 +274,15 @@ int64_t ray_poll_run(ray_poll_t* poll) if (poll->timers) ray_timers_fire_expired((ray_timers_t*)poll->timers); + if (bounded) break; } - return poll->code; + return poll->code >= 0 ? poll->code : 0; +} + +int64_t ray_poll_run(ray_poll_t* poll) +{ + return ray_poll_run_for(poll, -1); } #endif /* __linux__ */ diff --git a/src/core/iocp.c b/src/core/iocp.c index 8bbfac871..17b64ea54 100644 --- a/src/core/iocp.c +++ b/src/core/iocp.c @@ -51,10 +51,15 @@ void ray_poll_deregister(ray_poll_t* poll, int64_t id) (void)poll; (void)id; } -int64_t ray_poll_run(ray_poll_t* poll) +int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) { - (void)poll; + (void)poll; (void)timeout_ms; return -1; } +int64_t ray_poll_run(ray_poll_t* poll) +{ + return ray_poll_run_for(poll, -1); +} + #endif /* _WIN32 */ diff --git a/src/core/kqueue.c b/src/core/kqueue.c index abbd49c67..0a5d43497 100644 --- a/src/core/kqueue.c +++ b/src/core/kqueue.c @@ -29,6 +29,7 @@ #include #include #include +#include #include #define RAY_POLL_MAX_EVENTS 64 @@ -159,15 +160,22 @@ void ray_poll_deregister(ray_poll_t* poll, int64_t id) poll->sels[id] = NULL; } -int64_t ray_poll_run(ray_poll_t* poll) +int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) { if (!poll) return -1; struct kevent events[RAY_POLL_MAX_EVENTS]; + bool bounded = timeout_ms >= 0; + int64_t end_ms = bounded ? ray_time_now_ms() + timeout_ms : INT64_MAX; while (poll->code < 0) { - struct timespec ts; - struct timespec* timeout = NULL; + int64_t wait_ms = -1; + if (bounded) { + int64_t remaining = end_ms - ray_time_now_ms(); + if (remaining < 0) remaining = 0; + wait_ms = remaining; + } + if (poll->timers) { int64_t deadline = ray_timers_next_deadline_ms( (ray_timers_t*)poll->timers); @@ -175,12 +183,19 @@ int64_t ray_poll_run(ray_poll_t* poll) int64_t now = ray_time_now_ms(); int64_t delta = deadline - now; if (delta < 0) delta = 0; - ts.tv_sec = (time_t)(delta / 1000); - ts.tv_nsec = (long)((delta % 1000) * 1000000L); - timeout = &ts; + if (wait_ms < 0 || delta < wait_ms) + wait_ms = delta; } } + struct timespec ts; + struct timespec* timeout = NULL; + if (wait_ms >= 0) { + ts.tv_sec = (time_t)(wait_ms / 1000); + ts.tv_nsec = (long)((wait_ms % 1000) * 1000000L); + timeout = &ts; + } + int n = kevent((int)poll->fd, NULL, 0, events, RAY_POLL_MAX_EVENTS, timeout); if (n < 0) { @@ -263,9 +278,15 @@ int64_t ray_poll_run(ray_poll_t* poll) if (poll->timers) ray_timers_fire_expired((ray_timers_t*)poll->timers); + if (bounded) break; } - return poll->code; + return poll->code >= 0 ? poll->code : 0; +} + +int64_t ray_poll_run(ray_poll_t* poll) +{ + return ray_poll_run_for(poll, -1); } #endif /* __APPLE__ */ diff --git a/src/core/poll.h b/src/core/poll.h index 8d248a3e8..19fa57282 100644 --- a/src/core/poll.h +++ b/src/core/poll.h @@ -107,6 +107,7 @@ void ray_poll_destroy(ray_poll_t* poll); int64_t ray_poll_register(ray_poll_t* poll, ray_poll_reg_t* reg); void ray_poll_deregister(ray_poll_t* poll, int64_t id); int64_t ray_poll_run(ray_poll_t* poll); +int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms); void ray_poll_exit(ray_poll_t* poll, int64_t code); ray_selector_t* ray_poll_get(ray_poll_t* poll, int64_t id); diff --git a/src/lang/eval.c b/src/lang/eval.c index 1581c3abb..58c791a47 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -2282,6 +2282,11 @@ op_storeglobal: { ray_t *name_obj = cpool[idx]; /* `set` returns its value, so the result must stay on the stack; * PEEK rather than POP. ray_env_set retains its own ref. */ + if (RAY_UNLIKELY(__VM->restricted)) { + ray_release(POP()); + vm_err_obj = ray_error("access", "restricted"); + goto vm_error; + } ray_t *val = PEEK(); ray_err_t err = ray_env_set(name_obj->i64, val); if (err != RAY_OK) { @@ -2296,6 +2301,11 @@ op_storeglobal_w: { uint16_t idx = (uint16_t)((code[ip] << 8) | code[ip + 1]); ip += 2; ray_t *name_obj = cpool[idx]; + if (RAY_UNLIKELY(__VM->restricted)) { + ray_release(POP()); + vm_err_obj = ray_error("access", "restricted"); + goto vm_error; + } ray_t *val = PEEK(); ray_err_t err = ray_env_set(name_obj->i64, val); if (err != RAY_OK) { @@ -2327,6 +2337,12 @@ op_jmpf: { op_call1: { ray_t *arg = POP(); ray_t *fn_obj = POP(); + if (RAY_UNLIKELY(fn_is_restricted(fn_obj))) { + ray_release(arg); + ray_release(fn_obj); + vm_err_obj = ray_error("access", "restricted"); + goto vm_error; + } ray_unary_fn fn = (ray_unary_fn)(uintptr_t)fn_obj->i64; ray_t *result; /* Materialise lazy args for non-lazy-aware fns. @@ -2359,6 +2375,13 @@ op_call2: { ray_t *right = POP(); ray_t *left = POP(); ray_t *fn_obj = POP(); + if (RAY_UNLIKELY(fn_is_restricted(fn_obj))) { + ray_release(left); + ray_release(right); + ray_release(fn_obj); + vm_err_obj = ray_error("access", "restricted"); + goto vm_error; + } ray_binary_fn fn = (ray_binary_fn)(uintptr_t)fn_obj->i64; ray_t *result; /* Materialise lazy args for non-lazy-aware fns. @@ -2407,6 +2430,12 @@ op_calln: { for (int32_t i = n - 1; i >= 0; i--) fn_args[i] = POP(); ray_t *fn_obj = POP(); + if (RAY_UNLIKELY(fn_is_restricted(fn_obj))) { + for (int32_t i = 0; i < n; i++) ray_release(fn_args[i]); + ray_release(fn_obj); + vm_err_obj = ray_error("access", "restricted"); + goto vm_error; + } ray_vary_fn fn = (ray_vary_fn)(uintptr_t)fn_obj->i64; if (!(fn_obj->attrs & RAY_FN_LAZY_AWARE)) { ray_t* err = materialize_owned_args(fn_args, n); diff --git a/src/ops/builtins.c b/src/ops/builtins.c index c6bfaae66..b82e52fd1 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -1628,73 +1628,122 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { int64_t days = val->i32; return ray_timestamp(days * 24LL * 60 * 60 * 1000000000LL); } - /* ISO string -> timestamp: "YYYY-MM-DD[T ]HH:MM:SS[.nnn...]" or "YYYY.MM.DDDHH:MM:SS.nnn..." */ + /* ISO string -> timestamp. Parse the whole value with a bounded + * cursor and require it to reach the end of the string. A partial + * or trailing-garbage match must be REJECTED — otherwise malformed + * input is silently cast to a valid-but-wrong timestamp, the exact + * data-corruption class this parser guards against. Grammar: + * YYYYMMDD [ (T|' '|D) HH:MM[:SS][.frac] [Z|(+|-)HH[:]?MM] ] + * where is '-' or '.' and is consistent within the date. */ if (val->type == -RAY_STR) { const char* sp = ray_str_ptr(val); size_t sl = ray_str_len(val); - if (sl < 10) return ray_error("domain", "as: cannot parse str as timestamp, too short, got %lld chars", (long long)sl); - int y, m, d, hh = 0, mm = 0, ss = 0; - long long frac = 0; - /* Try both formats: YYYY-MM-DD and YYYY.MM.DD */ - int parsed = sscanf(sp, "%d-%d-%d", &y, &m, &d); - /* parse date: try YYYY-MM-DD then YYYY.MM.DD */ - if (parsed != 3) { - parsed = sscanf(sp, "%d.%d.%d", &y, &m, &d); - /* YYYY.MM.DD format */ - } - if (parsed != 3) return ray_error("domain", "as: cannot parse str as timestamp, expected YYYY-MM-DD or YYYY.MM.DD"); - /* Parse optional time part */ - if (sl > 10 && (sp[10] == 'T' || sp[10] == ' ' || sp[10] == 'D')) { - sscanf(sp + 11, "%d:%d:%d", &hh, &mm, &ss); - /* Parse fractional seconds */ - const char* dot = memchr(sp + 11, '.', sl - 11); - if (dot) { - dot++; + size_t i = 0; + int y = 0, m = 0, d = 0, hh = 0, mm = 0, ss = 0; + long long frac = 0, tz_ns = 0; + + /* Read exactly `w` digits (0-9) into `out`, or fail. */ + #define TS_DIGITS(w, out) do { \ + (out) = 0; \ + for (int _k = 0; _k < (w); _k++) { \ + if (i >= sl || sp[i] < '0' || sp[i] > '9') \ + return ray_error("domain", "as: cannot parse str as timestamp, expected %d-digit field at offset %lld", (w), (long long)i); \ + (out) = (out) * 10 + (sp[i] - '0'); i++; \ + } \ + } while (0) + + TS_DIGITS(4, y); + if (i >= sl || (sp[i] != '-' && sp[i] != '.')) + return ray_error("domain", "as: cannot parse str as timestamp, expected '-' or '.' date separator"); + char dsep = sp[i]; i++; + TS_DIGITS(2, m); + if (i >= sl || sp[i] != dsep) + return ray_error("domain", "as: cannot parse str as timestamp, inconsistent date separator"); + i++; + TS_DIGITS(2, d); + if (m < 1 || m > 12 || d < 1) + return ray_error("domain", "as: cannot parse str as timestamp, date component out of range"); + static const int ts_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)); + int mdays = ts_md[m] + (m == 2 && leap ? 1 : 0); + if (d > mdays) + return ray_error("domain", "as: cannot parse str as timestamp, date component out of range"); + + if (i < sl) { + /* date/time separator: T, space, or D (kdb literal form) */ + if (sp[i] != 'T' && sp[i] != ' ' && sp[i] != 'D') + return ray_error("domain", "as: cannot parse str as timestamp, expected 'T', ' ', or 'D' between date and time"); + i++; + TS_DIGITS(2, hh); + if (i >= sl || sp[i] != ':') + return ray_error("domain", "as: cannot parse str as timestamp, expected ':' after hour"); + i++; + TS_DIGITS(2, mm); + if (i < sl && sp[i] == ':') { i++; TS_DIGITS(2, ss); } + if (hh > 23 || mm > 59 || ss > 59) + return ray_error("domain", "as: cannot parse str as timestamp, time component out of range"); + /* optional fractional seconds: at least one digit; up to 9 + * are kept (right-padded), any beyond are consumed. */ + if (i < sl && sp[i] == '.') { + i++; + if (i >= sl || sp[i] < '0' || sp[i] > '9') + return ray_error("domain", "as: cannot parse str as timestamp, expected fractional digits after '.'"); char fbuf[10] = "000000000"; int fi = 0; - while (*dot >= '0' && *dot <= '9' && fi < 9) fbuf[fi++] = *dot++; + while (i < sl && sp[i] >= '0' && sp[i] <= '9') { + if (fi < 9) fbuf[fi++] = sp[i]; + i++; + } frac = strtoll(fbuf, NULL, 10); } + /* optional timezone: Z | (+|-)HH[:]?MM */ + if (i < sl) { + if (sp[i] == 'Z' || sp[i] == 'z') { + i++; + } else if (sp[i] == '+' || sp[i] == '-') { + int tz_sign = (sp[i] == '+') ? 1 : -1; i++; + int tz_hh = 0, tz_mm = 0; + TS_DIGITS(2, tz_hh); + if (i < sl && sp[i] == ':') i++; /* optional ':' */ + TS_DIGITS(2, tz_mm); + if (tz_hh > 23 || tz_mm > 59) + return ray_error("domain", "as: cannot parse str as timestamp, timezone offset out of range"); + tz_ns = (long long)tz_sign * + ((long long)tz_hh * 3600 + (long long)tz_mm * 60) * 1000000000LL; + } else { + return ray_error("domain", "as: cannot parse str as timestamp, unexpected trailing characters"); + } + } } + if (i != sl) + return ray_error("domain", "as: cannot parse str as timestamp, unexpected trailing characters"); + #undef TS_DIGITS + /* Convert to days since 2000-01-01 */ int64_t days = 0; { int ty; for (ty = 2000; ty < y; ty++) days += (ty % 4 == 0 && (ty % 100 != 0 || ty % 400 == 0)) ? 366 : 365; for (ty = y; ty < 2000; ty++) days -= (ty % 4 == 0 && (ty % 100 != 0 || ty % 400 == 0)) ? 366 : 365; } - { static const int 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)); - for (int mi = 1; mi < m; mi++) days += md[mi] + (mi == 2 && leap ? 1 : 0); + { + for (int mi = 1; mi < m; mi++) days += ts_md[mi] + (mi == 2 && leap ? 1 : 0); days += d - 1; } - int64_t ns = days * 86400000000000LL + (int64_t)hh * 3600000000000LL + - (int64_t)mm * 60000000000LL + (int64_t)ss * 1000000000LL + frac; - /* Handle timezone offset: Z, +HH:MM, -HH:MM, +HHMM, -HHMM */ - if (sl > 19) { - const char* tz = sp + 19; /* after YYYY-MM-DDTHH:MM:SS */ - /* Skip fractional seconds */ - if (tz < sp + sl && *tz == '.') { - tz++; - while (tz < sp + sl && *tz >= '0' && *tz <= '9') tz++; - } - if (tz < sp + sl) { - if (*tz == 'Z') { - /* UTC, no adjustment */ - } else if (*tz == '+' || *tz == '-') { - int tz_sign = (*tz == '+') ? 1 : -1; - int tz_hh = 0, tz_mm = 0; - tz++; - /* Parse HH:MM or HHMM */ - if (tz + 4 < sp + sl && tz[2] == ':') { - sscanf(tz, "%2d:%2d", &tz_hh, &tz_mm); - } else { - sscanf(tz, "%2d%2d", &tz_hh, &tz_mm); - } - int64_t tz_ns = ((int64_t)tz_hh * 3600 + (int64_t)tz_mm * 60) * 1000000000LL; - ns -= tz_sign * tz_ns; - } - } - } + const int64_t ns_per_day = 86400000000000LL; + if (days > INT64_MAX / ns_per_day || days < INT64_MIN / ns_per_day) + return ray_error("domain", "as: timestamp out of int64 nanosecond range"); + int64_t day_ns = days * ns_per_day; + int64_t tod_ns = (int64_t)hh * 3600000000000LL + + (int64_t)mm * 60000000000LL + (int64_t)ss * 1000000000LL + frac; + if (day_ns > INT64_MAX - tod_ns) + return ray_error("domain", "as: timestamp out of int64 nanosecond range"); + int64_t ns = day_ns + tod_ns; + /* Timezone offset converts local wall-clock to UTC. */ + if (tz_ns > 0 && ns < INT64_MIN + tz_ns) + return ray_error("domain", "as: timestamp out of int64 nanosecond range"); + if (tz_ns < 0 && ns > INT64_MAX + tz_ns) + return ray_error("domain", "as: timestamp out of int64 nanosecond range"); + ns -= tz_ns; return ray_timestamp(ns); } /* Vector cast */ diff --git a/src/ops/graph.c b/src/ops/graph.c index 9775a6920..fdaa9de3a 100644 --- a/src/ops/graph.c +++ b/src/ops/graph.c @@ -421,6 +421,15 @@ static int8_t promote(int8_t a, int8_t b) { return RAY_BOOL; } +static bool type_is_temporal(int8_t t) { + return t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP; +} + +static int8_t promote_if_type(int8_t a, int8_t b) { + if (a == b && type_is_temporal(a)) return a; + return promote(a, b); +} + /* -------------------------------------------------------------------------- * Unary element-wise ops * -------------------------------------------------------------------------- */ @@ -493,7 +502,7 @@ ray_op_t* ray_if(ray_graph_t* g, ray_op_t* cond, ray_op_t* then_val, ray_op_t* e uint32_t cond_id = cond->id; uint32_t then_id = then_val->id; uint32_t else_id = else_val->id; - int8_t out_type = promote(then_val->out_type, else_val->out_type); + int8_t out_type = promote_if_type(then_val->out_type, else_val->out_type); /* IF preserves string types: promote() handles RAY_STR (wins over SYM); * SYM override only applies when neither side is RAY_STR */ if (out_type != RAY_STR && diff --git a/src/ops/query.c b/src/ops/query.c index f236bebd8..a0b5b2d52 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -11238,6 +11238,43 @@ static ray_t* append_atom_to_col(ray_t* col_vec, ray_t* atom) { } } +/* Build a fresh boxed LIST column. A table payload supplies a LIST column + * whose slots are rows and is therefore spliced; positional LIST/DICT rows + * append their value as one boxed cell. Every copied pointer gets its own + * retain so source tables and returned snapshots remain independently owned. */ +static ray_t* append_boxed_table_col(ray_t* orig_col, ray_t* payload, + bool splice_payload) { + if (!orig_col || RAY_IS_ERR(orig_col) || orig_col->type != RAY_LIST) + return ray_error("type", "insert: boxed column source must be LIST"); + if (splice_payload && + (!payload || RAY_IS_ERR(payload) || payload->type != RAY_LIST)) + return ray_error("type", "insert: table payload for a LIST column must be LIST"); + + int64_t tail = splice_payload ? payload->len : 1; + if (tail < 0 || orig_col->len > INT64_MAX - tail) + return ray_error("oom", NULL); + ray_t* out = ray_list_new(orig_col->len + tail); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + ray_t** dst = (ray_t**)ray_data(out); + ray_t** src = (ray_t**)ray_data(orig_col); + for (int64_t r = 0; r < orig_col->len; r++) { + dst[r] = src[r]; + if (dst[r]) ray_retain(dst[r]); + } + if (splice_payload) { + ray_t** cells = (ray_t**)ray_data(payload); + for (int64_t r = 0; r < tail; r++) { + dst[orig_col->len + r] = cells[r]; + if (cells[r]) ray_retain(cells[r]); + } + } else { + dst[orig_col->len] = payload; + if (payload) ray_retain(payload); + } + out->len = orig_col->len + tail; + return out; +} + /* (update {col: expr ... from: t [where: pred]}) * Special form — receives unevaluated dict arg. * For rows matching where (or all if no where), evaluate column expressions @@ -12192,7 +12229,9 @@ static int parted_key_atom_cmp(ray_t* key, ray_t* keys, int64_t cell, } static bool parted_segment_attrs_valid(int8_t base, uint8_t attrs) { - uint8_t allowed = RAY_ATTR_HAS_INDEX | RAY_ATTR_SORTED; + uint8_t allowed = base == RAY_LIST + ? 0 + : (RAY_ATTR_HAS_INDEX | RAY_ATTR_SORTED); if (base == RAY_SYM) allowed |= RAY_SYM_W_MASK; if (base == RAY_I32 || base == RAY_I64) allowed |= RAY_ATTR_HAS_LINK; @@ -12291,7 +12330,7 @@ static ray_t* validate_parted_insert_target(ray_t* tbl, wrapper->len != nparts || wrapper->attrs != 0) return ray_error("corrupt", "insert: physical column %lld is not a canonical PARTED wrapper", (long long)(c - 1)); int8_t base = (int8_t)RAY_PARTED_BASETYPE(wrapper->type); - if (base < RAY_BOOL || base > RAY_STR) + if (base != RAY_LIST && (base < RAY_BOOL || base > RAY_STR)) return ray_error("type", "insert: unsupported parted base type in physical column %lld", (long long)(c - 1)); ray_t** segs = (ray_t**)ray_data(wrapper); @@ -12408,7 +12447,22 @@ static ray_t* normalize_parted_insert_rows(ray_t* tbl, } ray_t** items = (ray_t**)ray_data(rows); for (int64_t c = 0; c < v->ndata; c++) { - vals = parted_values_append(vals, items[c], false); + ray_t* wrapper = ray_table_get_col_idx(tbl, c + 1); + if (RAY_PARTED_BASETYPE(wrapper->type) == RAY_LIST) { + ray_t* one = ray_list_new(1); + if (!one || RAY_IS_ERR(one)) { + ray_release(vals); + return one ? one : ray_error("oom", NULL); + } + one = ray_list_append(one, items[c]); + if (!one || RAY_IS_ERR(one)) { + ray_release(vals); + return one ? one : ray_error("oom", NULL); + } + vals = parted_values_append(vals, one, true); + } else { + vals = parted_values_append(vals, items[c], false); + } if (!vals || RAY_IS_ERR(vals)) return vals; } return vals; @@ -12472,7 +12526,23 @@ static ray_t* normalize_parted_insert_rows(ray_t* tbl, } if (dvals->type == RAY_LIST) { ray_t* item = ((ray_t**)ray_data(dvals))[found]; - vals = parted_values_append(vals, item, false); + ray_t* wrapper = ray_table_get_col_idx(tbl, c); + if (RAY_PARTED_BASETYPE(wrapper->type) == RAY_LIST && + item && item->type == RAY_LIST) { + ray_t* one = ray_list_new(1); + if (!one || RAY_IS_ERR(one)) { + ray_release(vals); + return one ? one : ray_error("oom", NULL); + } + one = ray_list_append(one, item); + if (!one || RAY_IS_ERR(one)) { + ray_release(vals); + return one ? one : ray_error("oom", NULL); + } + vals = parted_values_append(vals, one, true); + } else { + vals = parted_values_append(vals, item, false); + } } else { int owned = 0; ray_t* item = collection_elem(dvals, found, &owned); @@ -12484,7 +12554,8 @@ static ray_t* normalize_parted_insert_rows(ray_t* tbl, } static bool parted_value_is_scalar(ray_t* v) { - return v && !RAY_IS_ERR(v) && (RAY_IS_NULL(v) || v->type < 0); + return v && !RAY_IS_ERR(v) && + (RAY_IS_NULL(v) || (v->type != RAY_LIST && !ray_is_vec(v))); } static bool parted_source_vec_compatible(int8_t dst, int8_t src) { @@ -12540,7 +12611,8 @@ static ray_t* validate_parted_payloads(ray_t* tbl, for (int64_t c = 0; c < v->ndata; c++) { ray_t* payload = pv[c]; if (parted_value_is_scalar(payload)) continue; - if (!payload || RAY_IS_ERR(payload) || !ray_is_vec(payload)) + if (!payload || RAY_IS_ERR(payload) || + (payload->type != RAY_LIST && !ray_is_vec(payload))) return ray_error("type", "insert: physical column %lld payload must be an atom or an exactly typed vector", (long long)c); if (payload->len < 0) @@ -12555,6 +12627,12 @@ static ray_t* validate_parted_payloads(ray_t* tbl, ray_t* wrapper = ray_table_get_col_idx(tbl, c + 1); int8_t dst = (int8_t)RAY_PARTED_BASETYPE(wrapper->type); ray_t* payload = pv[c]; + if (dst == RAY_LIST) { + if (!parted_value_is_scalar(payload) && payload->type != RAY_LIST) + return ray_error("type", "insert: physical column %lld LIST payload must contain boxed rows", + (long long)c); + continue; + } if (!parted_value_is_scalar(payload) && !parted_source_vec_compatible(dst, payload->type)) return ray_error("type", "insert: physical column %lld vector type must exactly match %s", @@ -12742,6 +12820,38 @@ static ray_t* build_parted_nonsym_segment(int8_t base, return result; } +static ray_t* build_parted_list_segment(ray_t* old_seg, int64_t old_len, + ray_t* payload, int64_t batch) { + if (old_len > INT64_MAX - batch) return ray_error("oom", NULL); + ray_t* out = ray_list_new(old_len + batch); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + ray_t** dst = (ray_t**)ray_data(out); + if (old_seg) { + ray_t** src = (ray_t**)ray_data(old_seg); + for (int64_t r = 0; r < old_len; r++) { + dst[r] = src[r]; + if (dst[r]) ray_retain(dst[r]); + } + } else { + memset(dst, 0, (size_t)old_len * sizeof(ray_t*)); + } + + if (payload->type == RAY_LIST) { + ray_t** cells = (ray_t**)ray_data(payload); + for (int64_t r = 0; r < batch; r++) { + dst[old_len + r] = cells[r]; + if (cells[r]) ray_retain(cells[r]); + } + } else { + for (int64_t r = 0; r < batch; r++) { + dst[old_len + r] = payload; + ray_retain(payload); + } + } + out->len = old_len + batch; + return out; +} + /* Allocate and copy the old prefix of a W64 FILE-domain SYM segment. Appended * positions are intentionally zero until the late domain-intern commit pass. */ static ray_t* build_parted_sym_skeleton(parted_insert_view_t* v, @@ -13008,7 +13118,9 @@ static ray_t* insert_parted_rows(ray_t* tbl, ray_t* key, ray_t* rows) { ray_t** segs = (ray_t**)ray_data(wrapper); int8_t base = (int8_t)RAY_PARTED_BASETYPE(wrapper->type); ray_t* old_seg = new_partition ? NULL : segs[v.nparts - 1]; - ray_t* new_seg = base == RAY_SYM + ray_t* new_seg = base == RAY_LIST + ? build_parted_list_segment(old_seg, old_len, pv[c], batch) + : base == RAY_SYM ? build_parted_sym_skeleton(&v, old_seg, old_len, batch) : build_parted_nonsym_segment(base, old_seg, old_len, parted_wrapper_metadata(wrapper, active), @@ -13494,6 +13606,19 @@ ray_t* ray_insert(ray_t** args, int64_t n) { if (ct == RAY_LIST && ray_len(orig_col) == 0) ct = typeless_col_type(row_elems[c]); + if (ct == RAY_LIST) { + ray_t* new_col = append_boxed_table_col( + orig_col, row_elems[c], tbl_row_list != NULL); + if (!new_col || RAY_IS_ERR(new_col)) { + ray_release(result); + return new_col ? new_col : ray_error("oom", NULL); + } + result = ray_table_add_col(result, col_name, new_col); + ray_release(new_col); + if (!result || RAY_IS_ERR(result)) return result; + continue; + } + ray_t* new_col = ray_vec_new(ct, nrows + 1); if (RAY_IS_ERR(new_col)) { ray_release(result); return new_col; } diff --git a/src/store/col.c b/src/store/col.c index 2d1d04d1e..7f0c17dbf 100644 --- a/src/store/col.c +++ b/src/store/col.c @@ -28,6 +28,7 @@ #include "store/fileio.h" #include "table/sym.h" #include "table/domain.h" +#include "table/dict.h" #include "ops/idxop.h" #include "vec/str.h" #include "lang/format.h" @@ -155,6 +156,52 @@ static bool is_serializable_type(int8_t t) { } } +/* Mirror col_write_recursive without touching a FILE. This is deliberately + * structural rather than size-estimating: the save path can still report I/O + * or OOM later, but deterministic unsupported/corrupt object graphs are + * rejected before a splayed overwrite replaces any live column. */ +static ray_err_t col_preflight_recursive(ray_t* obj) { + if (!obj || RAY_IS_ERR(obj)) return RAY_ERR_TYPE; + int8_t type = obj->type; + if (type < 0 || is_serializable_type(type)) return RAY_OK; + + if (type == RAY_LIST) { + ray_t** slots = (ray_t**)ray_data(obj); + for (int64_t i = 0; i < obj->len; i++) { + ray_err_t err = col_preflight_recursive(slots[i]); + if (err != RAY_OK) return err; + } + return RAY_OK; + } + + if (type == RAY_TABLE) { + int64_t ncols = ray_table_ncols(obj); + for (int64_t c = 0; c < ncols; c++) { + ray_err_t err = col_preflight_recursive( + ray_table_get_col_idx(obj, c)); + if (err != RAY_OK) return err; + } + return RAY_OK; + } + + if (type == RAY_DICT) { + ray_t* keys = ray_dict_keys(obj); + ray_t* vals = ray_dict_vals(obj); + ray_err_t err = col_preflight_recursive(keys); + return err == RAY_OK ? col_preflight_recursive(vals) : err; + } + + return RAY_ERR_NYI; +} + +ray_err_t ray_col_save_preflight(ray_t* vec) { + if (!vec || RAY_IS_ERR(vec)) return RAY_ERR_TYPE; + if (is_serializable_type(vec->type)) return RAY_OK; + if (vec->type == RAY_LIST || vec->type == RAY_TABLE) + return col_preflight_recursive(vec); + return RAY_ERR_NYI; +} + /* -------------------------------------------------------------------------- * String list detection: RAY_LIST whose elements are all -RAY_STR * -------------------------------------------------------------------------- */ @@ -359,6 +406,13 @@ static ray_err_t col_write_recursive(ray_t* obj, FILE* f) { return RAY_OK; } + if (type == RAY_DICT) { + ray_t* keys = ray_dict_keys(obj); + ray_t* vals = ray_dict_vals(obj); + ray_err_t err = col_write_recursive(keys, f); + return err == RAY_OK ? col_write_recursive(vals, f) : err; + } + return RAY_ERR_NYI; } @@ -538,6 +592,17 @@ static ray_t* col_read_recursive(const uint8_t** pp, size_t* remaining) { return tbl; } + if (type == RAY_DICT) { + ray_t* keys = col_read_recursive(pp, remaining); + if (!keys || RAY_IS_ERR(keys)) return keys; + ray_t* vals = col_read_recursive(pp, remaining); + if (!vals || RAY_IS_ERR(vals)) { + ray_release(keys); + return vals; + } + return ray_dict_new(keys, vals); /* consumes keys + vals */ + } + return ray_error("nyi", NULL); } diff --git a/src/store/col.h b/src/store/col.h index 2167b4c82..615ce5390 100644 --- a/src/store/col.h +++ b/src/store/col.h @@ -85,6 +85,10 @@ static inline ray_err_t ray_col_check_format(const ray_t* header) { * loads attach that symfile's domain (sym-domain architecture spec). */ ray_err_t ray_col_save(ray_t* vec, const char* path); ray_err_t ray_col_save_bulk(ray_t* vec, const char* path); +/* Validate the complete object graph accepted by ray_col_save without + * opening or modifying a file. Splayed saves use this before mutating a + * symfile or any already-committed column generation. */ +ray_err_t ray_col_save_preflight(ray_t* vec); ray_t* ray_col_load(const char* path); ray_t* ray_col_mmap(const char* path); diff --git a/src/store/splay.c b/src/store/splay.c index 79d19c3ea..8e1acd5bc 100644 --- a/src/store/splay.c +++ b/src/store/splay.c @@ -82,6 +82,34 @@ static bool table_has_col_named(ray_t* tbl, const char* name, size_t len) { return false; } +static bool splay_col_name_safe(const char* name, size_t name_len) { + return name_len > 0 && name[0] != '.' && + !memchr(name, '/', name_len) && + !memchr(name, '\\', name_len) && + !memchr(name, '\0', name_len); +} + +static ray_err_t splay_validate_persisted_names(ray_t* tbl) { + int64_t nc = ray_table_ncols(tbl); + for (int64_t c = 0; c < nc; c++) { + ray_t* a = ray_sym_str(ray_table_col_name(tbl, c)); + 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; + 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 (alen == blen && memcmp(an, bn, alen) == 0) + return RAY_ERR_DOMAIN; + } + } + return RAY_OK; +} + /* Remove regular files in `dir` that are not part of the just-written * table: not a dotfile (".d", ".sym", ".sym.lk"), not a current column. * Runs after the .d commit so a stale wider-schema file can never shadow @@ -119,6 +147,20 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa if (!tbl || RAY_IS_ERR(tbl)) return RAY_ERR_TYPE; if (!dir) return RAY_ERR_IO; + ray_err_t name_err = splay_validate_persisted_names(tbl); + if (name_err != RAY_OK) return name_err; + + /* Validate every column graph before mkdir, sym-domain growth, or the + * first per-column atomic rename. Without this pass, an unsupported + * value in a later recursive LIST cell can return NYI after earlier + * columns have already replaced an existing committed generation. */ + int64_t preflight_ncols = ray_table_ncols(tbl); + for (int64_t c = 0; c < preflight_ncols; c++) { + ray_t* col = ray_table_get_col_idx(tbl, c); + ray_err_t err = ray_col_save_preflight(col); + if (err != RAY_OK) return err; + } + /* Symfile/column collision guard. A column is written as `dir/`; * the symfile (and its `.lk` lock) is written at `sym_path`. A * column whose file lands on the symfile path — or its lock path — @@ -237,9 +279,7 @@ 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 (name_len == 0 || name[0] == '.' || - memchr(name, '/', name_len) || memchr(name, '\\', name_len) || - memchr(name, '\0', name_len)) + if (!splay_col_name_safe(name, name_len)) continue; /* unsafe name: no file, no .d entry */ char path[1024]; @@ -255,8 +295,9 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa : (durable ? ray_col_save(col, path) : ray_col_save_bulk(col, path)); if (err != RAY_OK) { - /* No .d written yet: the dir stays in its previous committed - * state (old .d) or uncommitted state (no .d) — never torn. */ + /* No new .d is written. Preflight prevents deterministic format + * failures here; an I/O error or crash can still leave an + * existing directory with mixed-generation column files. */ ray_release(schema); if (dom) ray_sym_domain_release(dom); return err; @@ -359,9 +400,7 @@ static ray_t* splay_load_dom_impl(const char* dir, ray_sym_domain_t* dom, /* Reject names with path separators, traversal, or starting with '.' * — these indicate a corrupt/hand-tampered .d. */ - if (name_len == 0 || name[0] == '.' || - memchr(name, '/', name_len) || memchr(name, '\\', name_len) || - memchr(name, '\0', name_len)) { + if (!splay_col_name_safe(name, name_len)) { ray_release(schema); ray_release(tbl); return ray_error("corrupt", diff --git a/test/rfl/ops/builtins_branch_cov.rfl b/test/rfl/ops/builtins_branch_cov.rfl index a06a9987a..241477e9a 100644 --- a/test/rfl/ops/builtins_branch_cov.rfl +++ b/test/rfl/ops/builtins_branch_cov.rfl @@ -325,6 +325,47 @@ (type (as 'TIMESTAMP "2024.01.15D12:30:45.000000000")) -- 'timestamp (as 'TIMESTAMP "2024.01.15D12:30:45.000000000") -- 2024.01.15D12:30:45.000000000 +;; TIMESTAMP STR malformed input must be REJECTED, not silently normalized. +;; The parser walks a bounded cursor over +;; YYYYMMDD [ (T| |D) HH:MM[:SS][.frac] [Z|(+|-)HH[:]?MM] ] +;; and must consume the whole string — a partial match or trailing garbage +;; that used to be ignored silently corrupts the value. +;; Bad date/time separator (dropped the time, returned midnight): +(as 'TIMESTAMP "2024-01-02x01:02:03") !- domain +(as 'TIMESTAMP "2024-01-02abc") !- domain +;; Out-of-range time component (used to roll into the next day): +(as 'TIMESTAMP "2024-01-02T25:02:03") !- domain +(as 'TIMESTAMP "2024-01-02T12:99:03") !- domain +;; Trailing garbage after HH:MM / HH:MM:SS / fraction / 'Z': +(as 'TIMESTAMP "2024-01-02T12:34junk") !- domain +(as 'TIMESTAMP "2024-01-02T12:34:03junk") !- domain +(as 'TIMESTAMP "2024-01-02T12:34:03Zjunk") !- domain +(as 'TIMESTAMP "2024-01-02T12:34:03.5junk") !- domain +;; Partial / dangling component: +(as 'TIMESTAMP "2024-01-02T12:34:") !- domain +(as 'TIMESTAMP "2024-01-02T12:34:03.") !- domain +;; Out-of-range timezone offset: +(as 'TIMESTAMP "2024-01-02T12:34:03+99:99") !- domain +;; Timezone minutes are mandatory: grammar is HH[:]?MM, not bare HH. +(as 'TIMESTAMP "2024-01-02T12:34:03+12") !- domain +(as 'TIMESTAMP "2024-01-02T12:34:03+12:") !- domain +;; Inconsistent / malformed date separator and short fields: +(as 'TIMESTAMP "2024-01.02T00:00:00") !- domain +(as 'TIMESTAMP "2024-1-2T00:00:00") !- domain +;; Calendar dates must be valid for the selected month/leap year. +(as 'TIMESTAMP "2024-02-31") !- domain +(as 'TIMESTAMP "2023-02-29") !- domain +(as 'TIMESTAMP "2024-04-31") !- domain +;; Reject values outside int64 nanosecond timestamp range before overflow. +(as 'TIMESTAMP "9999-12-31") !- domain +;; Bare date (no time) is valid and yields midnight. +(as 'TIMESTAMP "2024-01-02") -- 2024.01.02D00:00:00.000000000 +(as 'TIMESTAMP "2024-02-29") -- 2024.02.29D00:00:00.000000000 +;; Space separator, HH:MM without seconds, and a tz offset are all accepted. +(as 'TIMESTAMP "2024-01-02 01:02:03") -- 2024.01.02D01:02:03.000000000 +(as 'TIMESTAMP "2024-01-02T12:34") -- 2024.01.02D12:34:00.000000000 +(as 'TIMESTAMP "2004-10-21 12:00:00.010-23:00") -- 2004.10.22D11:00:00.010000000 + ;; --- Cast to GUID --- (type (as 'GUID "01234567-89ab-cdef-0123-456789abcdef")) -- 'guid (as 'STR (as 'GUID "01234567-89ab-cdef-0123-456789abcdef")) -- "01234567-89ab-cdef-0123-456789abcdef" diff --git a/test/rfl/ops/pivot_coverage.rfl b/test/rfl/ops/pivot_coverage.rfl index b5d2ea6c7..a3e27fdc3 100644 --- a/test/rfl/ops/pivot_coverage.rfl +++ b/test/rfl/ops/pivot_coverage.rfl @@ -36,31 +36,25 @@ (set RTTS (at (select {t: (if x ts ts2) from: TTS}) 't)) (count RTTS) -- 3 ;; Value-check: x=[t,f,t] picks ts[0]=100, ts2[1]=20, ts[2]=300. -(at RTTS 0) -- 100 -(at RTTS 1) -- 20 -(at RTTS 2) -- 300 +(type RTTS) -- 'TIMESTAMP +(as 'I64 RTTS) -- [100 20 300] ;; ── 1d. DATE output branch (4-byte temporal) ─────────────────────── (set TDate (table [x d] (list [1 2 3 4] [2024.01.01 2024.01.02 2024.01.03 2024.01.04]))) -;; if x>2 use d else 2024.01.01; dates as epoch-day I32 +;; if x>2 use d else 2024.01.01; result remains DATE. (set RTDate (at (select {r: (if (> x 2) d 2024.01.01) from: TDate}) 'r)) (count RTDate) -- 4 -;; Value-check: cond=(x>2)=[f,f,t,t] → [01,01,03,04] as epoch-days -;; (2024.01.01=8766, 2024.01.03=8768, 2024.01.04=8769). -(at RTDate 0) -- 8766 -(at RTDate 1) -- 8766 -(at RTDate 2) -- 8768 -(at RTDate 3) -- 8769 +;; Value-check: cond=(x>2)=[f,f,t,t] → [01,01,03,04]. +(type RTDate) -- 'DATE +RTDate -- [2024.01.01 2024.01.01 2024.01.03 2024.01.04] ;; ── 1e. TIME output branch (4-byte temporal) ─────────────────────── (set TTime (table [x t] (list [1 2 3] [09:30:00.000 10:00:00.000 11:00:00.000]))) (set RTTime (at (select {r: (if (> x 1) t 09:30:00.000) from: TTime}) 'r)) (count RTTime) -- 3 -;; Value-check: cond=(x>1)=[f,t,t] → [09:30,10:00,11:00] as millis -;; (34200000, 36000000, 39600000). -(at RTTime 0) -- 34200000 -(at RTTime 1) -- 36000000 -(at RTTime 2) -- 39600000 +;; Value-check: cond=(x>1)=[f,t,t] → [09:30,10:00,11:00]. +(type RTTime) -- 'TIME +RTTime -- [09:30:00.000 10:00:00.000 11:00:00.000] ;; ── 1e2. I16 output branch ───────────────────────────────────────── ;; A table with two I16 columns; the if projection produces I16 output. @@ -646,37 +640,26 @@ ;; ==================================================================== ;; Section 29: exec_if — TIMESTAMP/DATE/TIME output branches -;; BUG: These branches (lines 189-209) are UNREACHABLE. -;; promote(RAY_TIMESTAMP, RAY_TIMESTAMP) returns RAY_I64 -;; promote(RAY_DATE, RAY_DATE) returns RAY_I32 -;; promote(RAY_TIME, RAY_TIME) returns RAY_I32 -;; so exec_if never enters the TIMESTAMP/DATE/TIME arms. -;; These arms handle correct temporal semantics but are dead. -;; -;; Verify the current (demoted) behavior: +;; IF uses temporal-preserving promotion for matching branch types. ;; ==================================================================== -;; TIMESTAMP if → actually produces I64 (not TIMESTAMP) +;; TIMESTAMP if preserves TIMESTAMP output. (set TTSdead (table [x ts1 ts2] (list [true false] (as 'TIMESTAMP [100 200]) (as 'TIMESTAMP [10 20])))) (set RTSdead (at (select {t: (if x ts1 ts2) from: TTSdead}) 't)) (count RTSdead) -- 2 -;; Value-check: x=[t,f] picks ts1[0]=100, ts2[1]=20 (demoted to I64 nanos). -(at RTSdead 0) -- 100 -(at RTSdead 1) -- 20 +(type RTSdead) -- 'TIMESTAMP +(as 'I64 RTSdead) -- [100 20] -;; DATE if → actually produces I32 (not DATE) +;; DATE if preserves DATE output. (set TDatedead (table [x d1 d2] (list [true false] [2024.01.01 2024.01.02] [2023.01.01 2023.01.02]))) (set RDatedead (at (select {d: (if x d1 d2) from: TDatedead}) 'd)) (count RDatedead) -- 2 -;; Value-check: x=[t,f] picks d1[0]=2024.01.01, d2[1]=2023.01.02 (epoch-day I32). -;; 2024.01.01 epoch-day = 8766; 2023.01.02 = 8766-365+1 = 8402. -(at RDatedead 0) -- 8766 -(at RDatedead 1) -- 8402 +(type RDatedead) -- 'DATE +RDatedead -- [2024.01.01 2023.01.02] -;; TIME if → actually produces I32 (not TIME) +;; TIME if preserves TIME output. (set TTimedead (table [x t1 t2] (list [true false] [09:30:00.000 10:00:00.000] [08:00:00.000 11:00:00.000]))) (set RTimedead (at (select {t: (if x t1 t2) from: TTimedead}) 't)) (count RTimedead) -- 2 -;; Value-check: x=[t,f] picks t1[0]=09:30 (34200000ms), t2[1]=11:00 (39600000ms). -(at RTimedead 0) -- 34200000 -(at RTimedead 1) -- 39600000 +(type RTimedead) -- 'TIME +RTimedead -- [09:30:00.000 11:00:00.000] diff --git a/test/rfl/query/query_select_fastpath_coverage.rfl b/test/rfl/query/query_select_fastpath_coverage.rfl index a281eaa11..76955bbc9 100644 --- a/test/rfl/query/query_select_fastpath_coverage.rfl +++ b/test/rfl/query/query_select_fastpath_coverage.rfl @@ -283,6 +283,7 @@ (sum (at (select {r: (if (> v 0) v (sqrt s)) from: Tiflazy}) 'r)) -- 15 (sum (at (select {r: (if (< v 0) (sqrt s) v) from: Tiflazy}) 'r)) -- 15 (set Tifdate (table [v s d] (list [-1 1 2 -2] (as 'STR (list "2024.01.01" "bad" "bad" "2024.01.03")) [2020.01.01 2020.01.02 2020.01.03 2020.01.04]))) +(type (at (select {r: (if (< v 0) (as 'DATE s) d) from: Tifdate}) 'r)) -- 'DATE (at (select {r: (if (< v 0) (as 'DATE s) d) from: Tifdate}) 'r) -- [2024.01.01 2020.01.02 2020.01.03 2024.01.03] ;; do in DAG: evaluates last expression diff --git a/test/rfl/system/splayed.rfl b/test/rfl/system/splayed.rfl index d9e6b9394..e7f8a7037 100644 --- a/test/rfl/system/splayed.rfl +++ b/test/rfl/system/splayed.rfl @@ -21,6 +21,16 @@ (at R-Small 'a) -- (at T-Small 'a) (at R-Small 'b) -- (at T-Small 'b) +;; ────────────── duplicate persisted names are rejected ────────────── +;; Splayed stores one file per column name. A table with duplicate column +;; names used to write both columns to the same path, so the later column +;; overwrote the earlier one and reload duplicated the later data. +(.sys.exec "rm -rf /tmp/rfl_splayed_dup") +(set J-L (table [sym qty px] (list ['A 'B] [10 20] [1.0 2.0]))) +(set J-R (table [sym qty venue] (list ['A 'C] [100 300] ['X 'Z]))) +(.db.splayed.set "/tmp/rfl_splayed_dup/join/" (full-join [sym] J-L J-R)) !- domain +(.db.splayed.set "/tmp/rfl_splayed_dup/csv/" (table [a a] (list [1 2] [10 20]))) !- domain + ;; ────────────── morsel-boundary table (1024 rows) ────────────── (set T-1024 (table [n] (list (til 1024)))) (.db.splayed.set "/tmp/rfl_splayed_1024/" T-1024) diff --git a/test/test_lang.c b/test/test_lang.c index 3247ae100..fe235f6e8 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -2965,6 +2965,37 @@ static test_result_t test_eval_insert_list_append(void) { PASS(); } +/* ---- Test: insert into a table with a boxed LIST column --------------- */ +static test_result_t test_eval_insert_list_column(void) { + const char* setup = + "(set nested_t (table ['k 'sched] (list ['a 'b] " + " (list (list (as 'i64 (list 0)) (as 'f64 (list 5))) " + " (list (as 'i64 (list 0 250000)) " + " (as 'f64 (list 15 10)))))))"; + ray_t* r = ray_eval_str(setup); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + + /* A table payload is a batch: copy each boxed cell with a retain. */ + ASSERT_EQ("(insert 'nested_t nested_t)", "'nested_t"); + ASSERT_EQ("(count nested_t)", "4"); + ASSERT_EQ("(at nested_t 'sched)", + "(list (list [0] [5.0]) " + " (list [0 250000] [15.0 10.0]) " + " (list [0] [5.0]) " + " (list [0 250000] [15.0 10.0]))"); + + /* A positional row keeps its nested LIST as one cell, not a batch. */ + ASSERT_EQ("(insert 'nested_t " + " (list 'c (list [1 2] [3.0 4.0])))", + "'nested_t"); + ASSERT_EQ("(count nested_t)", "5"); + ASSERT_EQ("(get (at nested_t 'sched) 4)", + "(list [1 2] [3.0 4.0])"); + PASS(); +} + /* ---- Test: insert positional (arity 3, scalar idx) ---- */ static test_result_t test_eval_insert_vec_positional(void) { /* Head, middle, tail (== append) */ @@ -4287,6 +4318,25 @@ static test_result_t test_eval_parted_list_column_impl(const char* root) { /* The parted view itself must stay usable after the reads. */ ASSERT_EQ("(at pl 'acct)", "['a 'b 'a 'b]"); + + /* Append two boxed rows to the active partition. The historical LIST + * segment stays mmap-backed while the active segment becomes a retained + * heap snapshot. */ + ASSERT_EQ("(insert 'pl 2024.01.02 " + " (table ['acct 'brk] " + " (list ['c 'd] (list [1 2] [3 4 5]))))", + "'pl"); + ASSERT_EQ("(count pl)", "6"); + ASSERT_EQ("(at pl 'brk)", + "(list [0 250000] [0 250000 5000000] " + " [0 250000] [0 250000 5000000] [1 2] [3 4 5])"); + + /* A greater key creates a new boxed heap segment. */ + ASSERT_EQ("(insert 'pl 2024.01.03 " + " (table ['acct 'brk] (list ['e] (list [7 8]))))", + "'pl"); + ASSERT_EQ("(count pl)", "7"); + ASSERT_EQ("(get (at pl 'brk) 6)", "[7 8]"); PASS(); } @@ -6327,6 +6377,82 @@ static test_result_t test_eval_restricted_fn(void) { PASS(); } +/* Evaluate one expression with the same VM-wide flag used by restricted IPC. + * Restore the caller's state before inspecting the result so a failed + * assertion cannot leak restricted mode into the next test. */ +static ray_t* eval_restricted_expr(const char* expr) { + bool previous = ray_eval_get_restricted(); + ray_eval_set_restricted(true); + ray_t* result = ray_eval_str(expr); + ray_eval_set_restricted(previous); + return result; +} + +static bool restricted_expr_returns_access(const char* expr) { + ray_t* result = eval_restricted_expr(expr); + bool access = result && RAY_IS_ERR(result) && + ray_err_code(result) && + strcmp(ray_err_code(result), "access") == 0; + if (result) { + if (RAY_IS_ERR(result)) ray_error_free(result); + else ray_release(result); + } + return access; +} + +/* Restricted builtins must be rejected at the actual invocation boundary, + * including compiled lambda bytecode. Invalid filesystem arguments are + * deliberate: before the fix they return os/type instead of access without + * performing a useful side effect. */ +static test_result_t test_eval_restricted_lambda_bypass(void) { + /* OP_CALL1: unary restricted builtin. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "((fn [x] (.sys.exec \"true\")) 0)")); + + /* OP_CALL2: binary restricted builtin. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "((fn [x] (write \"/__rayforce_issue_363_missing__/file\" \"x\")) 0)")); + + /* OP_CALLN: variadic restricted builtin. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "((fn [x] (.db.splayed.set 1 2)) 0)")); + + /* OP_STOREGLOBAL: the compiler lowers `set` directly instead of calling + * the registered restricted special form. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "((fn [x] (set '__rf_issue_363_injected 1)) 0)")); + + /* The wide-constant opcode is a separate VM handler and must enforce the + * same rule. Fill the constant pool before compiling `set` so its name + * index exceeds one byte and OP_STOREGLOBAL_W is emitted. */ + char wide_set[4096]; + size_t used = (size_t)snprintf(wide_set, sizeof(wide_set), + "((fn [x] (do "); + for (int i = 0; i < 260 && used < sizeof(wide_set); i++) + used += (size_t)snprintf(wide_set + used, sizeof(wide_set) - used, + "%d ", i); + if (used < sizeof(wide_set)) + used += (size_t)snprintf(wide_set + used, sizeof(wide_set) - used, + "(set '__rf_issue_363_wide 1))) 0)"); + TEST_ASSERT(used < sizeof(wide_set), "wide restricted set expression fits buffer"); + TEST_ASSERT_TRUE(restricted_expr_returns_access(wide_set)); + + /* Nested bytecode and dynamic callable dispatch stay restricted too. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "((fn [x] ((fn [y] (read \"/__rayforce_issue_363_missing__/file\")) x)) 0)")); + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "((fn [f] (f \"/__rayforce_issue_363_missing__/file\")) read)")); + + /* Pure computation remains available in read-only mode. */ + ray_t* allowed = eval_restricted_expr("((fn [x] (+ x 1)) 2)"); + TEST_ASSERT_NOT_NULL(allowed); + TEST_ASSERT_FALSE(RAY_IS_ERR(allowed)); + TEST_ASSERT_EQ_I(allowed->type, -RAY_I64); + TEST_ASSERT_EQ_I(allowed->i64, 3); + ray_release(allowed); + PASS(); +} + /* --- self-recursive lambda via recursion (tests op_calls path) --- */ static test_result_t test_eval_self_recursion_direct(void) { /* Direct recursion using named function — compiler may use op_calls */ @@ -8700,6 +8826,7 @@ const test_entry_t lang_entries[] = { { "lang/eval/insert", test_eval_insert, lang_setup, lang_teardown }, { "lang/eval/insert_vec_append", test_eval_insert_vec_append, lang_setup, lang_teardown }, { "lang/eval/insert_list_append", test_eval_insert_list_append, lang_setup, lang_teardown }, + { "lang/eval/insert_list_column", test_eval_insert_list_column, lang_setup, lang_teardown }, { "lang/eval/insert_vec_positional", test_eval_insert_vec_positional, lang_setup, lang_teardown }, { "lang/eval/insert_list_positional", test_eval_insert_list_positional, lang_setup, lang_teardown }, { "lang/eval/insert_positional_multi", test_eval_insert_positional_multi, lang_setup, lang_teardown }, @@ -8853,6 +8980,7 @@ const test_entry_t lang_entries[] = { { "lang/eval/table_list_col_f64_promote", test_eval_table_list_col_f64_i64_promote, lang_setup, lang_teardown }, { "lang/eval/cond_and_branches", test_eval_cond_and_branches, lang_setup, lang_teardown }, { "lang/eval/restricted_fn", test_eval_restricted_fn, lang_setup, lang_teardown }, + { "lang/eval/restricted_lambda_bypass", test_eval_restricted_lambda_bypass, lang_setup, lang_teardown }, { "lang/eval/self_recursion_direct", test_eval_self_recursion_direct, lang_setup, lang_teardown }, { "lang/eval/nested_lambda_calls", test_eval_nested_lambda_calls, lang_setup, lang_teardown }, { "lang/eval/vm_empty_ret", test_eval_vm_empty_ret, lang_setup, lang_teardown }, diff --git a/test/test_pool.c b/test/test_pool.c index 81e40261e..1dfeb0b39 100644 --- a/test/test_pool.c +++ b/test/test_pool.c @@ -31,17 +31,20 @@ #include "core/pool.h" #include "core/poll.h" #include "core/platform.h" +#include "core/timer.h" #include "mem/heap.h" #include "ops/ops.h" #include #include #include -#if defined(__linux__) +#if defined(__linux__) || defined(__APPLE__) #include #include #include +#endif +#if defined(__linux__) static void epoll_sleep_ms(long ms) { struct timespec ts = { .tv_sec = ms / 1000, .tv_nsec = (ms % 1000) * 1000000L }; nanosleep(&ts, NULL); @@ -994,6 +997,82 @@ static test_result_t test_dispatch_n_exact_cap(void) { PASS(); } +/* ========================================================================== + * Bounded poll-step tests + * ========================================================================== */ + +#if defined(__linux__) || defined(__APPLE__) + +typedef struct { + int calls; +} poll_run_for_ctx_t; + +static int64_t poll_run_for_recv(int64_t fd, uint8_t* buf, int64_t len) { + return (int64_t)read((int)fd, buf, (size_t)len); +} + +static ray_t* poll_run_for_read(ray_poll_t* poll, ray_selector_t* sel) { + poll_run_for_ctx_t* ctx = (poll_run_for_ctx_t*)sel->data; + ctx->calls++; + ray_poll_deregister(poll, sel->id); + return NULL; +} + +static test_result_t test_poll_run_for_zero_drains_ready_event(void) { + ray_poll_t* poll = ray_poll_create(); + TEST_ASSERT_NOT_NULL(poll); + + int pfd[2]; + TEST_ASSERT_EQ_I(pipe(pfd), 0); + + poll_run_for_ctx_t ctx = {0}; + ray_poll_reg_t reg; + memset(®, 0, sizeof(reg)); + reg.fd = pfd[0]; + reg.type = RAY_SEL_SOCKET; + reg.data = &ctx; + reg.recv_fn = poll_run_for_recv; + reg.read_fn = poll_run_for_read; + + int64_t id = ray_poll_register(poll, ®); + TEST_ASSERT_TRUE(id >= 0); + ray_selector_t* sel = ray_poll_get(poll, id); + TEST_ASSERT_NOT_NULL(sel); + ray_poll_rx_request(poll, sel, 1); + + TEST_ASSERT_EQ_I(write(pfd[1], "x", 1), 1); + TEST_ASSERT_EQ_I(ray_poll_run_for(poll, 0), 0); + TEST_ASSERT_EQ_I(ctx.calls, 1); + + close(pfd[0]); + close(pfd[1]); + ray_poll_destroy(poll); + PASS(); +} + +static test_result_t test_poll_run_for_positive_timeout(void) { + TEST_ASSERT_EQ_I(ray_poll_run_for(NULL, 10), -1); + + ray_poll_t* poll = ray_poll_create(); + TEST_ASSERT_NOT_NULL(poll); + + int64_t before = ray_time_now_ms(); + TEST_ASSERT_EQ_I(ray_poll_run_for(poll, 25), 0); + int64_t elapsed = ray_time_now_ms() - before; + + TEST_ASSERT_FMT(elapsed >= 15, + "bounded poll returned too early (%lld ms)", + (long long)elapsed); + TEST_ASSERT_FMT(elapsed < 500, + "bounded poll exceeded its budget (%lld ms)", + (long long)elapsed); + + ray_poll_destroy(poll); + PASS(); +} + +#endif + /* ========================================================================== * epoll.c region-coverage tests * @@ -1258,6 +1337,10 @@ const test_entry_t pool_entries[] = { { "pool/destroy_when_uninit", test_destroy_when_uninit, NULL, NULL }, { "pool/dispatch_n_multi_grow", test_dispatch_n_multi_grow, NULL, NULL }, { "pool/dispatch_n_exact_cap", test_dispatch_n_exact_cap, NULL, NULL }, +#if defined(__linux__) || defined(__APPLE__) + { "pool/poll_run_for_zero_drains_ready_event", test_poll_run_for_zero_drains_ready_event, NULL, NULL }, + { "pool/poll_run_for_positive_timeout", test_poll_run_for_positive_timeout, NULL, NULL }, +#endif #if defined(__linux__) { "pool/epoll_sel_cap_growth", test_epoll_sel_cap_growth, NULL, NULL }, { "pool/epoll_hup_branch", test_epoll_hup_branch, NULL, NULL }, @@ -1265,4 +1348,3 @@ const test_entry_t pool_entries[] = { #endif { NULL, NULL, NULL, NULL }, }; - diff --git a/test/test_public_api.c b/test/test_public_api.c index 9e7b6a548..16537dde1 100644 --- a/test/test_public_api.c +++ b/test/test_public_api.c @@ -58,6 +58,25 @@ static test_result_t test_public_ipc_client_symbols(void) { PASS(); } +static test_result_t test_public_poll_symbols(void) { + ray_poll_t* (*create_fn)(void) = ray_poll_create; + void (*destroy_fn)(ray_poll_t*) = ray_poll_destroy; + int64_t (*run_fn)(ray_poll_t*) = ray_poll_run; + int64_t (*run_for_fn)(ray_poll_t*, int) = ray_poll_run_for; + void (*exit_fn)(ray_poll_t*, int64_t) = ray_poll_exit; + void (*set_fn)(void*) = ray_runtime_set_poll; + void* (*get_fn)(void) = ray_runtime_get_poll; + + TEST_ASSERT_NOT_NULL((void*)create_fn); + TEST_ASSERT_NOT_NULL((void*)destroy_fn); + TEST_ASSERT_NOT_NULL((void*)run_fn); + TEST_ASSERT_NOT_NULL((void*)run_for_fn); + TEST_ASSERT_NOT_NULL((void*)exit_fn); + TEST_ASSERT_NOT_NULL((void*)set_fn); + TEST_ASSERT_NOT_NULL((void*)get_fn); + PASS(); +} + static test_result_t test_public_query_and_format_symbols(void) { ray_t* (*select_fn)(ray_t**, int64_t) = ray_select; ray_t* (*update_fn)(ray_t**, int64_t) = ray_update; @@ -661,6 +680,7 @@ static test_result_t test_public_nullability_matrix(void) { const test_entry_t public_api_entries[] = { { "public/ipc_client_symbols", test_public_ipc_client_symbols, NULL, NULL }, + { "public/poll_symbols", test_public_poll_symbols, NULL, NULL }, { "public/query_and_format_symbols", test_public_query_and_format_symbols, NULL, NULL }, { "public/obj_type_atom_i64", test_public_obj_type_atom_i64, public_api_setup, public_api_teardown }, diff --git a/test/test_repl.c b/test/test_repl.c index ee5cdeb36..f064c6042 100644 --- a/test/test_repl.c +++ b/test/test_repl.c @@ -2788,6 +2788,24 @@ static bool pty_read_until(int fd, const char* needle, int timeout_ms, return false; } +static bool pty_write_all(int fd, const void* data, size_t len, int timeout_ms) { + const char* p = data; + size_t off = 0; + int waited = 0; + while (off < len) { + ssize_t n = write(fd, p + off, len - off); + if (n > 0) { + off += (size_t)n; + continue; + } + if (n < 0 && errno != EAGAIN && errno != EINTR) return false; + if (waited >= timeout_ms) return false; + usleep(10 * 1000); + waited += 10; + } + return true; +} + /* A literal Ctrl-C keypress must interrupt lazy/DAG materialization, not sit * in raw input until after the result prints. */ static int run_pty_ctrl_c_during_lazy_materialize(void) { @@ -2822,7 +2840,12 @@ static int run_pty_ctrl_c_during_lazy_materialize(void) { const char* preload_fmt = "(do (set l (til %d)) 0)\n"; char preload[96]; snprintf(preload, sizeof(preload), preload_fmt, N); - (void)write(master_fd, preload, strlen(preload)); + if (!pty_write_all(master_fd, preload, strlen(preload), 1000)) { + kill(pid, SIGKILL); + int s; waitpid(pid, &s, 0); + close(master_fd); + return -10; + } if (!pty_read_until(master_fd, "\r\n0\r\n", 30000, accum, sizeof(accum), &pos)) { kill(pid, SIGKILL); int s; waitpid(pid, &s, 0); @@ -2834,7 +2857,12 @@ static int run_pty_ctrl_c_during_lazy_materialize(void) { char expr[256]; snprintf(expr, sizeof(expr), "(do (println \"%s\") (deltas (+ l 1)))\n", marker); - (void)write(master_fd, expr, strlen(expr)); + if (!pty_write_all(master_fd, expr, strlen(expr), 1000)) { + kill(pid, SIGKILL); + int s; waitpid(pid, &s, 0); + close(master_fd); + return -11; + } if (!pty_read_until(master_fd, marker_line, 10000, accum, sizeof(accum), &pos)) { kill(pid, SIGKILL); int s; waitpid(pid, &s, 0); @@ -2844,15 +2872,24 @@ static int run_pty_ctrl_c_during_lazy_materialize(void) { /* The marker is emitted immediately before constructing the lazy result. * Send Ctrl-C as soon as it is observed: fixed sleeps race with faster - * materialization and can miss the interruptible window entirely. */ + * materialization and can miss the interruptible window entirely. A + * nonblocking PTY write can also fail transiently under load, so write all + * input robustly and resend the literal keypress until the REPL + * acknowledges it. Seeing the result first still fails the test, + * preventing a retry after materialization from hiding a real regression. */ const char ctrl_c = '\003'; - (void)write(master_fd, &ctrl_c, 1); + if (!pty_write_all(master_fd, &ctrl_c, 1, 1000)) { + kill(pid, SIGKILL); + int s; waitpid(pid, &s, 0); + close(master_fd); + return -12; + } bool saw_ctrl_c = false; bool result_before_ctrl_c = false; size_t ctrl_len = strlen("^C"); size_t res_len = strlen(expected_result); - for (int waited = 0; waited < 5000; waited += 10) { + for (int waited = 0; waited < 15000; waited += 10) { char buf[4096]; ssize_t n = read(master_fd, buf, sizeof(buf)); if (n > 0) { @@ -2876,6 +2913,10 @@ static int run_pty_ctrl_c_during_lazy_materialize(void) { } else if (n < 0 && errno != EAGAIN && errno != EINTR) { break; } + if (waited > 0 && waited % 250 == 0 + && !pty_write_all(master_fd, &ctrl_c, 1, 1000)) { + break; + } usleep(10 * 1000); } diff --git a/test/test_runtime.c b/test/test_runtime.c index a81f6261f..684a3fc07 100644 --- a/test/test_runtime.c +++ b/test/test_runtime.c @@ -716,6 +716,34 @@ static test_result_t test_syscov_time_timer_fires(void) { PASS(); } +/* The production poll driver must also service Rayfall timers while an + * embedder lends it the thread for a bounded slice. */ +static test_result_t test_poll_run_for_fires_timer(void) { + ray_poll_t* poll = (ray_poll_t*)ray_runtime_get_poll(); + TEST_ASSERT_NOT_NULL(poll); + + ray_t* setup_counter = ray_eval_str("(set bounded_timer_fired 0)"); + TEST_ASSERT_NOT_NULL(setup_counter); + TEST_ASSERT_FALSE(RAY_IS_ERR(setup_counter)); + ray_release(setup_counter); + + ray_t* setup_timer = ray_eval_str( + "(.time.timer.set 5 1 (fn [t] (set bounded_timer_fired 1)))"); + TEST_ASSERT_NOT_NULL(setup_timer); + TEST_ASSERT_FALSE(RAY_IS_ERR(setup_timer)); + ray_release(setup_timer); + + TEST_ASSERT_EQ_I(ray_poll_run_for(poll, 30), 0); + + ray_t* fired = ray_eval_str("bounded_timer_fired"); + TEST_ASSERT_NOT_NULL(fired); + TEST_ASSERT_FALSE(RAY_IS_ERR(fired)); + TEST_ASSERT_EQ_I(fired->type, -RAY_I64); + TEST_ASSERT_EQ_I(fired->i64, 1); + ray_release(fired); + PASS(); +} + /* ─── timer.c deep coverage (heap helpers + edge paths) ─────── * * The static heap helpers (heap_less, heap_swap, heap_up sift body, @@ -1173,6 +1201,7 @@ const test_entry_t runtime_entries[] = { { "runtime/syscov_time_now", test_syscov_time_now, sys_setup, sys_teardown }, { "runtime/syscov_time_timer_set_del", test_syscov_time_timer_set_del, sys_setup_with_poll, sys_teardown_with_poll }, { "runtime/syscov_time_timer_fires", test_syscov_time_timer_fires, sys_setup_with_poll, sys_teardown_with_poll }, + { "runtime/poll_run_for_fires_timer", test_poll_run_for_fires_timer, sys_setup_with_poll, sys_teardown_with_poll }, { "runtime/timer_heap_grow_past_initial_cap", test_timer_heap_grow_past_initial_cap, sys_setup_with_poll, sys_teardown_with_poll }, { "runtime/timer_next_deadline_ms", test_timer_next_deadline_ms, sys_setup_with_poll, sys_teardown_with_poll }, { "runtime/timer_heap_sift_paths", test_timer_heap_sift_paths, sys_setup_with_poll, sys_teardown_with_poll }, @@ -1194,4 +1223,3 @@ const test_entry_t runtime_entries[] = { { NULL, NULL, NULL, NULL }, }; - diff --git a/test/test_store.c b/test/test_store.c index 4edb0210b..38f373ccd 100644 --- a/test/test_store.c +++ b/test/test_store.c @@ -508,6 +508,114 @@ static test_result_t test_splay_short_strv_roundtrip(void) { PASS(); } +/* ---- test_splay_dict_column_roundtrip --------------------------------- */ +static test_result_t test_splay_dict_column_roundtrip(void) { + (void)!system("rm -rf " TMP_SPLAY_DIR); + + int64_t ids_raw[] = {1, 2}; + ray_t* ids = ray_vec_from_raw(RAY_I64, ids_raw, 2); + ray_t* sched = ray_list_new(2); + TEST_ASSERT_FALSE(RAY_IS_ERR(ids)); + TEST_ASSERT_FALSE(RAY_IS_ERR(sched)); + + int64_t k0_raw[] = {0}; + double v0_raw[] = {5.0}; + int64_t k1_raw[] = {0, 250000}; + double v1_raw[] = {15.0, 10.0}; + ray_t* d0 = ray_dict_new(ray_vec_from_raw(RAY_I64, k0_raw, 1), + ray_vec_from_raw(RAY_F64, v0_raw, 1)); + ray_t* d1 = ray_dict_new(ray_vec_from_raw(RAY_I64, k1_raw, 2), + ray_vec_from_raw(RAY_F64, v1_raw, 2)); + TEST_ASSERT_FALSE(RAY_IS_ERR(d0)); + TEST_ASSERT_FALSE(RAY_IS_ERR(d1)); + sched = ray_list_append(sched, d0); + sched = ray_list_append(sched, d1); + TEST_ASSERT_FALSE(RAY_IS_ERR(sched)); + ray_release(d0); + ray_release(d1); + + ray_t* tbl = ray_table_new(2); + int64_t id_id = ray_sym_intern("id", 2); + int64_t sched_id = ray_sym_intern("sched", 5); + tbl = ray_table_add_col(tbl, id_id, ids); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); + tbl = ray_table_add_col(tbl, sched_id, sched); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); + + TEST_ASSERT_EQ_I(ray_splay_save(tbl, TMP_SPLAY_DIR, NULL), RAY_OK); + ray_t* loaded = ray_read_splayed(TMP_SPLAY_DIR, NULL); + TEST_ASSERT_NOT_NULL(loaded); + TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); + ray_t* loaded_sched = ray_table_get_col(loaded, sched_id); + TEST_ASSERT_NOT_NULL(loaded_sched); + TEST_ASSERT_EQ_I(loaded_sched->type, RAY_LIST); + TEST_ASSERT_EQ_I(loaded_sched->len, 2); + + ray_t* ld0 = ray_list_get(loaded_sched, 0); + ray_t* ld1 = ray_list_get(loaded_sched, 1); + TEST_ASSERT_EQ_I(ld0->type, RAY_DICT); + TEST_ASSERT_EQ_I(ld1->type, RAY_DICT); + TEST_ASSERT_EQ_I(ray_dict_keys(ld0)->type, RAY_I64); + TEST_ASSERT_EQ_I(ray_dict_vals(ld1)->type, RAY_F64); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_dict_keys(ld1)))[1], 250000); + TEST_ASSERT(((double*)ray_data(ray_dict_vals(ld1)))[1] == 10.0, + "dict value roundtrip"); + + ray_release(loaded); + ray_release(tbl); + ray_release(ids); + ray_release(sched); + (void)!system("rm -rf " TMP_SPLAY_DIR); + PASS(); +} + +/* A deterministic unsupported column must be rejected before an earlier + * column can replace the committed generation. */ +static test_result_t test_splay_save_preflight_preserves_generation(void) { + (void)!system("rm -rf " TMP_SPLAY_DIR); + int64_t k_id = ray_sym_intern("k", 1); + int64_t v_id = ray_sym_intern("v", 1); + + int64_t old_k_raw[] = {1, 2}; + int64_t old_v_raw[] = {3, 4}; + ray_t* old_k = ray_vec_from_raw(RAY_I64, old_k_raw, 2); + ray_t* old_v = ray_vec_from_raw(RAY_I64, old_v_raw, 2); + ray_t* good = ray_table_new(2); + good = ray_table_add_col(good, k_id, old_k); + good = ray_table_add_col(good, v_id, old_v); + TEST_ASSERT_FALSE(RAY_IS_ERR(good)); + TEST_ASSERT_EQ_I(ray_splay_save(good, TMP_SPLAY_DIR, NULL), RAY_OK); + + int64_t new_k_raw[] = {9, 10}; + int64_t dk_raw[] = {1, 2}; + int64_t dv_raw[] = {11, 12}; + ray_t* new_k = ray_vec_from_raw(RAY_I64, new_k_raw, 2); + ray_t* unsupported = ray_dict_new(ray_vec_from_raw(RAY_I64, dk_raw, 2), + 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); + TEST_ASSERT_FALSE(RAY_IS_ERR(bad)); + TEST_ASSERT_EQ_I(ray_splay_save(bad, TMP_SPLAY_DIR, NULL), RAY_ERR_NYI); + + ray_t* loaded = ray_read_splayed(TMP_SPLAY_DIR, NULL); + TEST_ASSERT_NOT_NULL(loaded); + TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); + ray_t* loaded_k = ray_table_get_col(loaded, k_id); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(loaded_k))[0], 1); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(loaded_k))[1], 2); + + ray_release(loaded); + ray_release(bad); + ray_release(unsupported); + ray_release(new_k); + ray_release(good); + ray_release(old_v); + ray_release(old_k); + (void)!system("rm -rf " TMP_SPLAY_DIR); + PASS(); +} + /* ---- test_parted_nrows ------------------------------------------------- */ static test_result_t test_parted_nrows(void) { @@ -3619,6 +3727,28 @@ static test_result_t test_ipc_restricted(void) { TEST_ASSERT_TRUE(RAY_IS_ERR(r4)); ray_release(r4); + /* Entering compiled lambda bytecode must preserve the connection's + * restricted context. These are the request-level escapes from #363. */ + const char* q_lambda = + "((fn [x] (.sys.exec \"true\")) 0)"; + ray_t* msg5 = ray_str(q_lambda, strlen(q_lambda)); + ray_t* r5 = ray_ipc_send(h, msg5); + ray_release(msg5); + TEST_ASSERT_NOT_NULL(r5); + TEST_ASSERT_TRUE(RAY_IS_ERR(r5)); + TEST_ASSERT_STR_EQ(ray_err_code(r5), "access"); + ray_release(r5); + + const char* q_lambda_set = + "((fn [x] (set '__rf_issue_363_ipc_injected 1)) 0)"; + ray_t* msg6 = ray_str(q_lambda_set, strlen(q_lambda_set)); + ray_t* r6 = ray_ipc_send(h, msg6); + ray_release(msg6); + TEST_ASSERT_NOT_NULL(r6); + TEST_ASSERT_TRUE(RAY_IS_ERR(r6)); + TEST_ASSERT_STR_EQ(ray_err_code(r6), "access"); + ray_release(r6); + ray_ipc_close(h); srv.running = false; ray_thread_join(tid); @@ -4954,6 +5084,8 @@ const test_entry_t store_entries[] = { { "store/splay_open_roundtrip", test_splay_open_roundtrip, store_setup, store_teardown }, { "store/splay_str_column_roundtrip", test_splay_str_column_roundtrip, store_setup, store_teardown }, { "store/splay_short_strv_roundtrip", test_splay_short_strv_roundtrip, store_setup, store_teardown }, + { "store/splay_dict_column_roundtrip", test_splay_dict_column_roundtrip, store_setup, store_teardown }, + { "store/splay_save_preflight", test_splay_save_preflight_preserves_generation, store_setup, store_teardown }, { "store/parted_nrows", test_parted_nrows, store_setup, store_teardown }, { "store/table_nrows_parted", test_table_nrows_parted, store_setup, store_teardown }, { "store/parted_release", test_parted_release, store_setup, store_teardown },