diff --git a/docs/docs/language/syntax.md b/docs/docs/language/syntax.md index 4ff2a0fc4..8832fde8c 100644 --- a/docs/docs/language/syntax.md +++ b/docs/docs/language/syntax.md @@ -39,6 +39,8 @@ false ; boolean false Symbols are interned identifiers used for column names, dictionary keys, and categorical data. Prefix with a single quote to create a literal symbol. +A symbol literal runs over letters, digits, `_`, `.` and `-`. A symbol, keyword, name or number cannot be directly followed by a quote, a colon, or another name or number character: `['a:1]` is a parse error rather than the two symbols `a` and `1`, and `0Na` is not `0` followed by `Na`. A symbol that must contain a colon is built from a string, `(as 'symbol "a:1")`. + ```lisp 'AAPL ; symbol atom 'price ; used as column reference @@ -124,9 +126,18 @@ sentinel for their type: Symbols have no typed null literal (there is no `0Ns`). -Inside `select` and `update` expressions, `(nil? col)` lowers to the DAG -null-check opcode and returns a boolean per row, so it can be used directly in -`where:` predicates and projections. +`nil?` is element-wise: given a vector or a list it returns a `B8` vector with +one entry per element, so `(where (nil? v))` and `(sum (as 'I64 (nil? v)))` +work without a `map`. An atom answers for itself, and so does any other +container (a table or a dict is never null). Inside `select` and `update` +expressions, `(nil? col)` lowers to the DAG null-check opcode, which gives the +same per-row answer and can be used directly in `where:` predicates and +projections. + +```lisp +(nil? [1 0N 3]) ; [false true false] +(nil? [a ' b]) ; [false true false] — the empty symbol is SYM's null +``` ## Vectors diff --git a/docs/docs/namespaces/time.md b/docs/docs/namespaces/time.md index 07671eb8f..69220db5e 100644 --- a/docs/docs/namespaces/time.md +++ b/docs/docs/namespaces/time.md @@ -1,6 +1,6 @@ # `.time.*` — clock and timers -Monotonic clock access plus a recurring-callback scheduler. Timers integrate into the runtime's poll loop — they only fire when control is back in `ray_poll_run`, i.e. between REPL inputs, between IPC requests, or while idling in server-only mode. A long-running synchronous evaluation will defer pending timers until it returns. +Monotonic clock access plus a recurring-callback scheduler. Timers integrate into the runtime's poll loop — they only fire when control is back in the loop, i.e. between REPL inputs (interactive or piped: both read stdin through the loop), between IPC requests, or while idling in server-only mode. A long-running synchronous evaluation will defer pending timers until it returns. A script, or a piped session that reached end of input, stays alive until its pending timers are spent, so a one-shot timer set by a script fires before the process exits; a periodic timer keeps it running until the script ends the process itself. An open client handle does not keep a script alive. The clock is the same `CLOCK_MONOTONIC` source the scheduler uses for its deadlines, so `(.time.now)` is directly comparable to the `ms` argument passed to `.time.timer.set`. Wall-clock time is intentionally not exposed here: a host sleep / resume must not retroactively shift a scheduled deadline. diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index f37d04b71..1994f63da 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -585,7 +585,7 @@ Type checking, casting, null testing, and object inspection. |---|---|---|---|---| | `type` | unary | — | Get the type name of a value | `(type 42)` → `i64` | | `as` | binary | — | Cast value to another type | `(as 'i64 "42")` → `42` | -| `nil?` | unary | DAG in queries | Test if value is null; element-wise in query expressions | `(nil? 0Ni)` → `true` | +| `nil?` | unary | DAG in queries | Test for null; element-wise over vectors and lists (a `B8` per element), the same in and out of queries | `(nil? [1 0N 3])` → `[false true false]` | | `rc` | unary | — | Get reference count of an object | `(rc x)` → `1` | | `guid` | unary | — | Generate a vector of N GUIDs (`(guid 0)` → `[]`) | `(guid 1)` | @@ -726,7 +726,8 @@ TCP-based IPC for connecting to remote Rayforce instances. Uses binary serializa | `.ipc.open` | variadic | restricted | Open TCP connection to host:port (optional connect timeout in ms), returns handle | `(.ipc.open "localhost:5000" 2000)` | | `.ipc.close` | unary | restricted | Close an IPC connection handle | `(.ipc.close h)` | | `.ipc.send` | binary | restricted | Send a value over an IPC handle (sync request) | `(.ipc.send h "(sum (til 100))")` | -| `.ipc.handle` | variadic | — | Current connection handle inside any `.ipc.on.*` hook, `-1` outside | `(.ipc.handle)` | +| `.ipc.handle` | variadic | — | Current connection handle inside any `.ipc.on.*` hook, `-1` outside; given a live connection handle, that connection's transmit-queue view (`limit_bytes`, `limit_frames`, `queued_bytes`, `queued_frames`, `hwm_bytes`) | `(.ipc.handle)`, `(.ipc.handle h)` | +| `.ipc.txlimit` | variadic | restricted | Transmit backlog policy: `()` reads the process default, `(bytes [frames])` sets it, `(h bytes frames)` overrides one connection; a frame that would exceed a connection's limit is refused and a multicast subscriber is dropped and closed | `(.ipc.txlimit 8388608 64)` | | `.ipc.on.open` | hook | user-settable | Fires after inbound connection completes handshake; arg = handle | `(set .ipc.on.open (fn [h] ...))` | | `.ipc.on.close` | hook | user-settable | Fires before inbound connection teardown; arg = handle | `(set .ipc.on.close (fn [h] ...))` | | `.ipc.on.sync` | hook | user-settable | Intercepts sync messages; return value becomes the response | `(set .ipc.on.sync (fn [m] (eval (parse m))))` | diff --git a/docs/docs/storage/ipc.md b/docs/docs/storage/ipc.md index 3eadb6439..336814ed8 100644 --- a/docs/docs/storage/ipc.md +++ b/docs/docs/storage/ipc.md @@ -175,6 +175,20 @@ The query is assembled as data: while the `(list ...)` is built, `(quote price)` !!! note "Message types" `.ipc.send` uses synchronous messaging — it blocks until the server returns a result. For asynchronous (fire-and-forget) messaging, use `.ipc.post`, which sends without waiting for a response (the C equivalent is `ray_ipc_send_async`). +### .ipc.txlimit + +Every connection queues outbound bytes the socket cannot take immediately (asynchronous `.ipc.post` sends and multicast fan-out). The queue is bounded per connection: a frame that would push the backlog past the limit is refused, and for a multicast subscriber that means it is dropped from the topic and closed, so a lagging consumer learns of the loss explicitly instead of silently missing updates. + +```lisp +(.ipc.txlimit) ; {bytes:268435456 frames:0} — the process default +(.ipc.txlimit 8388608) ; 8 MiB per connection, frames unlimited +(.ipc.txlimit 8388608 64) ; at most 8 MiB or 64 queued frames, whichever first +(.ipc.txlimit h 67108864 0) ; one connection may hold 64 MiB +(.ipc.handle h) ; {handle limit_bytes limit_frames queued_bytes queued_frames hwm_bytes} +``` + +The default is 256 MiB with no frame cap; the minimum is 4 KiB, and `frames` of `0` means unlimited. Changing the default applies to every connection without an override, including ones already open. `.mc.stats` reports the default as `tx_limit_bytes` / `tx_limit_frames` and the largest backlog any connection has held as `tx_hwm_bytes`. `.ipc.txlimit` is restricted: it decides when a peer is dropped. + ## Connection Hooks The server side exposes the inbound connection lifecycle to Rayfall code through five user-installable lambdas under `.ipc.on.*` — `open`, `close`, `sync`, `async`, and `auth` — plus the `(.ipc.handle)` accessor that returns the current connection's handle inside any hook. See [IPC Connection Hooks](ipc-hooks.md) for the full reference: signatures, install / clear semantics, the reserved-namespace carve-out, per-hook error handling, and the restricted-mode interaction. diff --git a/docs/multicast-usage.md b/docs/multicast-usage.md index 78947b0d0..4871c98b8 100644 --- a/docs/multicast-usage.md +++ b/docs/multicast-usage.md @@ -21,7 +21,8 @@ It does not yet provide durable replay, topic filters, wildcard topics, ACLs, pe ## API ```clj -(.mc.sub topic null) ;; subscribe the current IPC handle to topic +(.mc.sub topic) ;; subscribe the current IPC handle to topic +(.mc.sub topic null) ;; explicit no-filter form (.mc.unsub topic) ;; unsubscribe the current IPC handle from topic (.mc.pub topic payload) ;; publish payload to all current subscribers (.mc.stats) ;; return aggregate multicast stats @@ -30,6 +31,7 @@ It does not yet provide durable replay, topic filters, wildcard topics, ACLs, pe `topic` can be a string or a symbol: ```clj +(.mc.sub "ticks") (.mc.sub "ticks" null) (.mc.sub 'ticks null) @@ -37,9 +39,10 @@ It does not yet provide durable replay, topic filters, wildcard topics, ACLs, pe (.mc.pub 'ticks (dict ['sym 'price] (list 'AAPL 185.5))) ``` -Filters are reserved for later work. For now, pass `null`: +Filters are reserved for later work. For now, omit the filter or pass `null`: ```clj +(.mc.sub "ticks") ;; ok (.mc.sub "ticks" null) ;; ok (.mc.sub "ticks" 1) ;; nyi ``` diff --git a/src/app/main.c b/src/app/main.c index 652fd2dbf..f27d2b91c 100644 --- a/src/app/main.c +++ b/src/app/main.c @@ -282,7 +282,14 @@ int main(int argc, char** argv) { /* Load script if specified */ if (file) { rc = ray_repl_run_file(file); - if (!interactive && !(port > 0)) goto done; + if (!interactive && !(port > 0)) { + /* A script that armed timers means to run them: stay until + * they are spent (a one-shot fires once, a periodic one until + * the script ends the process). Nothing else keeps a script + * alive — a client handle it left open is not a reason. */ + if (poll) ray_poll_drain_timers(poll); + goto done; + } } /* REPL or pure server mode. diff --git a/src/app/repl.c b/src/app/repl.c index 80d8ecb50..35cbf4e7f 100644 --- a/src/app/repl.c +++ b/src/app/repl.c @@ -32,6 +32,7 @@ #include "app/term.h" #include "core/ipc.h" #include "core/poll.h" +#include "core/timer.h" #include "core/pool.h" #include "lang/env.h" #include "lang/eval.h" @@ -58,6 +59,7 @@ #define STDIN_FD 0 #else #include +#include #include #define STDIN_FD STDIN_FILENO #endif @@ -1180,13 +1182,111 @@ static int32_t count_unmatched(const char* s, size_t len) { return d > 0 ? d : 0; } +/* ── Piped stdin, read through the poll loop ────────────────────────── + * fgets() on a pipe blocks outside the poll loop, so while a producer + * held the pipe open nothing else ran: no timer fired, no IPC request + * was served, until the writer closed (#493). The piped REPL now reads + * stdin through a small line reader: when it needs bytes and a poll + * exists, stdin is a registered selector whose read_fn pumps the pipe + * into the reader's buffer, and the reader waits in bounded poll passes + * — which fire due timers and serve every other selector. Without a + * poll it reads directly, as before. */ +typedef struct { + ray_repl_t* repl; + char buf[PIPE_BUF_SIZE * 2]; + size_t head, tail; + bool eof; + int64_t sel_id; /* -1 once deregistered (EOF) or never registered */ +} pipe_rd_t; + +static ray_t* piped_pump(ray_poll_t* poll, ray_selector_t* sel) { + pipe_rd_t* rd = (pipe_rd_t*)sel->data; + if (rd->tail >= sizeof(rd->buf)) return NULL; /* consumer drains first */ + ssize_t n = read(STDIN_FD, rd->buf + rd->tail, sizeof(rd->buf) - rd->tail); + if (n > 0) { rd->tail += (size_t)n; return NULL; } + if (n < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) return NULL; + rd->eof = true; + ray_poll_deregister(poll, sel->id); /* close_fn clears sel_id */ + return NULL; +} + +/* The poller deregisters a selector on hangup after serving its last + * readable event, without another read_fn call — a pipe's data and its + * hangup arrive in one event. Mark the reader so it stops waiting on + * the poll and drains whatever the pipe still holds with direct reads + * (which never block once the writer is gone). */ +static void piped_closed(ray_poll_t* poll, ray_selector_t* sel) { + (void)poll; + pipe_rd_t* rd = (pipe_rd_t*)sel->data; + if (rd) rd->sel_id = -1; +} + +/* fgets semantics over the reader: returns `line` holding up to size-1 + * bytes including a trailing newline when one was seen, or NULL at EOF + * with nothing left. A line longer than size-1 comes back in pieces, + * exactly as fgets hands it out. */ +static char* piped_fgets(pipe_rd_t* rd, char* line, size_t size) { + for (;;) { + size_t avail = rd->tail - rd->head; + size_t maxn = size - 1 < avail ? size - 1 : avail; + char* nl = maxn ? memchr(rd->buf + rd->head, '\n', maxn) : NULL; + if (nl) { + size_t n = (size_t)(nl - (rd->buf + rd->head)) + 1; + memcpy(line, rd->buf + rd->head, n); line[n] = '\0'; + rd->head += n; + return line; + } + if (avail >= size - 1) { + memcpy(line, rd->buf + rd->head, size - 1); line[size - 1] = '\0'; + rd->head += size - 1; + return line; + } + if (rd->eof) { + if (avail == 0) return NULL; + memcpy(line, rd->buf + rd->head, avail); line[avail] = '\0'; + rd->head = rd->tail; + return line; + } + if (rd->head > 0) { /* compact, then refill */ + memmove(rd->buf, rd->buf + rd->head, avail); + rd->head = 0; rd->tail = avail; + } + ray_poll_t* poll = rd->repl ? rd->repl->poll : NULL; + if (poll && rd->sel_id >= 0) { + if (ray_poll_run_for(poll, 1000) < 0 || poll->code >= 0) { + /* The loop was told to exit (an IPC hook, a callback): + * stop reading, let run_piped wind down. */ + rd->eof = true; + } + } else { + ssize_t n = read(STDIN_FD, rd->buf + rd->tail, sizeof(rd->buf) - rd->tail); + if (n > 0) rd->tail += (size_t)n; + else if (n < 0 && errno == EINTR) continue; + else rd->eof = true; + } + } +} + static void run_piped(ray_repl_t* repl) { char line[PIPE_BUF_SIZE]; char accum[PIPE_BUF_SIZE]; size_t accum_len = 0; bool mid_line = false; - while (fgets(line, PIPE_BUF_SIZE, stdin)) { + pipe_rd_t rd = { .repl = repl, .head = 0, .tail = 0, .eof = false, .sel_id = -1 }; + if (repl->poll) { + ray_poll_reg_t reg = {0}; + reg.fd = STDIN_FD; + reg.type = RAY_SEL_STDIN; + reg.read_fn = piped_pump; + reg.close_fn = piped_closed; + reg.data = &rd; + rd.sel_id = ray_poll_register(repl->poll, ®); + /* A registration failure (an fd the poller cannot watch) falls + * back to direct reads, exactly the old behaviour. */ + } + + while (piped_fgets(&rd, line, PIPE_BUF_SIZE)) { size_t len = strlen(line); bool had_newline = (len > 0 && line[len - 1] == '\n'); if (had_newline) line[--len] = '\0'; @@ -1226,7 +1326,7 @@ static void run_piped(ray_repl_t* repl) { accum_len = 0; mid_line = false; while (!had_newline) { - if (!fgets(line, PIPE_BUF_SIZE, stdin)) break; + if (!piped_fgets(&rd, line, PIPE_BUF_SIZE)) break; len = strlen(line); had_newline = (len > 0 && line[len - 1] == '\n'); if (had_newline) { @@ -1236,7 +1336,7 @@ static void run_piped(ray_repl_t* repl) { depth += bracket_delta_s(line, len, &bs); } while (depth > 0) { - if (!fgets(line, PIPE_BUF_SIZE, stdin)) break; + if (!piped_fgets(&rd, line, PIPE_BUF_SIZE)) break; len = strlen(line); had_newline = (len > 0 && line[len - 1] == '\n'); if (had_newline) { @@ -1245,7 +1345,7 @@ static void run_piped(ray_repl_t* repl) { } depth += bracket_delta_s(line, len, &bs); while (!had_newline) { - if (!fgets(line, PIPE_BUF_SIZE, stdin)) break; + if (!piped_fgets(&rd, line, PIPE_BUF_SIZE)) break; len = strlen(line); had_newline = (len > 0 && line[len - 1] == '\n'); if (had_newline) { @@ -1275,9 +1375,16 @@ static void run_piped(ray_repl_t* repl) { eval_and_print(NULL, accum, false, repl->timeit); } - /* If poll has registered selectors (IPC server), enter poll_run after stdin */ - if (repl->poll && repl->poll->n_sels > 0) - ray_poll_run(repl->poll); + if (repl->poll) { + if (rd.sel_id >= 0) ray_poll_deregister(repl->poll, rd.sel_id); + /* After stdin: a listener or connections keep the process serving + * (as before, now counting live selectors rather than slots); + * with none, stay only until pending timers are spent. */ + if (repl->poll->n_live > 0) + ray_poll_run(repl->poll); + else + ray_poll_drain_timers(repl->poll); + } } void ray_repl_run(ray_repl_t* repl) { diff --git a/src/core/epoll.c b/src/core/epoll.c index 88aab4bcd..73e57e68d 100644 --- a/src/core/epoll.c +++ b/src/core/epoll.c @@ -160,6 +160,7 @@ int64_t ray_poll_register(ray_poll_t* poll, ray_poll_reg_t* reg) return -1; } + poll->n_live++; if (sel->open_fn) sel->open_fn(poll, sel); return id; } @@ -186,6 +187,7 @@ void ray_poll_deregister(ray_poll_t* poll, int64_t id) ray_poll_buf_free(sel->tx.buf); ray_sys_free(sel); poll->sels[id] = NULL; + if (poll->n_live > 0) poll->n_live--; } int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) @@ -205,6 +207,11 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) wait_ms = (int)remaining; } + /* Nothing registered and nothing scheduled: an unbounded loop + * would block here forever. Return instead, so a process that + * stayed only for its timers can end once they are spent. */ + if (!bounded && ray_poll_idle(poll)) return 0; + if (poll->timers) { int64_t deadline = ray_timers_next_deadline_ms( (ray_timers_t*)poll->timers); diff --git a/src/core/ipc.c b/src/core/ipc.c index ac6e139c4..412ca2370 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -167,7 +167,12 @@ size_t ray_ipc_decompress(const uint8_t* src, size_t clen, #define RAY_IPC_PHASE_HEADER 1 #define RAY_IPC_PHASE_PAYLOAD 2 #define RAY_IPC_PHASE_CREDS 3 -#define RAY_IPC_TX_MAX_BYTES (256LL * 1024LL * 1024LL) +/* Hard cap on a single wire frame; the backlog a connection may hold is + * the separately configurable transmit limit (ray_ipc_tx_limit_set). */ +#define RAY_IPC_FRAME_MAX_BYTES (256LL * 1024LL * 1024LL) + +static int64_t g_tx_limit_bytes = RAY_IPC_TX_DEFAULT_BYTES; +static int64_t g_tx_limit_frames = 0; /* unlimited */ /* Constant-time comparison — prevents timing side-channel on password. */ static bool ct_eq(const void* a, const void* b, size_t len) { @@ -254,6 +259,18 @@ static void ipc_ctx_set(int64_t handle, ray_poll_t* poll) { __VM->ipc_poll = poll; } +static _Thread_local bool g_auto_journal_eval = false; + +bool ray_ipc_auto_journal_eval(void) { + return g_auto_journal_eval; +} + +#ifdef DEBUG +void ray_ipc_set_auto_journal_eval_for_test(bool enabled) { + g_auto_journal_eval = enabled; +} +#endif + ray_poll_t* ray_ipc_active_poll(void) { ray_poll_t* p = ipc_ctx_poll(); return p ? p : (ray_poll_t*)ray_runtime_get_poll(); @@ -507,6 +524,7 @@ static ray_t* eval_payload_core(uint8_t* payload, size_t payload_len, * behaviour: "the message has not been logged so we cannot * accept it". Silently evaluating un-logged mutations defeats * the entire durability premise of `-l`/`-L`. */ + bool auto_journaled = false; if (ray_journal_is_open() && hdr->msgtype == RAY_IPC_MSG_SYNC) { ray_ipc_header_t log_hdr = *hdr; if (ray_eval_get_restricted()) @@ -516,6 +534,7 @@ static ray_t* eval_payload_core(uint8_t* payload, size_t payload_len, fprintf(stderr, "log: ERROR journal write failed (rc=%d) — refusing to evaluate\n", (int)je); return ray_error("io", "journal write failed; mutation refused"); } + auto_journaled = true; } /* Query-statistics ring: bracket the eval so the server records one @@ -547,6 +566,8 @@ static ray_t* eval_payload_core(uint8_t* payload, size_t payload_len, } ray_t* result = NULL; + bool prev_auto_journal_eval = g_auto_journal_eval; + if (auto_journaled) g_auto_journal_eval = true; if (msg && !RAY_IS_ERR(msg)) { if (msg->type == RAY_LIST) { ray_t** elems = (ray_t**)ray_data(msg); @@ -593,6 +614,7 @@ static ray_t* eval_payload_core(uint8_t* payload, size_t payload_len, ray_release(msg); } } + g_auto_journal_eval = prev_auto_journal_eval; /* A lazy result is an internal deferred-DAG representation that cannot * be serialized — force it to a concrete value before it reaches the * wire. The direct ray_eval(msg) path (non-STR payloads, e.g. an @@ -1546,8 +1568,12 @@ static int conn_pump(ray_poll_t* poll, int64_t id) } } -static ray_poll_buf_t* conn_frame_msg(ray_t* msg, uint8_t msgtype, - uint8_t extra_flags, ray_err_t* err_out) +/* Serialize + compress + frame one message into an immutable, reference- + * counted frame (rc = 1 to the caller). Built once per message however + * many connections it goes to: ray_mcast_pub shares one frame across + * every subscriber's queue (#487). */ +static ray_poll_frame_t* conn_frame_msg(ray_t* msg, uint8_t msgtype, + uint8_t extra_flags, ray_err_t* err_out) { if (err_out) *err_out = RAY_OK; int64_t ser_size = ray_serde_size(msg); @@ -1602,14 +1628,14 @@ static ray_poll_buf_t* conn_frame_msg(ray_t* msg, uint8_t msgtype, }; size_t total = sizeof(hdr) + send_len; - if (total > (size_t)RAY_IPC_TX_MAX_BYTES) { + if (total > (size_t)RAY_IPC_FRAME_MAX_BYTES) { ray_sys_free(send_buf); if (payload) ray_sys_free(payload); if (err_out) *err_out = RAY_ERR_IO; return NULL; } - ray_poll_buf_t* frame = ray_poll_buf_new((int64_t)total); + ray_poll_frame_t* frame = ray_poll_frame_new((int64_t)total); if (!frame) { ray_sys_free(send_buf); if (payload) ray_sys_free(payload); @@ -1635,10 +1661,10 @@ static int64_t conn_write_msg(ray_sock_t fd, ray_t* msg, uint8_t msgtype, uint8_t extra_flags) { ray_err_t err = RAY_OK; - ray_poll_buf_t* frame = conn_frame_msg(msg, msgtype, extra_flags, &err); + ray_poll_frame_t* frame = conn_frame_msg(msg, msgtype, extra_flags, &err); if (!frame) return -1; int64_t rc = ray_sock_send(fd, frame->data, (size_t)frame->size); - ray_poll_buf_free(frame); + ray_poll_frame_release(frame); return rc < 0 ? -1 : 0; } @@ -1911,32 +1937,48 @@ ray_err_t ray_ipc_send_async(int64_t handle, ray_t* msg) return rc; } -static int64_t conn_tx_pending(ray_selector_t* sel) +static void conn_tx_limits(ray_selector_t* sel, int64_t* bytes, int64_t* frames) { - int64_t pending = 0; + *bytes = (sel && sel->tx.limit_bytes > 0) ? sel->tx.limit_bytes : g_tx_limit_bytes; + *frames = (sel && sel->tx.limit_frames > 0) ? sel->tx.limit_frames : g_tx_limit_frames; +} + +/* Bytes still to be written across the queue, and the number of queued + * frames. Saturates at INT64_MAX rather than overflowing. */ +static int64_t conn_tx_pending(ray_selector_t* sel, int64_t* frames_out) +{ + int64_t pending = 0, frames = 0; for (ray_poll_buf_t* b = sel ? sel->tx.buf : NULL; b; b = b->next) { if (b->size > b->offset) { int64_t rem = b->size - b->offset; - if (pending > RAY_IPC_TX_MAX_BYTES - rem) - return RAY_IPC_TX_MAX_BYTES + 1; - pending += rem; + pending = (pending > INT64_MAX - rem) ? INT64_MAX : pending + rem; + frames++; } } + if (frames_out) *frames_out = frames; return pending; } -static int conn_tx_append(ray_selector_t* sel, ray_poll_buf_t* frame) +/* Admit `frame` to the queue if the configured backlog allows it. */ +static int conn_tx_append(ray_poll_t* poll, ray_selector_t* sel, ray_poll_buf_t* frame) { if (!sel || !frame || frame->offset > frame->size) return -1; int64_t add = frame->size - frame->offset; - int64_t pending = conn_tx_pending(sel); - if (add < 0 || pending < 0 || pending > RAY_IPC_TX_MAX_BYTES - add) - return -1; + int64_t limit_bytes, limit_frames; + conn_tx_limits(sel, &limit_bytes, &limit_frames); + int64_t frames = 0; + int64_t pending = conn_tx_pending(sel, &frames); + if (add < 0 || pending > limit_bytes - add) return -1; + if (limit_frames > 0 && frames + 1 > limit_frames) return -1; ray_poll_buf_t** tail = &sel->tx.buf; while (*tail) tail = &(*tail)->next; *tail = frame; + + int64_t now = pending + add; + if (now > sel->tx.hwm_bytes) sel->tx.hwm_bytes = now; + if (poll && now > poll->tx_hwm_bytes) poll->tx_hwm_bytes = now; return 0; } @@ -1958,8 +2000,10 @@ static int conn_try_send_frame(ray_selector_t* sel, ray_poll_buf_t* frame) return 0; } -ray_err_t ray_ipc_try_send_async(int64_t handle, ray_t* msg) +ray_err_t ray_ipc_frame_async(ray_t* msg, ray_poll_frame_t** out) { + if (!out) return RAY_ERR_TYPE; + *out = NULL; bool owned = false; if (ray_is_lazy(msg)) { ray_retain(msg); @@ -1971,44 +2015,98 @@ ray_err_t ray_ipc_try_send_async(int64_t handle, ray_t* msg) } owned = true; } + ray_err_t err = RAY_OK; + ray_poll_frame_t* frame = conn_frame_msg(msg, RAY_IPC_MSG_ASYNC, 0, &err); + if (owned) ray_release(msg); + if (!frame) return err == RAY_OK ? RAY_ERR_IO : err; + *out = frame; + return RAY_OK; +} +ray_err_t ray_ipc_try_send_frame(int64_t handle, ray_poll_frame_t* frame) +{ + if (!frame) return RAY_ERR_TYPE; ray_poll_t* poll; ray_selector_t* sel = conn_resolve(&poll, handle); - if (!sel) { - if (owned) ray_release(msg); - return RAY_ERR_IO; - } + if (!sel) return RAY_ERR_IO; - ray_err_t err = RAY_OK; - ray_poll_buf_t* frame = conn_frame_msg(msg, RAY_IPC_MSG_ASYNC, 0, &err); - if (!frame) { - if (owned) ray_release(msg); - return err == RAY_OK ? RAY_ERR_IO : err; - } + /* The queue node holds its own reference; the caller keeps its own. */ + ray_poll_buf_t* node = ray_poll_buf_from_frame(frame); + if (!node) return RAY_ERR_OOM; int rc = 0; if (sel->tx.buf) { - rc = 1; + rc = 1; /* keep ordering behind queued bytes */ } else { - rc = conn_try_send_frame(sel, frame); + rc = conn_try_send_frame(sel, node); } if (rc == 0) { - ray_poll_buf_free(frame); + ray_poll_buf_free(node); } else if (rc > 0) { - if (conn_tx_append(sel, frame) < 0) { - ray_poll_buf_free(frame); - if (owned) ray_release(msg); + if (conn_tx_append(poll, sel, node) < 0) { + ray_poll_buf_free(node); return RAY_ERR_IO; } ray_poll_tx_request(poll, sel); } else { - ray_poll_buf_free(frame); + ray_poll_buf_free(node); } - if (owned) ray_release(msg); return rc >= 0 ? RAY_OK : RAY_ERR_IO; } +void ray_ipc_tx_limit_get(int64_t* bytes, int64_t* frames) +{ + if (bytes) *bytes = g_tx_limit_bytes; + if (frames) *frames = g_tx_limit_frames; +} + +ray_err_t ray_ipc_tx_limit_set(int64_t bytes, int64_t frames) +{ + if (bytes < RAY_IPC_TX_MIN_BYTES || frames < 0) return RAY_ERR_DOMAIN; + g_tx_limit_bytes = bytes; + g_tx_limit_frames = frames; + return RAY_OK; +} + +ray_err_t ray_ipc_tx_limit_set_handle(int64_t handle, int64_t bytes, int64_t frames) +{ + if (bytes < RAY_IPC_TX_MIN_BYTES || frames < 0) return RAY_ERR_DOMAIN; + ray_poll_t* poll; + ray_selector_t* sel = conn_resolve(&poll, handle); + if (!sel) return RAY_ERR_IO; + sel->tx.limit_bytes = bytes; + sel->tx.limit_frames = frames; + return RAY_OK; +} + +ray_err_t ray_ipc_tx_info(int64_t handle, ray_ipc_tx_info_t* out) +{ + if (!out) return RAY_ERR_TYPE; + ray_poll_t* poll; + ray_selector_t* sel = conn_resolve(&poll, handle); + if (!sel) return RAY_ERR_IO; + conn_tx_limits(sel, &out->limit_bytes, &out->limit_frames); + out->queued_bytes = conn_tx_pending(sel, &out->queued_frames); + out->hwm_bytes = sel->tx.hwm_bytes; + return RAY_OK; +} + +int64_t ray_ipc_tx_hwm_bytes(ray_poll_t* poll) +{ + return poll ? poll->tx_hwm_bytes : 0; +} + +ray_err_t ray_ipc_try_send_async(int64_t handle, ray_t* msg) +{ + ray_poll_frame_t* frame = NULL; + ray_err_t err = ray_ipc_frame_async(msg, &frame); + if (err != RAY_OK) return err; + err = ray_ipc_try_send_frame(handle, frame); + ray_poll_frame_release(frame); + return err; +} + /* Verbose-eval sync send: sets RAY_IPC_FLAG_VERBOSE on the outbound * header so the peer captures whatever the eval writes to * stdout/stderr and returns a 2-element list [captured_str, result] diff --git a/src/core/ipc.h b/src/core/ipc.h index 66f8f3c8c..282ff1828 100644 --- a/src/core/ipc.h +++ b/src/core/ipc.h @@ -74,6 +74,10 @@ size_t ray_ipc_decompress(const uint8_t* src, size_t clen, int64_t ray_ipc_current_handle(void); ray_poll_t* ray_ipc_active_poll(void); ray_poll_t* ray_ipc_context_poll(void); +bool ray_ipc_auto_journal_eval(void); +#ifdef DEBUG +void ray_ipc_set_auto_journal_eval_for_test(bool enabled); +#endif /* ===== Poll-based IPC (new API) ===== */ @@ -131,6 +135,38 @@ ray_t* ray_ipc_send(int64_t handle, ray_t* msg); ray_err_t ray_ipc_send_async(int64_t handle, ray_t* msg); ray_err_t ray_ipc_try_send_async(int64_t handle, ray_t* msg); +/* Fan-out building blocks (#487): frame a message once into an immutable + * reference-counted frame, then hand the same frame to any number of + * connections. ray_ipc_try_send_frame takes its own reference for the + * queue; the caller releases the one it got from ray_ipc_frame_async when + * it is done handing the frame out. Same send-or-queue semantics and + * return codes as ray_ipc_try_send_async, which is now the one-connection + * composition of the two. */ +ray_err_t ray_ipc_frame_async(ray_t* msg, ray_poll_frame_t** out); +ray_err_t ray_ipc_try_send_frame(int64_t handle, ray_poll_frame_t* frame); + +/* Transmit backlog (#486). A connection's queue admits a frame only while + * the bytes and frames already queued stay under its limit; a frame that + * would exceed it is refused (RAY_ERR_IO), which multicast turns into an + * explicit drop-and-close of that subscriber. The process default applies + * to every connection without an override. frames == 0 means unlimited. */ +#define RAY_IPC_TX_DEFAULT_BYTES (256LL * 1024LL * 1024LL) +#define RAY_IPC_TX_MIN_BYTES 4096LL + +typedef struct { + int64_t limit_bytes; /* effective limit on this connection */ + int64_t limit_frames; + int64_t queued_bytes; /* backlog right now */ + int64_t queued_frames; + int64_t hwm_bytes; /* largest backlog ever queued here */ +} ray_ipc_tx_info_t; + +void ray_ipc_tx_limit_get(int64_t* bytes, int64_t* frames); +ray_err_t ray_ipc_tx_limit_set(int64_t bytes, int64_t frames); /* process default */ +ray_err_t ray_ipc_tx_limit_set_handle(int64_t handle, int64_t bytes, int64_t frames); +ray_err_t ray_ipc_tx_info(int64_t handle, ray_ipc_tx_info_t* out); /* RAY_ERR_IO: not a live connection */ +int64_t ray_ipc_tx_hwm_bytes(ray_poll_t* poll); + /* Remote-REPL helper: send a SYNC message with RAY_IPC_FLAG_VERBOSE * set, returning a 2-element list [captured_str, result] where * captured_str is whatever the server's eval wrote to stdout/stderr diff --git a/src/core/kqueue.c b/src/core/kqueue.c index 3b05befa9..11c0d3ac4 100644 --- a/src/core/kqueue.c +++ b/src/core/kqueue.c @@ -166,6 +166,7 @@ int64_t ray_poll_register(ray_poll_t* poll, ray_poll_reg_t* reg) return -1; } + poll->n_live++; if (sel->open_fn) sel->open_fn(poll, sel); return id; } @@ -187,6 +188,7 @@ void ray_poll_deregister(ray_poll_t* poll, int64_t id) ray_poll_buf_free(sel->tx.buf); ray_sys_free(sel); poll->sels[id] = NULL; + if (poll->n_live > 0) poll->n_live--; } int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) @@ -205,6 +207,11 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) wait_ms = remaining; } + /* Nothing registered and nothing scheduled: an unbounded loop + * would block here forever. Return instead, so a process that + * stayed only for its timers can end once they are spent. */ + if (!bounded && ray_poll_idle(poll)) return 0; + if (poll->timers) { int64_t deadline = ray_timers_next_deadline_ms( (ray_timers_t*)poll->timers); diff --git a/src/core/mcast.c b/src/core/mcast.c index 19ed1bd8c..c2bd08646 100644 --- a/src/core/mcast.c +++ b/src/core/mcast.c @@ -33,6 +33,7 @@ struct ray_mcast { int64_t published; int64_t delivered; int64_t dropped; + int64_t framed; /* wire frames built: one per publication, not per subscriber */ }; static int64_t topic_sym(ray_t* topic) { @@ -292,11 +293,23 @@ ray_t* ray_mcast_pub(ray_poll_t* poll, ray_t* topic, ray_t* payload) { } } + /* Serialize and compress once; every subscriber's queue shares the + * frame and keeps only its own write offset (#487). */ + ray_poll_frame_t* frame = NULL; + ray_err_t ferr = ray_ipc_frame_async(msg, &frame); + ray_release(msg); + if (ferr != RAY_OK || !frame) { + if (dead_handles) ray_sys_free(dead_handles); + return ferr == RAY_ERR_OOM ? ray_error("oom", NULL) + : ray_error("io", ".mc.pub could not frame the payload"); + } + mc->framed++; + t->next_seq++; mc->published++; for (int32_t i = 0; i < t->n_subs;) { - ray_err_t rc = ray_ipc_try_send_async(t->subs[i].handle, msg); + ray_err_t rc = ray_ipc_try_send_frame(t->subs[i].handle, frame); if (rc == RAY_OK) { t->subs[i].last_sent_seq = seq; mc->delivered++; @@ -309,7 +322,7 @@ ray_t* ray_mcast_pub(ray_poll_t* poll, ray_t* topic, ray_t* payload) { dead_handles[dead_n++] = dead; } } - ray_release(msg); + ray_poll_frame_release(frame); if (t->n_subs == 0) { int32_t ti = topic_index(mc, sym); if (ti >= 0) remove_topic(mc, ti); @@ -330,8 +343,8 @@ ray_t* ray_mcast_stats(ray_poll_t* poll) { subs += mc->topics[i].n_subs; } - ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 5); - ray_t* vals = ray_list_new(5); + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 9); + ray_t* vals = ray_list_new(9); if (!keys || RAY_IS_ERR(keys) || !vals || RAY_IS_ERR(vals)) { if (keys && !RAY_IS_ERR(keys)) ray_release(keys); if (vals && !RAY_IS_ERR(vals)) ray_release(vals); @@ -360,6 +373,25 @@ ray_t* ray_mcast_stats(ray_poll_t* poll) { if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } v = ray_i64(mc ? mc->dropped : 0); vals = ray_list_append(vals, v); ray_release(v); if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + k = ray_sym_intern("framed", 6); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + v = ray_i64(mc ? mc->framed : 0); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + /* Backlog policy in force and the largest backlog seen (#486). */ + int64_t lim_bytes = 0, lim_frames = 0; + ray_ipc_tx_limit_get(&lim_bytes, &lim_frames); + k = ray_sym_intern("tx_limit_bytes", 14); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + v = ray_i64(lim_bytes); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + k = ray_sym_intern("tx_limit_frames", 15); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + v = ray_i64(lim_frames); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + k = ray_sym_intern("tx_hwm_bytes", 12); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + v = ray_i64(ray_ipc_tx_hwm_bytes(poll)); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } return ray_dict_new(keys, vals); } diff --git a/src/core/poll.c b/src/core/poll.c index 74ff0d7e4..ce8a38bc1 100644 --- a/src/core/poll.c +++ b/src/core/poll.c @@ -22,6 +22,7 @@ */ #include "core/poll.h" +#include "core/timer.h" #include "mem/sys.h" #include @@ -44,6 +45,25 @@ ray_selector_t* ray_poll_get(ray_poll_t* poll, int64_t id) return poll->sels[id]; } +bool ray_poll_idle(ray_poll_t* poll) +{ + if (!poll) return true; + if (poll->n_live > 0) return false; + if (!poll->timers) return true; + return ray_timers_next_deadline_ms((ray_timers_t*)poll->timers) == INT64_MAX; +} + +void ray_poll_drain_timers(ray_poll_t* poll) +{ + if (!poll) return; + while (poll->code < 0 && poll->timers && + ray_timers_next_deadline_ms((ray_timers_t*)poll->timers) != INT64_MAX) { + /* One bounded pass: wakes for the next deadline (the loop trims + * the wait to it) or for any selector event, fires what is due. */ + if (ray_poll_run_for(poll, 1000) < 0) break; + } +} + ray_poll_buf_t* ray_poll_buf_new(int64_t size) { ray_poll_buf_t* buf = (ray_poll_buf_t*)ray_sys_alloc( @@ -52,6 +72,8 @@ ray_poll_buf_t* ray_poll_buf_new(int64_t size) buf->next = NULL; buf->size = size; buf->offset = 0; + buf->data = buf->storage; + buf->frame = NULL; return buf; } @@ -59,11 +81,46 @@ void ray_poll_buf_free(ray_poll_buf_t* buf) { while (buf) { ray_poll_buf_t* next = buf->next; + if (buf->frame) ray_poll_frame_release(buf->frame); ray_sys_free(buf); buf = next; } } +ray_poll_frame_t* ray_poll_frame_new(int64_t size) +{ + ray_poll_frame_t* f = (ray_poll_frame_t*)ray_sys_alloc( + sizeof(ray_poll_frame_t) + (size_t)size); + if (!f) return NULL; + f->rc = 1; + f->size = size; + return f; +} + +void ray_poll_frame_retain(ray_poll_frame_t* f) +{ + if (f) f->rc++; +} + +void ray_poll_frame_release(ray_poll_frame_t* f) +{ + if (f && --f->rc == 0) ray_sys_free(f); +} + +ray_poll_buf_t* ray_poll_buf_from_frame(ray_poll_frame_t* f) +{ + if (!f) return NULL; + ray_poll_buf_t* buf = (ray_poll_buf_t*)ray_sys_alloc(sizeof(ray_poll_buf_t)); + if (!buf) return NULL; + buf->next = NULL; + buf->size = f->size; + buf->offset = 0; + buf->data = f->data; + buf->frame = f; + ray_poll_frame_retain(f); + return buf; +} + void ray_poll_rx_request(ray_poll_t* poll, ray_selector_t* sel, int64_t size) { (void)poll; diff --git a/src/core/poll.h b/src/core/poll.h index 6290d5c1f..87ce0cff1 100644 --- a/src/core/poll.h +++ b/src/core/poll.h @@ -44,11 +44,27 @@ typedef ray_t* (*ray_poll_data_fn)(ray_poll_t* poll, ray_selector_t* sel, void* /* ===== Buffer ===== */ +/* Immutable, reference-counted bytes. A frame built once for a multicast + * publication is shared by every subscriber's transmit queue; each queue + * holds its own ray_poll_buf_t node (offset, link) pointing at the same + * frame, and the frame is freed when the last node is done with it. */ +typedef struct ray_poll_frame { + int32_t rc; + int64_t size; + uint8_t data[]; +} ray_poll_frame_t; + +/* A queue node. `data` points either at the node's own trailing storage + * (ray_poll_buf_new: rx buffers, one-off tx frames) or into a shared + * ray_poll_frame_t (ray_poll_buf_from_frame), which `frame` then owns a + * reference to. Readers use data/size/offset the same way either way. */ typedef struct ray_poll_buf { struct ray_poll_buf* next; int64_t size; int64_t offset; - uint8_t data[]; + uint8_t* data; + ray_poll_frame_t* frame; + uint8_t storage[]; } ray_poll_buf_t; /* ===== Selector — one per registered fd ===== */ @@ -63,7 +79,13 @@ struct ray_selector { ray_event_fn error_fn; ray_poll_data_fn data_fn; struct { ray_poll_buf_t* buf; ray_io_fn recv_fn; ray_read_fn read_fn; } rx; - struct { ray_poll_buf_t* buf; ray_io_fn send_fn; } tx; + struct { + ray_poll_buf_t* buf; + ray_io_fn send_fn; + int64_t limit_bytes; /* per-connection backlog override; 0 = process default */ + int64_t limit_frames; /* idem; 0 = process default (which may be unlimited) */ + int64_t hwm_bytes; /* largest backlog ever queued on this connection */ + } tx; }; /* ===== Registration ===== */ @@ -93,17 +115,27 @@ struct ray_poll { * compiler hoist the load out of the loop. */ _Atomic int64_t code; /* exit code (-1 = running) */ ray_selector_t** sels; /* selector array */ - uint32_t n_sels; + uint32_t n_sels; /* slots (deregistered slots stay NULL) */ + uint32_t n_live; /* registered selectors right now */ uint32_t sel_cap; char auth_secret[256]; /* password from -u/-U, empty = no auth */ bool restricted; /* true if -U (read-only IPC mode) */ void* timers; /* opaque ray_timers_t*; lazily allocated */ void* mcast; /* opaque ray_mcast_t*; lazily allocated */ + int64_t tx_hwm_bytes; /* largest backlog ever queued on any connection */ }; /* ===== API ===== */ ray_poll_t* ray_poll_create(void); +/* True when the loop has nothing to wait for: no registered selector and + * no pending timer. ray_poll_run returns instead of blocking forever. */ +bool ray_poll_idle(ray_poll_t* poll); +/* Run bounded passes until no timer is pending (or the loop was told to + * exit). Serves whatever selectors exist meanwhile, but does not stay + * for them: a script's lingering client handle must not keep the + * process alive once its timers are spent. */ +void ray_poll_drain_timers(ray_poll_t* poll); void ray_poll_destroy(ray_poll_t* poll); void ray_poll_set_restricted(ray_poll_t* poll, bool restricted); int64_t ray_poll_register(ray_poll_t* poll, ray_poll_reg_t* reg); @@ -117,6 +149,10 @@ ray_poll_buf_t* ray_poll_buf_new(int64_t size); void ray_poll_buf_free(ray_poll_buf_t* buf); void ray_poll_rx_request(ray_poll_t* poll, ray_selector_t* sel, int64_t size); +ray_poll_frame_t* ray_poll_frame_new(int64_t size); /* rc = 1 */ +void ray_poll_frame_retain(ray_poll_frame_t* f); +void ray_poll_frame_release(ray_poll_frame_t* f); +ray_poll_buf_t* ray_poll_buf_from_frame(ray_poll_frame_t* f); /* node holding a new ref */ void ray_poll_tx_request(ray_poll_t* poll, ray_selector_t* sel); void ray_poll_tx_cancel(ray_poll_t* poll, ray_selector_t* sel); int ray_poll_tx_flush(ray_poll_t* poll, ray_selector_t* sel); diff --git a/src/core/types.h b/src/core/types.h index c70b4dd65..728f1d998 100644 --- a/src/core/types.h +++ b/src/core/types.h @@ -39,8 +39,12 @@ /* Type sizes lookup table (defined in types.c) */ extern const uint8_t ray_type_sizes[256]; -/* Element size for a given type tag */ -#define ray_elem_size(t) (ray_type_sizes[(t)]) +/* Element size for a given type tag. Cast to uint8_t so a negative (atom) + * type tag indexes the upper, zero-filled half of the 256-entry table rather + * than reading out of bounds — ray_type_sizes[(int8_t)-1] is an OOB read (UB). + * Non-vector/atom tags legitimately have no element size and read back 0, and + * this matches the (uint8_t) indexing already used in vec.c. */ +#define ray_elem_size(t) (ray_type_sizes[(uint8_t)(t)]) static inline int64_t ray_cast_f64_to_i64_null(double v) { if (v != v) return NULL_I64; diff --git a/src/lang/eval.c b/src/lang/eval.c index e99c299e9..81c5ae389 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -3400,6 +3400,9 @@ static void ray_register_builtins(void) { /* Current connection handle inside any `.ipc.on.*` hook, -1 otherwise. * Variadic for the `(.ipc.handle)` / `(.ipc.handle 0)` convention. */ register_vary( ".ipc.handle", RAY_FN_NONE, ray_ipc_handle_fn); + /* Transmit backlog policy: read, set the process default, or override + * one connection. Privileged — it decides when a peer is dropped. */ + register_vary( ".ipc.txlimit", RAY_FN_RESTRICTED, ray_ipc_txlimit_fn); /* Multicast/pub-sub over IPC. Subscriptions are allowed under * restricted IPC; publishing stays privileged. */ diff --git a/src/lang/internal.h b/src/lang/internal.h index e653f97d5..bc21a86f0 100644 --- a/src/lang/internal.h +++ b/src/lang/internal.h @@ -645,6 +645,7 @@ ray_t* ray_hclose_fn(ray_t* x); ray_t* ray_hsend_fn(ray_t* handle, ray_t* msg); ray_t* ray_hpost_fn(ray_t* handle, ray_t* msg); ray_t* ray_ipc_handle_fn(ray_t** args, int64_t n); +ray_t* ray_ipc_txlimit_fn(ray_t** args, int64_t n); ray_t* ray_mc_sub_fn(ray_t** args, int64_t n); ray_t* ray_mc_unsub_fn(ray_t* topic); ray_t* ray_mc_pub_fn(ray_t* topic, ray_t* payload); diff --git a/src/lang/parse.c b/src/lang/parse.c index 163bf6e34..94c16b0f4 100644 --- a/src/lang/parse.c +++ b/src/lang/parse.c @@ -852,6 +852,7 @@ static ray_t* parse_expr_inner(ray_parser_t *p) { int32_t sl = p->line, sc = p->col; const char *before = p->pos; ray_t *result; + bool leaf = true; /* symbol / keyword / name / number: must end at a delimiter */ switch (PA(*p->pos)) { case PA_END: return ray_error("parse", NULL); @@ -863,11 +864,11 @@ static ray_t* parse_expr_inner(ray_parser_t *p) { result = parse_name(p); /* standalone '-' or '-name' */ break; case PA_ALPHA: result = parse_name(p); break; - case PA_STRING: result = parse_string(p); break; + case PA_STRING: result = parse_string(p); leaf = false; break; case PA_QUOTE: result = parse_symbol(p); break; - case PA_LPAREN: result = parse_list(p); break; - case PA_LBRACK: result = parse_vector(p); break; - case PA_LBRACE: result = parse_dict(p); break; + case PA_LPAREN: result = parse_list(p); leaf = false; break; + case PA_LBRACK: result = parse_vector(p); leaf = false; break; + case PA_LBRACE: result = parse_dict(p); leaf = false; break; case PA_RPAREN: return ray_error("parse", NULL); case PA_RBRACK: return ray_error("parse", NULL); case PA_RBRACE: return ray_error("parse", NULL); @@ -889,6 +890,26 @@ static ray_t* parse_expr_inner(ray_parser_t *p) { default: result = parse_name(p); break; /* operators like +, *, etc. */ } + /* A leaf token must not be glued to another: a quote, a colon, or a + * name/number character directly after a symbol, keyword, name or + * number is a parse error. Without this, nothing separated adjacent + * tokens, so `['a:1]` lexed as the symbol `a` followed by the keyword + * symbol `:1` (a two-element vector printed as `[a 1]`), and `(+ 1'a)` + * or `0Na` quietly became something other than what was written. + * Brackets and strings stay self-delimiting on both sides: `fn[x]`, + * `gds(take ..)`, `(f x)(g y)` and `(list "A""B")` are established + * usage. */ + if (leaf && result && !RAY_IS_ERR(result)) { + char c = *p->pos; + bool glued = c == '\'' || c == ':' || PA(c) == PA_ALPHA || PA(c) == PA_DIGIT || + c == '_' || c == '.' || c == '-' || c == '?' || c == '!'; + if (glued) { + ray_release(result); + fixup_pos(p, before); + return ray_error("parse", "unexpected '%c' directly after a token; separate tokens with whitespace", c); + } + } + /* Fixup line/col: leaf parsers advance pos without updating line/col. * Compound parsers (list/vector/dict) use advance() internally and * call skip_ws_and_comments, so their line/col is already accurate. */ diff --git a/src/mem/heap.h b/src/mem/heap.h index 26a88d3f4..9b8b61293 100644 --- a/src/mem/heap.h +++ b/src/mem/heap.h @@ -58,7 +58,8 @@ * Bit 0x10 vectors: RAY_ATTR_SLICE * Bit 0x20 -RAY_SYM: ATTR_QUOTED (quoted/literal symbol; default = name reference) * Bit 0x20 vectors: RAY_ATTR_SORTED (non-descending order marker) - * Bit 0x40 vectors: RAY_ATTR_HAS_NULLS (sentinel-encoded; payload is truth) + * Bit 0x40 vectors: RAY_ATTR_HAS_NULLS (sentinel-encoded; payload is truth; + * a slice inherits its parent's bit) * Bit 0x80 all types: RAY_ATTR_ARENA (arena-allocated, no refcount) * * Overlapping bit values are safe because consumers always check the type tag diff --git a/src/ops/builtins.c b/src/ops/builtins.c index 8fba4b22a..7e0c4c171 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -2334,11 +2334,36 @@ ray_t* ray_dict_fn(ray_t* keys, ray_t* vals) { return ray_dict_new(keys, vlist); } -/* (nil? x) -> true if x is null */ +/* (nil? x) -> true if x is null. + * + * Element-wise over a vector or a boxed list: one BOOL per element, the + * same answer the query path's OP_ISNULL gives per row, so `nil?` means + * the same thing inside and outside a query (#485). Nulls are in-band + * (sentinels, the empty symbol, the empty string), so ray_vec_is_null + * decides per element regardless of the HAS_NULLS hint. A list element + * that is not an atom is not null. Atoms, the null object, and any + * other container (a table, a dict) answer for the object itself. */ ray_t* ray_nil_fn(ray_t* x) { RAY_ASSERT_VALUE(x); if (RAY_IS_NULL(x)) return ray_bool(true); - if (ray_is_atom(x) && RAY_ATOM_IS_NULL(x)) return ray_bool(true); + if (ray_is_atom(x)) return ray_bool(RAY_ATOM_IS_NULL(x)); + if (ray_is_vec(x) || x->type == RAY_LIST) { + int64_t n = ray_len(x); + ray_t* out = ray_vec_new(RAY_BOOL, n); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + uint8_t* o = (uint8_t*)ray_data(out); + if (x->type == RAY_LIST) { + ray_t** e = (ray_t**)ray_data(x); + for (int64_t i = 0; i < n; i++) + o[i] = (uint8_t)(!e[i] || RAY_IS_NULL(e[i]) || + (ray_is_atom(e[i]) && RAY_ATOM_IS_NULL(e[i]))); + } else { + for (int64_t i = 0; i < n; i++) + o[i] = (uint8_t)ray_vec_is_null(x, i); + } + out->len = n; + return out; + } return ray_bool(false); } diff --git a/src/ops/journal.c b/src/ops/journal.c index 4b397f35a..fcf5d20d6 100644 --- a/src/ops/journal.c +++ b/src/ops/journal.c @@ -91,6 +91,8 @@ ray_t* ray_log_open_fn(ray_t** args, int64_t n) { ray_t* ray_log_write_fn(ray_t* expr) { if (!ray_journal_is_open()) return ray_error("noopen", ".log.write: no journal open (start with -l/-L)"); + if (ray_ipc_auto_journal_eval()) + return ray_error("domain", ".log.write is disabled inside auto-journaled IPC eval"); if (!expr) return ray_error("type", ".log.write expects an argument"); bool owned = false; diff --git a/src/ops/system.c b/src/ops/system.c index 5a876732b..d7f16e356 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -1518,17 +1518,109 @@ ray_t* ray_hpost_fn(ray_t* handle, ray_t* msg) { * hook, or -1 outside any hook. Registered variadic so both * `(.ipc.handle)` (no args) and `(.ipc.handle 0)` (one arg, ignored) * work — matches the convention of `.sys.gc` / `.sys.info`. */ +/* Build {handle limit_bytes limit_frames queued_bytes queued_frames hwm_bytes} + * for a live connection. */ +static ray_t* ipc_tx_info_dict(int64_t h, const ray_ipc_tx_info_t* ti) { + static const char* const names[6] = { "handle", "limit_bytes", "limit_frames", + "queued_bytes", "queued_frames", "hwm_bytes" }; + int64_t vals_i[6] = { h, ti->limit_bytes, ti->limit_frames, + ti->queued_bytes, ti->queued_frames, ti->hwm_bytes }; + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 6); + ray_t* vals = ray_list_new(6); + if (!keys || RAY_IS_ERR(keys) || !vals || RAY_IS_ERR(vals)) { + if (keys && !RAY_IS_ERR(keys)) ray_release(keys); + if (vals && !RAY_IS_ERR(vals)) ray_release(vals); + return ray_error("oom", NULL); + } + for (int i = 0; i < 6; i++) { + int64_t k = ray_sym_intern(names[i], strlen(names[i])); + keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + ray_t* v = make_i64(vals_i[i]); + vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + } + return ray_dict_new(keys, vals); +} + +static bool ipc_arg_i64(ray_t* x, int64_t* out) { + if (!x || !ray_is_atom(x)) return false; + if (x->type == -RAY_I64) { *out = x->i64; return true; } + if (x->type == -RAY_I32) { *out = x->i32; return true; } + return false; +} + +/* `(.ipc.handle)` (no args) and `(.ipc.handle 0)` (one arg, ignored) + * answer the current connection's handle, -1 outside a hook. Given a + * LIVE connection handle, `(.ipc.handle h)` instead returns that + * connection's transmit-queue view (#486): its effective backlog limits, + * the bytes and frames queued right now, and its high-water mark. */ ray_t* ray_ipc_handle_fn(ray_t** args, int64_t n) { - (void)args; (void)n; + int64_t h; + if (n == 1 && ipc_arg_i64(args[0], &h)) { + ray_ipc_tx_info_t ti; + if (ray_ipc_tx_info(h, &ti) == RAY_OK) return ipc_tx_info_dict(h, &ti); + } return make_i64(ray_ipc_current_handle()); } +static ray_t* ipc_txlimit_dict(int64_t bytes, int64_t frames) { + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 2); + ray_t* vals = ray_list_new(2); + if (!keys || RAY_IS_ERR(keys) || !vals || RAY_IS_ERR(vals)) { + if (keys && !RAY_IS_ERR(keys)) ray_release(keys); + if (vals && !RAY_IS_ERR(vals)) ray_release(vals); + return ray_error("oom", NULL); + } + int64_t k = ray_sym_intern("bytes", 5); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + k = ray_sym_intern("frames", 6); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + ray_t* v = make_i64(bytes); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + v = make_i64(frames); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + return ray_dict_new(keys, vals); +} + +/* (.ipc.txlimit) -> {bytes frames}: the process default + * (.ipc.txlimit bytes [frames]) -> set the default; frames 0 = unlimited + * (.ipc.txlimit h bytes frames) -> override one live connection + * Every form answers with the limits now in force for its target. */ +ray_t* ray_ipc_txlimit_fn(ray_t** args, int64_t n) { + if (n > 3) return ray_error("rank", ".ipc.txlimit takes 0 to 3 arguments, got %lld", (long long)n); + int64_t a[3] = {0, 0, 0}; + for (int64_t i = 0; i < n; i++) + if (!ipc_arg_i64(args[i], &a[i])) + return ray_error("type", ".ipc.txlimit expects integer arguments, got %s", ray_type_name(args[i]->type)); + int64_t bytes, frames; + if (n == 0) { + ray_ipc_tx_limit_get(&bytes, &frames); + return ipc_txlimit_dict(bytes, frames); + } + if (n == 3) { + ray_err_t rc = ray_ipc_tx_limit_set_handle(a[0], a[1], a[2]); + if (rc == RAY_ERR_DOMAIN) + return ray_error("domain", ".ipc.txlimit: bytes must be >= %lld and frames >= 0", (long long)RAY_IPC_TX_MIN_BYTES); + if (rc != RAY_OK) + return ray_error("domain", ".ipc.txlimit: %lld is not a live connection handle", (long long)a[0]); + return ipc_txlimit_dict(a[1], a[2]); + } + ray_ipc_tx_limit_get(&bytes, &frames); + bytes = a[0]; + if (n == 2) frames = a[1]; + if (ray_ipc_tx_limit_set(bytes, frames) != RAY_OK) + return ray_error("domain", ".ipc.txlimit: bytes must be >= %lld and frames >= 0", (long long)RAY_IPC_TX_MIN_BYTES); + return ipc_txlimit_dict(bytes, frames); +} + ray_t* ray_mc_sub_fn(ray_t** args, int64_t n) { - if (n != 2) - return ray_error("domain", ".mc.sub expects 2 arguments"); + if (n < 1 || n > 2) + return ray_error("domain", ".mc.sub expects 1 or 2 arguments"); if (!ray_ipc_context_poll()) return ray_error("domain", ".mc.sub requires a poll IPC context"); - return ray_mcast_sub(ray_ipc_active_poll(), ray_ipc_current_handle(), args[0], args[1]); + ray_t* filter = (n == 2) ? args[1] : RAY_NULL_OBJ; + return ray_mcast_sub(ray_ipc_active_poll(), ray_ipc_current_handle(), args[0], filter); } ray_t* ray_mc_unsub_fn(ray_t* topic) { diff --git a/src/store/col.c b/src/store/col.c index ab99a864c..3db8a4550 100644 --- a/src/store/col.c +++ b/src/store/col.c @@ -732,6 +732,45 @@ ray_err_t ray_col_append_index(const char* path, const void* ix_v, return RAY_OK; } +/* Does the payload hold the type's null sentinel anywhere? Sequential + * read with an early return on the first hit; resolves a slice through + * its parent like every other reader. Types without a sentinel (BOOL, + * U8, SYM, STR, GUID, LIST) answer false — their null state is in-band + * or absent, and the bit means nothing to them on disk. */ +static bool col_payload_has_nulls(ray_t* vec) { + int64_t n = vec->len; + if (n <= 0) return false; + const void* p = ray_data(vec); + switch (vec->type) { + case RAY_F64: { + const double* d = (const double*)p; + for (int64_t i = 0; i < n; i++) if (d[i] != d[i]) return true; + return false; + } + case RAY_F32: { + const float* d = (const float*)p; + for (int64_t i = 0; i < n; i++) if (d[i] != d[i]) return true; + return false; + } + case RAY_I64: case RAY_TIMESTAMP: { + const int64_t* d = (const int64_t*)p; + for (int64_t i = 0; i < n; i++) if (d[i] == NULL_I64) return true; + return false; + } + case RAY_I32: case RAY_DATE: case RAY_TIME: { + const int32_t* d = (const int32_t*)p; + for (int64_t i = 0; i < n; i++) if (d[i] == NULL_I32) return true; + return false; + } + case RAY_I16: { + const int16_t* d = (const int16_t*)p; + for (int64_t i = 0; i < n; i++) if (d[i] == NULL_I16) return true; + return false; + } + default: return false; + } +} + static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { if (!vec || RAY_IS_ERR(vec)) return RAY_ERR_TYPE; if (!path) return RAY_ERR_IO; @@ -849,8 +888,21 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { memset(header.aux + 8, 0, 8); } - /* Clear slice flag — slices are materialized on save. */ - header.attrs &= (uint8_t)~RAY_ATTR_SLICE; + /* Clear slice flag — slices are materialized on save. A slice's + * aux holds the parent pointer and window offset, which must + * never reach disk. */ + if (vec->attrs & RAY_ATTR_SLICE) { + header.attrs &= (uint8_t)~RAY_ATTR_SLICE; + memset(header.aux, 0, 16); + } + /* The persisted HAS_NULLS bit is load-bearing for every reader + * (nothing rescans on load), so derive it from the payload rather + * than trust the producer: a column that holds a sentinel is + * written with the bit set whatever the in-memory header said + * (#495). Only ever sets — a spurious set costs a slow path, a + * missing one costs the answer. */ + if (!(header.attrs & RAY_ATTR_HAS_NULLS) && col_payload_has_nulls(vec)) + header.attrs |= RAY_ATTR_HAS_NULLS; if (!(header.attrs & RAY_ATTR_HAS_NULLS)) memset(header.aux, 0, 16); diff --git a/src/store/part.c b/src/store/part.c index 6bc5dd699..00134c89f 100644 --- a/src/store/part.c +++ b/src/store/part.c @@ -33,6 +33,7 @@ #include "store/splay.h" #include "table/sym.h" #include "table/domain.h" +#include "lang/cal.h" /* MONTHDAYS, date_leap_year — calendar-date validation */ #include #include #include @@ -40,8 +41,11 @@ #include #include -/* Validate YYYY.MM.DD format: exactly 10 chars, dots at pos 4/7, - * month 01-12, day 01-31. */ +/* Validate YYYY.MM.DD format: exactly 10 chars, dots at pos 4/7, and a real + * calendar date. A blanket day 01-31 check let calendar-impossible names like + * 2024.02.31 through; parse_date_dir then silently normalised them into a + * different real day (2024.03.02) — a mislabelled partition key. Validate the + * day against the leap-aware length of its month instead. */ static bool is_date_dir(const char* name) { if (strlen(name) != 10) return false; if (name[4] != '.' || name[7] != '.') return false; @@ -49,9 +53,14 @@ static bool is_date_dir(const char* name) { if (i == 4 || i == 7) continue; if (name[i] < '0' || name[i] > '9') return false; } + int year = (name[0]-'0')*1000 + (name[1]-'0')*100 + + (name[2]-'0')*10 + (name[3]-'0'); int month = (name[5] - '0') * 10 + (name[6] - '0'); int day = (name[8] - '0') * 10 + (name[9] - '0'); - return month >= 1 && month <= 12 && day >= 1 && day <= 31; + if (month < 1 || month > 12 || day < 1) return false; + int leap = date_leap_year(year); + int dim = (int)(MONTHDAYS[leap][month] - MONTHDAYS[leap][month - 1]); + return day <= dim; } /* Check if string is a pure integer (digits only, possibly with leading minus). */ diff --git a/src/vec/vec.c b/src/vec/vec.c index 0bfc4b3bc..815dd1852 100644 --- a/src/vec/vec.c +++ b/src/vec/vec.c @@ -435,7 +435,13 @@ ray_t* ray_vec_slice(ray_t* vec, int64_t offset, int64_t len) { if (!s || RAY_IS_ERR(s)) return s; s->type = parent->type; - s->attrs = RAY_ATTR_SLICE | (parent->attrs & RAY_SYM_W_MASK); + /* A slice inherits the parent's HAS_NULLS hint: it is a window onto + * the same sentinel-encoded payload, and every fast-path gate that + * reads the bit (aggregates, raze, the morsel null bitmap, the save + * path) would otherwise read a window with nulls as null-free and + * fold the sentinel in as a value (#495). Over-approximation when + * the window happens to hold no null is the bit's documented role. */ + s->attrs = RAY_ATTR_SLICE | (parent->attrs & (RAY_SYM_W_MASK | RAY_ATTR_HAS_NULLS)); s->len = len; s->slice_parent = parent; s->slice_offset = parent_offset; diff --git a/test/rfl/expr/cast_unary.rfl b/test/rfl/expr/cast_unary.rfl index be4304665..b801aa24a 100644 --- a/test/rfl/expr/cast_unary.rfl +++ b/test/rfl/expr/cast_unary.rfl @@ -76,9 +76,9 @@ ;; =================================================================== ;; ISNULL over I64 vec (exec_elementwise_unary lines 1320-1327) -;; Non-null vec: result is all false +;; Non-null vec: result is all false — one bool per element (#485) ;; =================================================================== -(nil? (til 5)) -- false +(nil? (til 5)) -- [false false false false false] (map nil? (til 3)) -- [false false false] ;; ISNULL on nullable vector detects null positions diff --git a/test/rfl/lang/parse_branch_cov.rfl b/test/rfl/lang/parse_branch_cov.rfl index bda6b0726..046871d53 100644 --- a/test/rfl/lang/parse_branch_cov.rfl +++ b/test/rfl/lang/parse_branch_cov.rfl @@ -104,16 +104,17 @@ ;; 3. BARE-0N IDENTIFIER-CONTINUATION GUARDS (parse_number :214-218) ;; ════════════════════════════════════════════════════════════════════ ;; `0N` followed by a letter/digit/underscore that is NOT a suffix is -;; *not* a null — the digit `0` is taken and the continuation parsed as a -;; separate trailing name, so `(do 0 )` evaluates to the name value. +;; *not* a null — the digit `0` is taken, and what follows is a second +;; token glued to it, which is a parse error since #484 (before, it was +;; silently read as `(do 0 )` and evaluated to the name's value). (set Na 7) -0Na -- 7 +0Na !- parse (set Nz 9) -0Nz -- 9 +0Nz !- parse (set N3 3) -0N3 -- 3 +0N3 !- parse (set N_x 11) -0N_x -- 11 +0N_x !- parse ;; ════════════════════════════════════════════════════════════════════ ;; 4. FLOAT / EXPONENT / INTEGER-OVERFLOW PROMOTION (parse_number) @@ -164,13 +165,13 @@ ;; time without sub-second fraction is still valid; eval pins the value. (type (parse "12:30:45")) -- 'time (eval (parse "12:30:45")) -- 12:30:45.000 -;; 2-digit + colon where try_parse_time fails → fall through to number, -;; then the remainder is re-lexed (parse_number :281-289, try_parse_time -;; NULL at MM :151, at MM-colon :157, at SS digits). Each yields -;; `(do 12 )` whose value is the trailing keyword sym. -(eval (parse "12:3x")) -- '3x -(eval (parse "12:30x")) -- '30x -(eval (parse "12:30:4x")) -- '4x +;; 2-digit + colon where try_parse_time fails → fall through to number +;; (parse_number, try_parse_time NULL at MM / MM-colon / SS digits); the +;; remainder is then a second token glued to the number, a parse error +;; since #484 (before, each re-lexed to `(do 12 )`). +(parse "12:3x") !- parse +(parse "12:30x") !- parse +(parse "12:30:4x") !- parse ;; timestamp YYYY.MM.DDDhh:mm:ss.nnnnnnnnn 2024.01.15D12:30:45.000000000 -- 2024.01.15D12:30:45.000000000 (type 2024.01.15D12:30:45.000000000) -- 'timestamp diff --git a/test/rfl/lang/parse_token_boundary.rfl b/test/rfl/lang/parse_token_boundary.rfl new file mode 100644 index 000000000..a51cb166d --- /dev/null +++ b/test/rfl/lang/parse_token_boundary.rfl @@ -0,0 +1,54 @@ +;; parse_token_boundary.rfl — a leaf token cannot be glued to another (#484). +;; +;; Regression: nothing required a delimiter between tokens, so `['a:1]` +;; lexed as the symbol `a` followed by the keyword symbol `:1` — a +;; two-element symbol vector that printed as `[a 1]` — and `(+ 1'a)` or +;; `0Na` quietly became something else. A symbol, keyword, name or +;; number directly followed by a quote, a colon, or another name/number +;; character is now a parse error at that position. Brackets and strings +;; stay self-delimiting on both sides: `fn[x]`, `gds(take ..)`, +;; `(f x)(g y)` and `(list "A""B")` still parse as before. + +;; ── the reported case and its relatives ── +(count ['a:1]) !- parse +['a:1] !- parse +[a:1] !- parse +(list 'a:1) !- parse +['a'b] !- parse +[1'a] !- parse +(+ 1'a) !- parse +(nil?'a) !- parse +:a:b !- parse +0Na !- parse +1x !- parse +(parse "12:3x") !- parse + +;; ── a colon inside a symbol is spelled through a cast ── +(count (list (as 'symbol "a:1"))) -- 1 +(type (as 'symbol "a:1")) -- 'sym + +;; ── everything delimited stays as it was ── +(count ['a 'b]) -- 2 +['a :b] -- [a b] +(count [1 2 3]) -- 3 +(+ 1 2) -- 3 +{a: 1} -- {a:1} +{a:1} -- {a:1} +(at {a: 1} 'a) -- 1 +(list "A""B""C") -- (list "A" "B" "C") +((fn [x] x) 5) -- 5 +(set _tb 1)(+ _tb 1) -- 2 +(count (list [1 2]3)) -- 2 +(count (list 1[2])) -- 2 +((fn[x] x) 5) -- 5 +(count (list [1 2] [3 4])) -- 2 +(count [2024.01.02D01:02:03.004005006 0Np]) -- 2 +(nil? ') -- true +-1 -- -1 +(- 5 2) -- 3 +[1 -2] -- [1 -2] +(count (quote (+ 1 2))) -- 3 +'a' -- "a" +'\n' -- "\n" +;; a comment right after a token is a delimiter too +(+ 1 2);; trailing comment diff --git a/test/rfl/null/nil_elementwise.rfl b/test/rfl/null/nil_elementwise.rfl new file mode 100644 index 000000000..9b133250e --- /dev/null +++ b/test/rfl/null/nil_elementwise.rfl @@ -0,0 +1,53 @@ +;; nil_elementwise.rfl — `nil?` is element-wise over vectors and lists +;; everywhere, not only inside queries (#485). +;; +;; Before: outside a query `nil?` tested whether the argument OBJECT was +;; null, so `(nil? [1 0N 3])` was `false` while `(select {n: (nil? v)})` +;; gave one bool per row. Now a vector or list argument yields a BOOL +;; vector, one entry per element, agreeing with the query opcode. Atoms +;; and the null object answer as before. + +;; ── atoms and the null object: unchanged ── +(nil? 0Nl) -- true +(nil? 1) -- false +(nil? 0Nf) -- true +(nil? 1.5) -- false +(nil? ') -- true +(nil? 'a) -- false +(nil? "") -- true +(nil? "x") -- false +(nil? null) -- true + +;; ── typed vectors: one bool per element, B8 result ── +(nil? [1 0N 3]) -- [false true false] +(type (nil? [1 0N 3])) -- 'B8 +(nil? [1.5 0Nf 2.5]) -- [false true false] +(nil? [1i 0Ni]) -- [false true] +(nil? [2024.01.01 0Nd]) -- [false true] +(nil? [2000.01.01D00:00:00.000000001 0Np]) -- [false true] +(nil? [a ' b]) -- [false true false] +(nil? (list "x" "" "y")) -- [false true false] +(nil? [true false]) -- [false false] +(nil? [1 2 3]) -- [false false false] +(nil? (as 'I64 [])) -- (as 'B8 []) +;; sentinel is the truth, whatever the HAS_NULLS hint says +(nil? (concat [1 0N] [0N 2])) -- [false true true false] + +;; ── boxed lists: null atoms are null, anything else is not ── +(nil? (list 1 0N "x" [1 2])) -- [false true false false] +(nil? (list (list 0N))) -- [false] +(nil? (list)) -- (as 'B8 []) + +;; ── the result composes without a cast ── +(where (nil? [1 0N 3 0N])) -- [1 3] +(count (where (nil? [0N 0N 1]))) -- 2 +(sum (as 'I64 (nil? [1 0N 3]))) -- 1 + +;; ── containers other than vectors and lists are whole objects, as before ── +(nil? (table [a] (list [1]))) -- false +(nil? (dict ['a] [1])) -- false + +;; ── the query path answers the same ── +(set t (table [v] (list [1 0N 3]))) +(at (select {n: (nil? v) from: t}) 'n) -- (nil? (at t 'v)) +(count (select {from: t where: (nil? v)})) -- 1 diff --git a/test/rfl/null/slice_has_nulls.rfl b/test/rfl/null/slice_has_nulls.rfl new file mode 100644 index 000000000..c30a383ec --- /dev/null +++ b/test/rfl/null/slice_has_nulls.rfl @@ -0,0 +1,60 @@ +;; slice_has_nulls.rfl — a slice sees its parent's nulls, in memory and on +;; disk (#495). +;; +;; Regression: ray_vec_slice built the slice header without the parent's +;; RAY_ATTR_HAS_NULLS hint, and every fast-path gate that trusts the hint +;; (sum/min/max/avg, raze, the save path) read a window holding a null +;; sentinel as null-free — folding INT64_MIN into a sum, materialising it +;; as a plain number through raze, and persisting the column with the bit +;; clear so every later reader was wrong too. (take D ) on a dict +;; slices the key vector, so three ordinary verbs produced one. + +;; ── in memory: the slice answers what the whole vector answers ── +(set D (dict (as 'I64 [1 0N 3 4]) [10 20 30 40])) +(set W (key D)) +(set S (key (take D [0 3]))) +(format "%s" S) -- "[1 0Nl 3]s" +(sum S) -- 4 +(sum (take W 3)) -- 4 +(min S) -- 1 +(max S) -- 3 +(avg S) -- 2.0 +(nil? S) -- [false true false] +(count (where (nil? S))) -- 1 + +;; ── raze keeps the null, whichever path it takes ── +(set R (raze (enlist S))) +(format "%s" R) -- "[1 0Nl 3]s" +(sum R) -- 4 +(sum (raze (list S S))) -- 8 +(sum (concat S (take S 0))) -- 4 +(sum (at S (til 3))) -- 4 + +;; ── the same through F64 and a nested slice ── +(set DF (dict (as 'F64 [1.5 0Nf 2.5 4.0]) [10 20 30 40])) +(set SF (key (take DF [0 3]))) +(sum SF) -- 4.0 +(min SF) -- 1.5 +(sum (take SF 2)) -- 1.5 +(sum (raze (enlist SF))) -- 4.0 + +;; a slice whose window holds no null still answers correctly +(set S2 (key (take D [2 4]))) +(sum S2) -- 7 +(nil? S2) -- [false false] + +;; ── on disk: the persisted bit is derived from the payload ── +(.sys.exec "rm -rf /tmp/rfl_slice_nulls") +(set G (as 'I64 [1 0N 3])) +(.db.splayed.set "/tmp/rfl_slice_nulls/good/" (table ['x] (list G))) +(.db.splayed.set "/tmp/rfl_slice_nulls/slice/" (table ['x] (list S))) +(.db.splayed.set "/tmp/rfl_slice_nulls/razed/" (table ['x] (list R))) +(.db.splayed.set "/tmp/rfl_slice_nulls/f64/" (table ['x] (list SF))) +(sum (at (.db.splayed.get "/tmp/rfl_slice_nulls/good/") 'x)) -- 4 +(sum (at (.db.splayed.get "/tmp/rfl_slice_nulls/slice/") 'x)) -- 4 +(sum (at (.db.splayed.get "/tmp/rfl_slice_nulls/razed/") 'x)) -- 4 +(format "%s" (at (.db.splayed.get "/tmp/rfl_slice_nulls/razed/") 'x)) -- "[1 0Nl 3]s" +(sum (at (.db.splayed.get "/tmp/rfl_slice_nulls/f64/") 'x)) -- 4.0 +;; the header byte itself: 0x40 (HAS_NULLS) on every one of them +(.sys.exec "for d in good slice razed f64; do [ \"$(xxd -s 19 -l 1 -p /tmp/rfl_slice_nulls/$d/x)\" = 40 ] || exit 1; done") -- 0 +(.sys.exec "rm -rf /tmp/rfl_slice_nulls") diff --git a/test/rfl/query/width_matrix.rfl b/test/rfl/query/width_matrix.rfl index bbcccbda3..4e8237807 100644 --- a/test/rfl/query/width_matrix.rfl +++ b/test/rfl/query/width_matrix.rfl @@ -1041,7 +1041,8 @@ ;; reflect how the vector's own consumers (sum, the DA accumulator) ;; treat it: they gate on the VECTOR's HAS_NULLS attribute first, which ;; is correctly unset here. -(nil? wm5_va) -- false +;; (element-wise since #485: no element is null) +(nil? wm5_va) -- [false false false false] (sum wm5_va) -- -2147483518 (at wm5_va 1) -- 100 (set wm5_vf [7i 7i 3i 3i]) diff --git a/test/rfl/system/ipc_txlimit.rfl b/test/rfl/system/ipc_txlimit.rfl new file mode 100644 index 000000000..8d163f3cb --- /dev/null +++ b/test/rfl/system/ipc_txlimit.rfl @@ -0,0 +1,22 @@ +;; ipc_txlimit.rfl — the per-connection transmit backlog is configurable +;; at runtime (#486). (.ipc.txlimit) reads the process default, +;; (.ipc.txlimit bytes [frames]) sets it, (.ipc.txlimit h bytes frames) +;; overrides one live connection. The overflow behaviour itself is +;; exercised with real sockets in test/test_mcast.c. +(at (.ipc.txlimit) 'bytes) -- 268435456 +(at (.ipc.txlimit) 'frames) -- 0 +(at (.ipc.txlimit 1048576) 'bytes) -- 1048576 +(at (.ipc.txlimit 1048576) 'frames) -- 0 +(at (.ipc.txlimit 2097152 8) 'frames) -- 8 +(at (.ipc.txlimit) 'bytes) -- 2097152 +;; bounds: at least one 4 KiB frame, frames >= 0 (0 = unlimited) +(.ipc.txlimit 0) !- domain +(.ipc.txlimit 1024) !- domain +(.ipc.txlimit 65536 -1) !- domain +(.ipc.txlimit "x") !- type +(.ipc.txlimit 1 2 3 4) !- rank +;; a per-connection override needs a live connection handle +(.ipc.txlimit 12345 65536 0) !- domain +(.ipc.handle 12345) -- -1 +;; restore the built-in default +(at (.ipc.txlimit 268435456 0) 'bytes) -- 268435456 diff --git a/test/rfl/system/log_journal_advanced.rfl b/test/rfl/system/log_journal_advanced.rfl index 51b222856..dd8974362 100644 --- a/test/rfl/system/log_journal_advanced.rfl +++ b/test/rfl/system/log_journal_advanced.rfl @@ -8,7 +8,7 @@ ;; Phase C: per-entry eval error in log warns-and-continues, doesn't ;; abort replay (commit message documents this; basic test ;; only exercises framing badtail) -;; Phase D: .log.write manual escape hatch round-trips via replay +;; Phase D: .log.write is rejected inside auto-journaled IPC eval ;; ── IPC connect with handshake-level retry ────────────────────────── ;; A /dev/tcp probe reports ready the instant the server calls listen(), @@ -130,11 +130,11 @@ (.sys.exec "rm -f /tmp/rftest_jerr*") ;; ════════════════════════════════════════════════════════════════════ -;; Phase D — .log.write manual entry round-trips via replay +;; Phase D — .log.write inside auto-journaled IPC eval is rejected ;; ════════════════════════════════════════════════════════════════════ -;; The escape hatch lets a Rayfall handler journal an arbitrary -;; expression out-of-band. Currently zero coverage — a regression -;; that broke the API would only surface for users. +;; A journaled server logs every SYNC IPC payload before evaluation. +;; Letting the payload call .log.write as well would persist nested +;; writes in addition to the already-logged outer request. (.sys.exec "pkill -KILL -f '[r]ayforce -l /tmp/rftest_jwr' 2>/dev/null; true") (.sys.exec "rm -f /tmp/rftest_jwr*") @@ -142,18 +142,9 @@ (.sys.exec "for i in $(seq 30); do bash -c '(echo > /dev/tcp/127.0.0.1/19994) 2>/dev/null' && exit 0; sleep 0.1; done; exit 1") -- 0 (set hD (wait_ipc "127.0.0.1:19994" 50)) -;; Journal a string-eval entry manually. On replay this string will -;; be re-evaluated (string payloads go through ray_eval_str), binding d1. -(.ipc.send hD "(.log.write \"(set d1 999)\")") +(.ipc.send hD "(.log.write \"(set d1 999)\")") !- domain (.ipc.close hD) (.sys.exec "pkill -TERM -f '[r]ayforce -l /tmp/rftest_jwr -p 19994' 2>/dev/null; true") (.sys.exec "for i in $(seq 30); do pgrep -f '[r]ayforce -l /tmp/rftest_jwr -p 19994' >/dev/null || exit 0; sleep 0.1; done; exit 1") -- 0 - -(.sys.exec "./rayforce -l /tmp/rftest_jwr -p 19994 /dev/null 2>&1 &") -(.sys.exec "for i in $(seq 30); do bash -c '(echo > /dev/tcp/127.0.0.1/19994) 2>/dev/null' && exit 0; sleep 0.1; done; exit 1") -- 0 - -(set hD2 (wait_ipc "127.0.0.1:19994" 50)) -(.ipc.send hD2 "d1") -- 999 -(.ipc.close hD2) (.sys.exec "pkill -KILL -f '[r]ayforce -l /tmp/rftest_jwr' 2>/dev/null; true") (.sys.exec "rm -f /tmp/rftest_jwr*") diff --git a/test/rfl/system/part.rfl b/test/rfl/system/part.rfl index 9d67478d9..978978232 100644 --- a/test/rfl/system/part.rfl +++ b/test/rfl/system/part.rfl @@ -393,5 +393,35 @@ (at (at (at Rnested 'n) 1) 0) -- 9.0 (.sys.exec "rm -rf /tmp/rfl_part_nested") +;; ────── calendar-impossible date dirs are not date partitions ────── +;; is_date_dir accepted any day 01-31, so a shaped-but-impossible dir like +;; 2024.02.31 classified as RAY_MC_DATE and parse_date_dir silently normalised +;; it to a real but WRONG day (2024.03.02). It must fail date validation: the +;; set then drops to RAY_MC_SYM (partition-key column 'part, keys kept literal) +;; instead of masquerading as a mislabelled date. +(.sys.exec "rm -rf /tmp/rfl_part_badcal /tmp/rfl_part_leap") +(set BC-A (table [v] (list [1 2 3]))) +(set BC-B (table [v] (list [4 5]))) +(.db.splayed.set "/tmp/rfl_part_badcal/2024.02.28/t/" BC-A) +(.db.splayed.set "/tmp/rfl_part_badcal/2024.02.31/t/" BC-B) +(set Pbad (.db.parted.get "/tmp/rfl_part_badcal/" 't)) +;; not 'date: the impossible Feb 31 defeats the all-date classification +(first (key Pbad)) -- 'part +(key Pbad) -- ['part 'v] +(count Pbad) -- 5 +(sum (at Pbad 'v)) -- 15 +;; The impossible day is kept LITERAL, not remapped: the partition-key column +;; holds the exact directory names. On dev this column is 'date and Feb 31's +;; rows read back 2024.03.02 — the silent mislabel this fix removes. +(at Pbad 'part) -- (as 'sym ["2024.02.28" "2024.02.28" "2024.02.28" "2024.02.31" "2024.02.31"]) +;; No over-rejection: 2024 is a leap year, so the real leap day 2024.02.29 +;; still classifies as a date partition ('date column). +(set LP (table [v] (list [7 8]))) +(.db.splayed.set "/tmp/rfl_part_leap/2024.02.29/t/" LP) +(set Pleap (.db.parted.get "/tmp/rfl_part_leap/" 't)) +(first (key Pleap)) -- 'date +(sum (at Pleap 'v)) -- 15 +(.sys.exec "rm -rf /tmp/rfl_part_badcal /tmp/rfl_part_leap") + ;; ────────────── teardown ────────────── (.sys.exec "rm -rf /tmp/rfl_part_date /tmp/rfl_part_int /tmp/rfl_part_sym /tmp/rfl_part_single /tmp/rfl_part_empty /tmp/rfl_part_missing /tmp/rfl_part_three /tmp/rfl_part_cd /tmp/rfl_part_cd_sym /tmp/rfl_part_minute /tmp/rfl_part_like /tmp/rfl_part_mc /tmp/rfl_part_mb") diff --git a/test/rfl/system/piped_timers.rfl b/test/rfl/system/piped_timers.rfl new file mode 100644 index 000000000..83cb6a64b --- /dev/null +++ b/test/rfl/system/piped_timers.rfl @@ -0,0 +1,39 @@ +;; piped_timers.rfl — timers keep firing while a piped (non-TTY) stdin is +;; held open, and a process stays for its pending timers after input ends +;; (#493, the narrowed report). +;; +;; Regression: run_piped blocked in fgets(), so with a producer holding +;; the pipe open a 100 ms timer fired only when the writer closed; and at +;; EOF the poll loop was entered only for registered selectors, so a +;; timer-only run printed the timer id and exited without firing it. +;; +;; Each case runs ./rayforce as a subprocess. The callback exits with a +;; distinctive code, so the exit code says whether it ran; the wall clock +;; says whether it ran before the producer let go. Process substitution +;; keeps the write end open in the background without making the shell +;; wait for it, so the elapsed time is rayforce's alone. +(.sys.exec "rm -f /tmp/rfl_pt.sh /tmp/rfl_pt.rfl") +(.sys.exec "printf '%s\n' '(.time.timer.set 100 1 (fn [t] (exit 7)))' > /tmp/rfl_pt.rfl") +(.sys.exec "printf '%s\n' 's=$(date +%s)' 'exec 3< <(printf \"(.time.timer.set 100 1 (fn [t] (exit 7)))\\n\"; sleep 4)' './rayforce -i <&3; rc=$?' 'exec 3<&-' 'e=$(date +%s)' '[ $rc -eq 7 ] && [ $((e-s)) -le 1 ]' > /tmp/rfl_pt.sh") + +;; pipe held open for 4 s: the callback runs at 100 ms, not at close +(.sys.exec "bash /tmp/rfl_pt.sh") -- 0 + +;; the same with a listener: IPC is served while stdin is open, and the +;; timer still fires early +(.sys.exec "sed -i.bak 's#./rayforce -i#./rayforce -i -p 19973#' /tmp/rfl_pt.sh; bash /tmp/rfl_pt.sh") -- 0 + +;; timer-only input that reaches EOF at once: the process stays for the +;; timer instead of exiting 0 with it unfired +(.sys.exec "./rayforce -i < /tmp/rfl_pt.rfl; [ $? -eq 7 ]") -- 0 + +;; a script file that armed a one-shot timer, no listener: same +(.sys.exec "./rayforce /tmp/rfl_pt.rfl /tmp/rfl_pt2.rfl; s=$(date +%s); ./rayforce /tmp/rfl_pt2.rfl /dev/null 2>&1; e=$(date +%s); [ $((e-s)) -le 1 ]") -- 0 + +(.sys.exec "rm -f /tmp/rfl_pt.sh /tmp/rfl_pt.sh.bak /tmp/rfl_pt.rfl /tmp/rfl_pt2.rfl") diff --git a/test/rfl/system/reserved_namespace.rfl b/test/rfl/system/reserved_namespace.rfl index 2336812e6..f8bc132dd 100644 --- a/test/rfl/system/reserved_namespace.rfl +++ b/test/rfl/system/reserved_namespace.rfl @@ -27,8 +27,8 @@ ;; getenv, setenv (count .fs) -- 2 ;; size, list -(count .ipc) -- 5 -;; open, close, send, post, handle +(count .ipc) -- 6 +;; open, close, send, post, handle, txlimit (count .csv) -- 4 ;; read, splayed, parted, write ;; .db.* — three-level reserved namespace for storage I/O. The diff --git a/test/rfl/system/system_branch_cov2.rfl b/test/rfl/system/system_branch_cov2.rfl index d1a1c3eec..806dfcc9a 100644 --- a/test/rfl/system/system_branch_cov2.rfl +++ b/test/rfl/system/system_branch_cov2.rfl @@ -13,7 +13,8 @@ (quote 42) -- 42 (quote 'hello) -- 'hello (quote [1 2 3]) -- [1 2 3] -(nil? (quote (+ 1 2))) -- false +;; a quoted form is a 3-element list; nil? is element-wise over it (#485) +(nil? (quote (+ 1 2))) -- [false false false] ;; ══════════════════════════════════════════════════════════════════════ ;; ray_return_fn (lines 590-593) diff --git a/test/test_index.c b/test/test_index.c index bb2d3ac93..af3a02135 100644 --- a/test/test_index.c +++ b/test/test_index.c @@ -517,7 +517,9 @@ static test_result_t test_index_aux_helper_slice(void) { ray_t* s = ray_vec_slice(v, 2, 4); TEST_ASSERT_FALSE(RAY_IS_ERR(s)); TEST_ASSERT_TRUE(s->attrs & RAY_ATTR_SLICE); - TEST_ASSERT_FALSE(s->attrs & RAY_ATTR_HAS_NULLS); + /* A slice inherits the parent's HAS_NULLS hint (#495): the gates + * that read the bit would otherwise treat the window as null-free. */ + TEST_ASSERT_TRUE(s->attrs & RAY_ATTR_HAS_NULLS); /* ray_vec_is_null still works correctly on the slice. */ TEST_ASSERT_FALSE(ray_vec_is_null(s, 0)); /* parent row 2 — not null */ diff --git a/test/test_journal.c b/test/test_journal.c index bd956828c..f4b0e173b 100644 --- a/test/test_journal.c +++ b/test/test_journal.c @@ -1164,6 +1164,36 @@ static test_result_t test_journal_snapshot_empty_env(void) { PASS(); } +/* 7e. Snapshot restores user-defined functions without binding errors. */ +static test_result_t test_journal_snapshot_function_binding_recovers(void) { + char base[256]; make_base(base, sizeof(base), "snap_fn"); + + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_OK); + ray_t* r = ray_eval_str("(set jrn_snap_fn (fn [x] (+ x 1)))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + + TEST_ASSERT_EQ_I(ray_journal_snapshot(), RAY_OK); + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + + int64_t sym = ray_sym_intern("jrn_snap_fn", 11); + ray_t* zero = ray_i64(0); + TEST_ASSERT_NOT_NULL(zero); + TEST_ASSERT_EQ_I(ray_env_set(sym, zero), RAY_OK); + ray_release(zero); + + TEST_ASSERT_EQ_I(ray_journal_recover(base), RAY_OK); + ray_t* val = ray_eval_str("(jrn_snap_fn 41)"); + TEST_ASSERT_NOT_NULL(val); + TEST_ASSERT_FALSE(RAY_IS_ERR(val)); + TEST_ASSERT_EQ_I(val->i64, 42); + ray_release(val); + + cleanup_base(base); + PASS(); +} + /* ═══════════════════════════════════════════════════════════════════════ * 8. is_open * ═══════════════════════════════════════════════════════════════════════ */ @@ -1993,7 +2023,30 @@ static test_result_t test_ops_write_noopen(void) { PASS(); } -/* 22q. ray_log_write_fn: pay_size <= 0 (lines 100-103). +/* 22q. ray_log_write_fn: reject explicit writes from auto-journaled IPC eval. */ +static test_result_t test_ops_write_rejects_auto_journal_eval(void) { + char base[256]; make_base(base, sizeof(base), "ops_auto_eval"); + + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_OK); + + ray_t* expr = ray_i64(42); + TEST_ASSERT_NOT_NULL(expr); + ray_ipc_set_auto_journal_eval_for_test(true); + ray_t* r = ray_log_write_fn(expr); + ray_ipc_set_auto_journal_eval_for_test(false); + ray_release(expr); + + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_TRUE(RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "domain"); + ray_error_free(r); + + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + cleanup_base(base); + PASS(); +} + +/* 22r. ray_log_write_fn: pay_size <= 0 (lines 100-103). * * ray_serde_size returns 0 for object types not in its switch (any type * value that is not a known atom/vector/container type). We manufacture @@ -2369,6 +2422,7 @@ const test_entry_t journal_entries[] = { { "journal/snapshot_basic", test_journal_snapshot_basic, jrn_setup, jrn_teardown }, { "journal/open_with_qdb", test_journal_open_with_qdb, jrn_setup, jrn_teardown }, { "journal/snapshot_empty_env", test_journal_snapshot_empty_env, jrn_setup, jrn_teardown }, + { "journal/snapshot_function_binding", test_journal_snapshot_function_binding_recovers, jrn_setup, jrn_teardown }, /* is_open */ { "journal/is_open_states", test_journal_is_open_states, jrn_setup, jrn_teardown }, /* Misc */ @@ -2407,6 +2461,7 @@ const test_entry_t journal_entries[] = { { "journal/ops_open_sync_mode", test_ops_open_sync_mode, jrn_setup, jrn_teardown }, { "journal/ops_write_null_expr", test_ops_write_null_expr, jrn_setup, jrn_teardown }, { "journal/ops_write_noopen", test_ops_write_noopen, jrn_setup, jrn_teardown }, + { "journal/ops_write_auto_journal_eval", test_ops_write_rejects_auto_journal_eval, jrn_setup, jrn_teardown }, { "journal/ops_write_serde_size_zero", test_ops_write_serde_size_zero, jrn_setup, jrn_teardown }, /* End-to-end RFL round-trip */ { "journal/replay_symbol_head_both_forms", test_journal_replay_symbol_head_both_forms, jrn_setup, jrn_teardown }, diff --git a/test/test_lang.c b/test/test_lang.c index 2723e3fb9..06fff1290 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -5716,13 +5716,14 @@ static test_result_t test_temporal_extract_slice_nulls(void) { TEST_ASSERT_TRUE((v->attrs & RAY_ATTR_HAS_NULLS) != 0); TEST_ASSERT_TRUE(ray_vec_is_null(v, 2)); - /* Slice [1..4): {2s, null, 4s}. Slice itself does not carry - * HAS_NULLS; only the parent does. */ + /* Slice [1..4): {2s, null, 4s}. Since #495 the slice header carries + * the parent's HAS_NULLS hint too, so the bit-only gates see it; the + * slice-aware detection below is still what reads the cell. */ ray_t* s = ray_vec_slice(v, 1, 3); TEST_ASSERT_NOT_NULL(s); TEST_ASSERT_FALSE(RAY_IS_ERR(s)); TEST_ASSERT_TRUE((s->attrs & RAY_ATTR_SLICE) != 0); - TEST_ASSERT_FALSE((s->attrs & RAY_ATTR_HAS_NULLS) != 0); + TEST_ASSERT_TRUE((s->attrs & RAY_ATTR_HAS_NULLS) != 0); TEST_ASSERT_TRUE(ray_vec_is_null(s, 1)); /* Extract seconds. Without slice-aware null detection this path diff --git a/test/test_mcast.c b/test/test_mcast.c index 0827b7b3b..d2108a6ed 100644 --- a/test/test_mcast.c +++ b/test/test_mcast.c @@ -520,6 +520,38 @@ static test_result_t test_mcast_no_subscribers_and_api_errors(void) { PASS(); } +static test_result_t test_mcast_bare_subscribe_shorthand(void) { + ray_poll_t* poll; + ray_vm_t* vm; + uint16_t port; + ray_thread_t tid; + test_result_t sr = start_server(&poll, &port, &vm, &tid); + if (sr.status != TEST_PASS) return sr; + + int64_t h = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + TEST_ASSERT((h) >= (0), "client connected"); + + ray_t* msg = ray_str("(.mc.sub \"bare\")", strlen("(.mc.sub \"bare\")")); + ray_t* sub = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); + TEST_ASSERT_EQ_I(sub->i64, 1); + ray_release(sub); + + msg = ray_str("(.mc.sub)", strlen("(.mc.sub)")); + ray_t* err = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(err); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); + TEST_ASSERT_STR_EQ(ray_err_code(err), "domain"); + ray_error_free(err); + + ray_ipc_close(h); + stop_server(poll, port, vm, tid); + PASS(); +} + static test_result_t test_mcast_restricted_sub_but_not_pub(void) { ray_poll_t* poll; ray_vm_t* vm; @@ -654,6 +686,246 @@ static test_result_t test_mcast_large_payload_queues_until_writable(void) { PASS(); } +/* One publication, N subscribers: the wire bytes are built once and shared + * (#487). A 4 KiB SO_SNDBUF on every server-side subscriber socket forces + * the large frame to queue on all of them; the stats `framed` counter must + * read 1 for the publication, every subscriber must still receive the whole + * payload, and a subscriber that closes while its copy is only partly + * written must not disturb the others or leak the shared bytes (ASan + * would report a leak or a use-after-free at teardown). */ +static test_result_t test_mcast_shared_frame_across_subscribers(void) { + ray_t* r = ray_eval_str( + "(set _mc_count 0)" + "(set _mc_len_sum 0)" + "(set _mc_handles [])" + "(set upd (fn [topic seq payload] " + " (do " + " (set _mc_count (+ _mc_count 1))" + " (set _mc_len_sum (+ _mc_len_sum (count payload))))))" + "(set .ipc.on.open (fn [h] (set _mc_handles (concat _mc_handles h))))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + if (r != RAY_NULL_OBJ) ray_release(r); + + ray_poll_t* poll; + ray_vm_t* vm; + uint16_t port; + ray_thread_t tid; + test_result_t sr = start_server(&poll, &port, &vm, &tid); + if (sr.status != TEST_PASS) return sr; + + int64_t hs[3]; + for (int i = 0; i < 3; i++) { + hs[i] = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + TEST_ASSERT((hs[i]) >= (0), "subscriber connected"); + ray_t* msg = ray_str("(.mc.sub \"big\" null)", strlen("(.mc.sub \"big\" null)")); + ray_t* sub = ray_ipc_send(hs[i], msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); + ray_release(sub); + } + int64_t hp = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + TEST_ASSERT((hp) >= (0), "publisher connected"); + +#ifndef RAY_OS_WINDOWS + ray_t* server_hs = ray_env_get(ray_sym_intern("_mc_handles", 11)); + TEST_ASSERT_NOT_NULL(server_hs); + TEST_ASSERT((ray_len(server_hs)) >= (3), "three server-side subscriber handles"); + for (int i = 0; i < 3; i++) { + int64_t sh = ((int64_t*)ray_data(server_hs))[i]; + ray_selector_t* ssel = ray_poll_get(poll, sh); + TEST_ASSERT_NOT_NULL(ssel); + int sndbuf = 4096; + setsockopt((ray_sock_t)ssel->fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)); + } +#endif + + const char* pub_src = "(.mc.pub \"big\" (+ (* (til 100000) 1103515245) 12345))"; + ray_t* msg = ray_str(pub_src, strlen(pub_src)); + ray_t* pub = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(pub); + TEST_ASSERT_FALSE(RAY_IS_ERR(pub)); + TEST_ASSERT_EQ_I(pub->i64, 1); + ray_release(pub); + + /* One subscriber goes away while its copy is at best partly written. */ + ray_ipc_close(hs[2]); + + TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_mc_count", 9, 2, 2000)); + ray_t* c = ray_env_get(ray_sym_intern("_mc_count", 9)); + ray_t* lsum = ray_env_get(ray_sym_intern("_mc_len_sum", 11)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_NOT_NULL(lsum); + TEST_ASSERT_EQ_I(c->i64, 2); + TEST_ASSERT_EQ_I(lsum->i64, 200000); + + msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + ray_t* st = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "published"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "delivered"), 3); + TEST_ASSERT_EQ_I(dict_i64(st, "framed"), 1); /* built once, not per subscriber */ + ray_release(st); + + /* A second publication to the two survivors: still one frame each time. */ + msg = ray_str("(.mc.pub \"big\" (til 50000))", strlen("(.mc.pub \"big\" (til 50000))")); + pub = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(pub); + TEST_ASSERT_FALSE(RAY_IS_ERR(pub)); + ray_release(pub); + TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_mc_count", 9, 4, 2000)); + + msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + st = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "framed"), 2); + TEST_ASSERT_EQ_I(dict_i64(st, "delivered"), 5); + ray_release(st); + + ray_ipc_close(hs[0]); + ray_ipc_close(hs[1]); + ray_ipc_close(hp); + stop_server(poll, port, vm, tid); + PASS(); +} + +/* Configurable transmit backlog (#486): a subscriber whose queue would + * exceed the process default is dropped and closed at admission, while a + * subscriber with a per-connection override large enough to hold the + * frame keeps receiving. The active limits and the high-water mark are + * readable from .mc.stats and per handle from (.ipc.handle h). */ +static test_result_t test_mcast_txlimit_overflow_disconnects(void) { + ray_t* r = ray_eval_str( + "(set _mc_count 0)" + "(set _mc_close_count 0)" + "(set _mc_handles [])" + "(set upd (fn [topic seq payload] (set _mc_count (+ _mc_count 1))))" + "(set .ipc.on.open (fn [h] (set _mc_handles (concat _mc_handles h))))" + "(set .ipc.on.close (fn [h] (set _mc_close_count (+ _mc_close_count 1))))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + if (r != RAY_NULL_OBJ) ray_release(r); + + ray_poll_t* poll; + ray_vm_t* vm; + uint16_t port; + ray_thread_t tid; + test_result_t sr = start_server(&poll, &port, &vm, &tid); + if (sr.status != TEST_PASS) return sr; + + int64_t h1 = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + int64_t h2 = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + int64_t hp = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + TEST_ASSERT((h1) >= (0), "h1 connected"); + TEST_ASSERT((h2) >= (0), "h2 connected"); + TEST_ASSERT((hp) >= (0), "publisher connected"); + for (int i = 0; i < 2; i++) { + ray_t* msg = ray_str("(.mc.sub \"cap\" null)", strlen("(.mc.sub \"cap\" null)")); + ray_t* sub = ray_ipc_send(i == 0 ? h1 : h2, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); + ray_release(sub); + } + + ray_t* server_hs = ray_env_get(ray_sym_intern("_mc_handles", 11)); + TEST_ASSERT_NOT_NULL(server_hs); + TEST_ASSERT((ray_len(server_hs)) >= (2), "two server-side subscriber handles"); + int64_t s1 = ((int64_t*)ray_data(server_hs))[0]; + int64_t s2 = ((int64_t*)ray_data(server_hs))[1]; +#ifndef RAY_OS_WINDOWS + for (int i = 0; i < 2; i++) { + ray_selector_t* ssel = ray_poll_get(poll, i == 0 ? s1 : s2); + TEST_ASSERT_NOT_NULL(ssel); + int sndbuf = 4096; + setsockopt((ray_sock_t)ssel->fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)); + } +#endif + + /* Process default: 64 KiB. h2 alone may hold 4 MiB. */ + ray_t* msg = ray_str("(.ipc.txlimit 65536 0)", strlen("(.ipc.txlimit 65536 0)")); + ray_t* lim = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(lim); + TEST_ASSERT_FALSE(RAY_IS_ERR(lim)); + TEST_ASSERT_EQ_I(dict_i64(lim, "bytes"), 65536); + TEST_ASSERT_EQ_I(dict_i64(lim, "frames"), 0); + ray_release(lim); + char src[96]; + int n = snprintf(src, sizeof(src), "(.ipc.txlimit %lld 4194304 0)", (long long)s2); + TEST_ASSERT((n) > (0) && (size_t)n < sizeof(src), "format override"); + msg = ray_str(src, (size_t)n); + lim = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(lim); + TEST_ASSERT_FALSE(RAY_IS_ERR(lim)); + TEST_ASSERT_EQ_I(dict_i64(lim, "bytes"), 4194304); + ray_release(lim); + + /* ~800 KiB on the wire: over h1's 64 KiB, under h2's 4 MiB. */ + const char* pub_src = "(.mc.pub \"cap\" (+ (* (til 100000) 1103515245) 12345))"; + msg = ray_str(pub_src, strlen(pub_src)); + ray_t* pub = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(pub); + TEST_ASSERT_FALSE(RAY_IS_ERR(pub)); + ray_release(pub); + + TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_mc_count", 9, 1, 2000)); + TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_mc_close_count", 15, 1, 2000)); + ray_t* c = ray_env_get(ray_sym_intern("_mc_count", 9)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_EQ_I(c->i64, 1); /* only h2 received it */ + + msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + ray_t* st = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "subscriptions"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "delivered"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "dropped"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "tx_limit_bytes"), 65536); + TEST_ASSERT_EQ_I(dict_i64(st, "tx_limit_frames"), 0); + TEST_ASSERT((dict_i64(st, "tx_hwm_bytes")) > (65536), "the override let a larger backlog form"); + TEST_ASSERT((dict_i64(st, "tx_hwm_bytes")) <= (4194304), "never past the override"); + ray_release(st); + + n = snprintf(src, sizeof(src), "(.ipc.handle %lld)", (long long)s2); + msg = ray_str(src, (size_t)n); + ray_t* info = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(info); + TEST_ASSERT_FALSE(RAY_IS_ERR(info)); + TEST_ASSERT_EQ_I(dict_i64(info, "handle"), s2); + TEST_ASSERT_EQ_I(dict_i64(info, "limit_bytes"), 4194304); + TEST_ASSERT_EQ_I(dict_i64(info, "limit_frames"), 0); + TEST_ASSERT((dict_i64(info, "hwm_bytes")) > (65536), "per-handle high-water mark"); + TEST_ASSERT((dict_i64(info, "queued_bytes")) >= (0), "queue drained or draining"); + ray_release(info); + + /* Restore the process default so later tests see the built-in limit. */ + msg = ray_str("(.ipc.txlimit 268435456 0)", strlen("(.ipc.txlimit 268435456 0)")); + lim = ray_ipc_send(hp, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(lim); + TEST_ASSERT_FALSE(RAY_IS_ERR(lim)); + ray_release(lim); + + ray_ipc_close(h1); + ray_ipc_close(h2); + ray_ipc_close(hp); + stop_server(poll, port, vm, tid); + PASS(); +} + static test_result_t test_mcast_failed_send_defers_close(void) { ray_t* r = ray_eval_str( "(set _mc_count 0)" @@ -859,10 +1131,13 @@ const test_entry_t mcast_entries[] = { { "mcast/duplicate_sub_idempotent", test_mcast_duplicate_sub_is_idempotent, mcast_setup, mcast_teardown }, { "mcast/multi_topic_routing", test_mcast_multi_topic_routing, mcast_setup, mcast_teardown }, { "mcast/no_subscribers_api_errors", test_mcast_no_subscribers_and_api_errors, mcast_setup, mcast_teardown }, + { "mcast/bare_sub_shorthand", test_mcast_bare_subscribe_shorthand, mcast_setup, mcast_teardown }, { "mcast/restricted_sub_not_pub", test_mcast_restricted_sub_but_not_pub, mcast_setup, mcast_teardown }, { "mcast/sub_requires_ipc_context", test_mcast_requires_ipc_context_for_sub, mcast_setup, mcast_teardown }, { "mcast/large_payload_queues", test_mcast_large_payload_queues_until_writable, mcast_setup, mcast_teardown }, { "mcast/sync_reply_after_queued", test_mcast_sync_reply_after_queued_frame, mcast_setup, mcast_teardown }, { "mcast/failed_send_defers_close", test_mcast_failed_send_defers_close, mcast_setup, mcast_teardown }, + { "mcast/shared_frame_across_subs", test_mcast_shared_frame_across_subscribers, mcast_setup, mcast_teardown }, + { "mcast/txlimit_overflow_disconnects", test_mcast_txlimit_overflow_disconnects, mcast_setup, mcast_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_repl.c b/test/test_repl.c index e2c4a4cb1..9866d73c2 100644 --- a/test/test_repl.c +++ b/test/test_repl.c @@ -659,6 +659,36 @@ static test_result_t test_repl_pty_ctrl_d(void) { PASS(); } +/* Timers keep firing while the interactive prompt is idle (#493). The + * interactive REPL registers stdin as a poll selector and sits in + * ray_poll_run, whose wait is bounded by the next timer deadline, so a + * callback must run without any further input. The poll has to be the + * runtime's published poll (run_pty_listen_with_poll), which is where + * .time.timer.set looks — as main.c does. The callback itself + * ends the session with a distinctive exit code: a clean exit with that + * code proves it ran while the prompt was idle, and the helper's 5 s + * timeout (-2) is what a starved timer would produce. Nothing after + * the timer line is ever written to the pty. */ +static int run_pty_listen_with_poll(const char* input); +static test_result_t test_repl_pty_timer_fires_while_idle(void) { +#ifndef RAY_OS_WINDOWS + int rc = run_pty_listen_with_poll("(.time.timer.set 150 1 (fn [t] (exit 7)))\n"); + TEST_ASSERT_FMT(rc == 7, "one-shot timer did not fire at an idle prompt: child rc %d", rc); +#endif + PASS(); +} + +/* Same for a periodic timer: three fires, none prompted by input. */ +static test_result_t test_repl_pty_periodic_timer_while_idle(void) { +#ifndef RAY_OS_WINDOWS + int rc = run_pty_listen_with_poll( + "(set _n 0)\n" + "(.time.timer.set 100 0 (fn [t] (do (set _n (+ _n 1)) (if (>= _n 3) (exit 3) 0))))\n"); + TEST_ASSERT_FMT(rc == 3, "periodic timer did not keep firing at an idle prompt: child rc %d", rc); +#endif + PASS(); +} + /* No-poll fallback: ray_repl_create(NULL) keeps repl->poll == NULL so * run_interactive uses the blocking-read fallback loop (lines ~940-998 * in repl.c). :q breaks out via the inline command dispatch in that @@ -3077,6 +3107,8 @@ const test_entry_t repl_entries[] = { { "repl/pty/backslash_exit", test_repl_pty_backslash_exit, repl_setup, repl_teardown }, { "repl/pty/eval_then_quit", test_repl_pty_eval_then_quit, repl_setup, repl_teardown }, { "repl/pty/ctrl_d", test_repl_pty_ctrl_d, repl_setup, repl_teardown }, + { "repl/pty/timer_fires_while_idle", test_repl_pty_timer_fires_while_idle, repl_setup, repl_teardown }, + { "repl/pty/periodic_timer_while_idle", test_repl_pty_periodic_timer_while_idle, repl_setup, repl_teardown }, { "repl/pty/no_poll_quit", test_repl_pty_no_poll_quit, repl_setup, repl_teardown }, { "repl/pty/no_poll_eval", test_repl_pty_no_poll_eval, repl_setup, repl_teardown }, { "repl/pty/no_poll_ctrl_d", test_repl_pty_no_poll_ctrl_d, repl_setup, repl_teardown }, diff --git a/test/test_runtime.c b/test/test_runtime.c index 684a3fc07..1a4049b4d 100644 --- a/test/test_runtime.c +++ b/test/test_runtime.c @@ -744,6 +744,51 @@ static test_result_t test_poll_run_for_fires_timer(void) { PASS(); } +/* An unbounded ray_poll_run with nothing registered and nothing scheduled + * returns instead of blocking forever, and one that has only a pending + * timer returns once the timer has fired (#493: a script or a piped + * session stays for its timers, then ends). ray_poll_drain_timers is the + * bounded form used by main.c and the piped REPL. */ +static test_result_t test_poll_run_returns_when_idle(void) { + ray_poll_t* poll = (ray_poll_t*)ray_runtime_get_poll(); + TEST_ASSERT_NOT_NULL(poll); + TEST_ASSERT_EQ_U(poll->n_live, 0u); + TEST_ASSERT_TRUE(ray_poll_idle(poll)); + + int64_t t0 = ray_time_now_ms(); + TEST_ASSERT_EQ_I(ray_poll_run(poll), 0); /* nothing to wait for */ + TEST_ASSERT_TRUE(ray_time_now_ms() - t0 < 500); + + ray_t* r = ray_eval_str("(set idle_timer_fired 0)" + "(.time.timer.set 20 1 (fn [t] (set idle_timer_fired 1)))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + TEST_ASSERT_FALSE(ray_poll_idle(poll)); + + t0 = ray_time_now_ms(); + TEST_ASSERT_EQ_I(ray_poll_run(poll), 0); /* fires, then idle */ + TEST_ASSERT_TRUE(ray_time_now_ms() - t0 < 2000); + ray_t* f = ray_eval_str("idle_timer_fired"); + TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I(f->i64, 1); + ray_release(f); + TEST_ASSERT_TRUE(ray_poll_idle(poll)); + + r = ray_eval_str("(set idle_timer_fired 0)" + "(.time.timer.set 20 1 (fn [t] (set idle_timer_fired 2)))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + ray_poll_drain_timers(poll); + f = ray_eval_str("idle_timer_fired"); + TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I(f->i64, 2); + ray_release(f); + TEST_ASSERT_TRUE(ray_poll_idle(poll)); + PASS(); +} + /* ─── timer.c deep coverage (heap helpers + edge paths) ─────── * * The static heap helpers (heap_less, heap_swap, heap_up sift body, @@ -1202,6 +1247,7 @@ const test_entry_t runtime_entries[] = { { "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/poll_run_returns_when_idle", test_poll_run_returns_when_idle, 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 }, diff --git a/test/test_store.c b/test/test_store.c index bc4e99c6f..e42a7c547 100644 --- a/test/test_store.c +++ b/test/test_store.c @@ -73,6 +73,48 @@ static void store_teardown(void) { ray_heap_destroy(); } +/* ---- test_col_save_derives_has_nulls ----------------------------------- */ + +/* The on-disk HAS_NULLS bit is load-bearing and nothing rescans on load, + * so the save path derives it from the payload (#495): a column whose + * producer left the bit clear while writing a sentinel is persisted with + * the bit set, on both the read and the mmap loader. */ +static test_result_t test_col_save_derives_has_nulls(void) { + int64_t raw[] = {1, NULL_I64, 3}; + ray_t* vec = ray_vec_from_raw(RAY_I64, raw, 3); + TEST_ASSERT_NOT_NULL(vec); + TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); + vec->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; /* the forgetful producer */ + + TEST_ASSERT_EQ_I(ray_col_save(vec, TMP_COL_PATH), RAY_OK); + + ray_t* loaded = ray_col_load(TMP_COL_PATH); + TEST_ASSERT_NOT_NULL(loaded); + TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); + TEST_ASSERT_TRUE((loaded->attrs & RAY_ATTR_HAS_NULLS) != 0); + TEST_ASSERT_TRUE(ray_vec_is_null(loaded, 1)); + ray_release(loaded); + + ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + TEST_ASSERT_NOT_NULL(mapped); + TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); + TEST_ASSERT_TRUE((mapped->attrs & RAY_ATTR_HAS_NULLS) != 0); + TEST_ASSERT_TRUE(ray_vec_is_null(mapped, 1)); + ray_release(mapped); + + /* A null-free column stays null-free: the scan only ever sets. */ + int64_t clean[] = {1, 2, 3}; + ray_t* cvec = ray_vec_from_raw(RAY_I64, clean, 3); + TEST_ASSERT_EQ_I(ray_col_save(cvec, TMP_COL_PATH), RAY_OK); + ray_t* cl = ray_col_load(TMP_COL_PATH); + TEST_ASSERT_NOT_NULL(cl); + TEST_ASSERT_TRUE((cl->attrs & RAY_ATTR_HAS_NULLS) == 0); + ray_release(cl); + ray_release(cvec); + ray_release(vec); + PASS(); +} + /* ---- test_col_mmap_i64 ------------------------------------------------- */ static test_result_t test_col_mmap_i64(void) { @@ -5479,6 +5521,7 @@ static test_result_t test_col_save_nyi_type(void) { const test_entry_t store_entries[] = { { "store/col_mmap_i64", test_col_mmap_i64, store_setup, store_teardown }, + { "store/col_save_derives_has_nulls", test_col_save_derives_has_nulls, store_setup, store_teardown }, { "store/col_mmap_f64", test_col_mmap_f64, store_setup, store_teardown }, { "store/col_mmap_f32", test_col_mmap_f32, store_setup, store_teardown }, { "store/col_mmap_cow", test_col_mmap_cow, store_setup, store_teardown }, diff --git a/test/test_types.c b/test/test_types.c index 75a171406..3a17d5d8c 100644 --- a/test/test_types.c +++ b/test/test_types.c @@ -67,6 +67,16 @@ static test_result_t test_elem_size_macro(void) { TEST_ASSERT_EQ_U(ray_elem_size(RAY_BOOL), 1); TEST_ASSERT_EQ_U(ray_elem_size(RAY_GUID), 16); + /* Negative (atom) type tags must index the zero-filled upper half of the + * 256-entry table, not read out of bounds: ray_type_sizes[(int8_t)-1] is + * an OOB read (UBSan `index -1 out of bounds`). Atoms carry no element + * size in this table, so the well-defined answer is 0. -RAY_BOOL == -1 is + * the tag that hit this via ray_sym_elem_size in the query path. */ + TEST_ASSERT_EQ_U(ray_elem_size((int8_t)-RAY_BOOL), 0); + TEST_ASSERT_EQ_U(ray_elem_size((int8_t)-RAY_I64), 0); + TEST_ASSERT_EQ_U(ray_elem_size((int8_t)-RAY_SYM), 0); + TEST_ASSERT_EQ_U(ray_elem_size((int8_t)-1), 0); + PASS(); }