diff --git a/Makefile b/Makefile index 3faeba387..aa6b666e9 100644 --- a/Makefile +++ b/Makefile @@ -215,6 +215,8 @@ dist: release # caps it; children inherit the env. Override for a fuller parallel stress, # e.g. `make test TEST_CORES=0` (serial) or `make test TEST_CORES=8`. TEST_CORES ?= 2 +TEST_FILTER ?= +TEST_ARGS = $(if $(TEST_FILTER),-f $(TEST_FILTER),) # Tests. Depends on $(TARGET) because test/rfl/system/ipc_diff.rfl # spawns ./$(TARGET) as an IPC server via .sys.exec — both binaries @@ -224,7 +226,7 @@ test: LDFLAGS = $(DEBUG_LDFLAGS) test: $(LIB_OBJ) $(MAIN_OBJ) $(TEST_OBJ) $(CC) $(CFLAGS) -o $(TARGET) $(LIB_OBJ) $(MAIN_OBJ) $(LIBS) $(LDFLAGS) $(CC) $(CFLAGS) -o $(TARGET).test $(LIB_OBJ) $(TEST_OBJ) $(LIBS) $(LDFLAGS) -Itest - RAYFORCE_CORES=$(TEST_CORES) ./$(TARGET).test + RAYFORCE_CORES=$(TEST_CORES) ./$(TARGET).test $(TEST_ARGS) # ─── ThreadSanitizer ──────────────────────────────────────────────── # Data-race detection for the lock-free pool/heap paths, which the diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index ef0d1aafb..9ed26fca3 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -299,6 +299,10 @@ A non-empty functional insert returns a new logical table view; the quoted-symbo `upsert` is not supported on parted tables. Materialize a flat table or use an application-level update strategy when key-based replacement is required. +`upsert` into a named flat table (`(upsert 'book 'px row)`) writes matched rows in place and appends new keys, so its cost is proportional to the payload rather than to the rows already present. A multi-row payload (a table, or a list of column vectors) is applied in one pass; a key repeated inside the payload resolves to its last row. A single-row `upsert` locates its row through a `.idx.hash` index on the key column when one is attached and fresh, and by one scan of the key column otherwise. A payload with a mistyped value is rejected before anything is written. + +`update` with `where:` into a named flat table writes the matched rows in place: the predicate is resolved through a fresh `.idx.hash` index on the column when it is a plain equality (`(== sym 'AAPL)`), elementwise update expressions (arithmetic, comparisons, and other atomic builtins over columns and literals) are evaluated over the matched rows only, and the results are scattered into the live columns. Any other expression, such as one with an aggregate, an order-dependent function like `deltas`, or a free variable, is evaluated over the whole table as before, so both spellings of `from:` agree. A mistyped or wrong-length value is rejected before anything is written. + ## Joins Rayforce supports equi-joins, outer joins, anti-joins, and time-series-aware joins. diff --git a/docs/docs/namespaces/time.md b/docs/docs/namespaces/time.md index 821860f87..07671eb8f 100644 --- a/docs/docs/namespaces/time.md +++ b/docs/docs/namespaces/time.md @@ -44,7 +44,9 @@ Errors: - `type` — non-`i64` `ms` / `num`, or `fn` not a lambda. - `oom` — heap allocation failed. -The callback's return value is released and discarded — timers are side-effecting procedures. If the callback raises an error, the error is printed to `stderr` (prefixed `timer :`) and the timer continues as if the call had succeeded; one fire is still counted toward `num`. +The callback's return value is released and discarded — timers are side-effecting procedures. If the callback raises an error, the error is printed to `stderr` as `timer : error: : ` (the same line the REPL would print) and the timer continues as if the call had succeeded; one fire is still counted toward `num`. + +A callback that overruns its period does not replay the fires it missed. After each fire the timer re-arms at its next scheduled deadline, or one period from now if that deadline has already passed, so a periodic timer fires at most once per `ms` and the poll loop gets back to serving I/O between fires. ```lisp ;; Print "tick" every second, three times diff --git a/docs/multicast-implementation-plan.md b/docs/multicast-implementation-plan.md new file mode 100644 index 000000000..ba41513f7 --- /dev/null +++ b/docs/multicast-implementation-plan.md @@ -0,0 +1,354 @@ +# Rayforce Multicast Implementation Plan + +## Goal + +Add a first-class multicast/pub-sub subsystem to Rayforce as a core engine module, exposed to Rayfall through a `.mc.*` namespace and delivered over the existing IPC wire. + +The target model is close to traditional ticker-plant style pub/sub, but adapted to Rayforce's current architecture: + +- IPC handles are poll selector ids. +- Server-side code can push to connected clients through the same handle namespace. +- `.ipc.post` already provides async frames, but currently writes directly to the socket. +- The poll loop is single-threaded for IPC dispatch. +- Durable replay already exists through the journal layer. + +The implementation should avoid UDP multicast initially. Rayforce needs typed payloads, authentication/restricted-mode behavior, replay, and per-client filtering; those fit application-level multicast over IPC much better than network-level multicast. + +## Proposed User API + +Expose multicast under reserved namespace `.mc.*`. + +```lisp +(.mc.sub topic filter) +(.mc.unsub topic) +(.mc.pub topic payload) +(.mc.stats) +``` + +Initial semantics: + +- `topic`: symbol or string, internally canonicalized to a symbol id or stable string key. +- `filter`: null, symbol vector/list, dict, or lambda. MVP should support only null and simple dict filters; lambdas can be a later phase. +- `payload`: any serializable Rayforce value, normally a table, vector, dict, or list. +- `.mc.pub` returns the assigned sequence number. +- `.mc.pub` returns `0` and does not create a topic when there are no active subscribers. +- `.mc.sub` uses `(.ipc.handle)` when called during inbound IPC evaluation. Optionally support explicit handle form later. +- pushed client message is an async IPC frame containing: + +```lisp +(upd topic seq payload) +``` + +This mirrors the common pub/sub convention where downstream clients implement `upd`. In +Rayforce the delivered `topic` should be a string, not a bare symbol, because +unquoted symbol atoms in expression position are name references in Rayfall. +The payload argument must be wrapped as data on the wire, for example with +`(quote payload)`, so list payloads are not evaluated on the subscriber. + +## Module Boundary + +Add a static core module, not a dynamic plugin ABI. + +Files: + +- `src/core/mcast.h` +- `src/core/mcast.c` +- `src/ops/mcast.c` for Rayfall builtin wrappers, or place the wrappers beside the existing IPC builtins in `src/ops/system.c` if that is still the local convention. +- `test/test_mcast.c` +- `docs/docs/namespaces/mc.md` +- update `docs/docs/namespaces/index.md` + +Suggested C API: + +```c +typedef struct ray_mcast ray_mcast_t; + +ray_mcast_t* ray_mcast_create(void); +void ray_mcast_destroy(ray_mcast_t* mc); + +ray_t* ray_mcast_sub(ray_poll_t* poll, int64_t handle, + ray_t* topic, ray_t* filter); +ray_t* ray_mcast_unsub(ray_poll_t* poll, int64_t handle, + ray_t* topic); +ray_t* ray_mcast_pub(ray_poll_t* poll, ray_t* topic, ray_t* payload); +ray_t* ray_mcast_replay(ray_poll_t* poll, ray_t* topic, + int64_t from_seq); +ray_t* ray_mcast_stats(ray_poll_t* poll); +void ray_mcast_on_close(ray_poll_t* poll, int64_t handle); +``` + +Store the module instance on `ray_poll_t` as an opaque pointer: + +```c +void* mcast; +``` + +Reason: Rayforce IPC handles are poll-local selector ids, so multicast subscriptions and outbound queues naturally belong to the poll that owns the connections. + +## Internal Data Model + +Core structures: + +```c +typedef struct ray_mcast_sub { + int64_t handle; + ray_t* filter; + int64_t last_sent_seq; + int64_t dropped; +} ray_mcast_sub_t; + +typedef struct ray_mcast_topic { + int64_t topic_sym; + int64_t next_seq; + ray_mcast_sub_t* subs; + int32_t n_subs; + int32_t cap_subs; +} ray_mcast_topic_t; + +typedef struct ray_mcast { + ray_mcast_topic_t* topics; + int32_t n_topics; + int32_t cap_topics; + int64_t published; + int64_t delivered; + int64_t dropped; +} ray_mcast_t; +``` + +MVP can use linear arrays, matching the current small fixed/simple style in the runtime. Replace with hash tables only when subscriber/topic counts make it necessary. + +Memory ownership: + +- retain `filter` on subscribe; +- release `filter` on unsubscribe/close/destroy; +- publish payload should be retained only while building queued outbound frames; +- avoid storing published payloads in memory unless replay cache is explicitly implemented. + +## Delivery Path + +Phase 1 can call the existing async IPC send path, but the production design should introduce queued transmit. + +Current issue: + +- `ray_ipc_send_async` resolves a handle and immediately calls the socket write path. +- That can block the publish path on slow subscribers or large payloads. + +Required engine improvement: + +1. Split IPC frame creation from socket writing. +2. Add per-selector TX queue. +3. Teach poll backends to watch socket writability when TX queue is non-empty. +4. Let multicast enqueue frames to each subscriber and return quickly. +5. Apply per-connection queue limits. + +Suggested helper boundary: + +```c +ray_err_t ray_ipc_enqueue_async(ray_poll_t* poll, int64_t handle, ray_t* msg); +ray_err_t ray_ipc_enqueue_frame(ray_poll_t* poll, int64_t handle, + uint8_t msgtype, ray_t* msg, + uint8_t extra_flags); +``` + +`ray_ipc_send_async` can then become a wrapper over enqueue for poll-owned connections. + +## Backpressure Policy + +Make slow-client behavior explicit per topic or process. + +Policies: + +- `disconnect`: default for event streams where loss is unacceptable. +- `drop-oldest`: useful for telemetry and snapshot-like topics. +- `drop-latest`: useful when preserving queued order matters more than newest value. +- `coalesce`: later optimization for keyed state topics, e.g. latest quote per sym. + +MVP default: + +- bounded queue per connection; +- if full, disconnect subscriber and increment dropped/slow counters. + +This is stricter than silently dropping, and easier to reason about for market/event data. + +## Filtering + +Start narrow. + +Phase 1 filters: + +- null filter: receive every message for the topic; +- dict filter for common table payload columns, e.g. `{sym: [AAPL MSFT]}`; +- symbol/list filter shorthand can map to `{sym: ...}` only if we explicitly document that convention. + +Avoid lambda filters in the first implementation. Calling Rayfall lambdas per subscriber inside publish adds eval reentrancy, no-closure edge cases, unpredictable latency, and error semantics that are not needed for the first useful version. + +For table payloads, filtering should create a selected table per subscriber only if needed. If multiple subscribers have the same filter, later optimization can cache the filtered payload for that publish call. + +## Durability And Replay + +There are two useful stream classes: + +- state streams: quotes, metrics, book snapshots; loss can be repaired by a fresh snapshot; +- event streams: trades, orders, audit; loss requires replay or disconnect. + +MVP: + +- assign sequence numbers per topic; +- `.mc.pub` writes a journal expression before fanout if multicast journaling is enabled; +- `.mc.replay` can initially return an explicit `nyi` until journal indexing is designed. + +Durable phase: + +- journal each publish as `(list '.mc.apply topic seq payload)`; +- on recovery, rebuild topic sequence counters and optional retained state; +- add a compact side index by topic/seq if replay from large logs matters. + +Do not rely on the generic journal alone for efficient replay. It can reconstruct state, but topic-range replay needs indexing or a retained log table. + +## Restricted Mode And Security + +Recommended builtin flags: + +- `.mc.sub`: allowed in restricted IPC mode. +- `.mc.unsub`: allowed in restricted IPC mode. +- `.mc.stats`: allowed, unless it leaks sensitive details. +- `.mc.pub`: restricted by default. +- `.mc.replay`: allowed only if it returns data the caller is already authorized to receive. + +Auth should remain at IPC handshake level. Fine-grained authorization can be added through `.ipc.on.auth` or a future `.mc.auth` policy hook, but do not add that in MVP. + +## Lifecycle Integration + +1. Initialize `poll->mcast` lazily on first `.mc.*` call. +2. Destroy it in `ray_poll_destroy`. +3. Call `ray_mcast_on_close(poll, sel->id)` from IPC close handling before `.ipc.on.close` runs. +4. Ensure selector id reuse cannot leak subscriptions: close cleanup must run before the selector slot can be reused. +5. If listener teardown destroys all selectors, multicast cleanup should release every retained filter and queued message. + +## Implementation Phases + +### Phase 0: Design Lock + +- Add this plan to the repo. +- Decide exact names: `.mc.*` vs `.ipc.pubsub.*`. +- Decide whether topics are symbols only or symbol/string. +- Decide whether `.mc.sub` takes explicit handle in addition to current IPC handle. + +Recommended decisions: + +- use `.mc.*`; +- accept symbol or string but canonicalize internally; +- MVP uses current IPC handle only; add explicit admin forms later. + +### Phase 1: Minimal Core Multicast + +- Add `src/core/mcast.h`. +- Add `src/core/mcast.c`. +- Add `void* mcast` to `ray_poll_t`. +- Add create/destroy/lazy-get helpers. +- Implement topic lookup, subscribe, unsubscribe, close cleanup, stats. +- Implement publish using a bounded nonblocking send path or a small internal enqueue placeholder if TX queue work is started immediately. +- Register `.mc.sub`, `.mc.unsub`, `.mc.pub`, `.mc.stats`. +- Add docs page with MVP semantics and limitations. + +Tests: + +- subscribe from an IPC client; +- publish delivers `(upd topic seq payload)` to that client; +- two clients receive the same message; +- unsubscribe stops delivery; +- close removes subscriptions; +- `.mc.stats` reports topic/subscriber counts. + +### Phase 2: TX Queue And Nonblocking Fanout + +- Refactor IPC frame serialization into reusable frame builder. +- Add TX queue to `ray_selector`. +- Add poll backend write readiness support for Linux epoll and macOS kqueue. +- Change `.ipc.post` to enqueue instead of direct socket write where possible. +- Add queue byte/message limits. +- Add disconnect-on-overflow policy. + +Tests: + +- large payload fanout to multiple subscribers does not block publish on the first slow reader; +- queue overflow disconnects or drops according to configured policy; +- queued frames preserve order on a single connection; +- sync `.ipc.send` still pumps inbound pushed async frames correctly. + +### Phase 3: Filters + +- Implement null filter. +- Implement dict equality/inclusion filter for table payloads. +- Implement topic-level filter validation at subscribe time. +- Return clear `type`/`domain` errors for unsupported filters. + +Tests: + +- `{sym: [AAPL MSFT]}` receives matching rows only; +- non-table payload with table-column filter errors or is skipped according to documented policy; +- multiple subscribers with different filters get different payloads. + +### Phase 4: Durability And Replay + +- Add `.mc.config` or process-level config for durable topics. +- Journal publish records before fanout. +- Implement replay API from retained in-memory log or journal side index. +- Add startup recovery behavior for sequence counters. + +Tests: + +- after replay/restart, next sequence continues after last published seq; +- replay from seq returns expected messages; +- corrupted tail follows existing journal validation behavior. + +### Phase 5: Operations Surface + +- Add `.mc.topics`. +- Add `.mc.subs topic`. +- Add `.mc.config` for queue limits and policy. +- Add querylog/profile integration if needed. +- Add documentation examples for ticker-plant style market data. + +## Test Strategy + +Add `test/test_mcast.c` using the existing IPC test style: + +- create runtime and poll; +- start poll server thread; +- connect clients with `ray_ipc_connect`; +- install client-side `.ipc.on.async` or use pushed eval side effects as current tests do; +- publish from server-side eval or direct C API; +- use sync round-trip as an ordering barrier. + +Also add Rayfall integration tests under `test/rfl/system/` once the `.mc.*` namespace exists. + +Regression areas: + +- selector id reuse after close; +- restricted mode access; +- non-serializable payloads; +- publish from inside `.ipc.on.sync`; +- publish while a client is already in sync wait; +- large compressed payloads; +- cleanup on poll destroy. + +## Open Questions + +- Should `.mc.pub` be allowed locally only, or also from authenticated unrestricted IPC clients? +- Should sequence numbers be global or per topic? Recommendation: per topic. +- Should the pushed function name be fixed as `upd`, or configurable per subscription? Recommendation: fixed first. +- Should filters be applied before journaling or after? Recommendation: journal original payload, filter only for delivery. +- Should replay use existing `.log` files or a dedicated multicast log table? Recommendation: use existing journal for recovery, add a topic/seq index for replay. + +## Initial Acceptance Criteria + +The first merge is useful if it satisfies: + +- a Rayforce process can accept two IPC clients; +- both clients can call `.mc.sub`; +- server can call `.mc.pub`; +- both clients receive async `(upd topic seq payload)` messages in order; +- closing one client removes only that client's subscriptions; +- restricted clients can subscribe but cannot publish; +- tests cover lifecycle, fanout, and close cleanup. diff --git a/docs/multicast-usage.md b/docs/multicast-usage.md new file mode 100644 index 000000000..78947b0d0 --- /dev/null +++ b/docs/multicast-usage.md @@ -0,0 +1,249 @@ +# Rayforce Multicast Usage Guide + +This document describes how to use the current Rayforce multicast module and how to migrate existing IPC fan-out or legacy topic pub/sub code to it. + +## Status + +The current implementation is a live IPC multicast module exposed through `.mc.*`. + +It supports: + +- topic subscription over existing Rayforce IPC connections +- server-side fan-out with async `upd` delivery +- unsubscribe and automatic cleanup on IPC close +- string and symbol topic inputs +- serializable Rayforce payloads +- aggregate runtime statistics +- restricted-mode guard: restricted clients can subscribe but cannot publish + +It does not yet provide durable replay, topic filters, wildcard topics, ACLs, per-topic stats, per-client lag, or queued backpressure. + +## API + +```clj +(.mc.sub topic null) ;; subscribe the current IPC handle to topic +(.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 +``` + +`topic` can be a string or a symbol: + +```clj +(.mc.sub "ticks" null) +(.mc.sub 'ticks null) + +(.mc.pub "ticks" 42) +(.mc.pub 'ticks (dict ['sym 'price] (list 'AAPL 185.5))) +``` + +Filters are reserved for later work. For now, pass `null`: + +```clj +(.mc.sub "ticks" null) ;; ok +(.mc.sub "ticks" 1) ;; nyi +``` + +## Delivery Model + +Subscribers receive async IPC messages that evaluate this expression in the client process: + +```clj +(upd topic seq payload) +``` + +The client must define `upd` before subscribing: + +```clj +(set upd (fn [topic seq payload] + (do + (println "topic=% seq=% payload=%" topic seq payload) + null))) +``` + +The delivered `topic` is a string even if the publisher used a symbol. This avoids Rayfall symbol name-resolution surprises in pushed expression-list messages. + +The delivered `payload` is wrapped with `quote` on the wire, so lists, dicts, symbols, and other serializable values arrive as data rather than being evaluated as code by the subscriber. + +`seq` is a per-topic publish sequence number. It is currently useful for logging and gap detection, but there is no replay API yet. + +## Running A Server + +Start a Rayforce IPC server: + +```sh +./rayforce -p 5000 +``` + +For server-only mode: + +```sh +./rayforce -p 5000 rayforce.log 2>&1 & +``` + +Optionally load init code first: + +```sh +./rayforce -p 5000 init.rfl +``` + +## Minimal Subscriber + +```clj +(set count 0) + +(set upd (fn [topic seq payload] + (do + (set count (+ count 1)) + (println "recv topic=% seq=% payload=% count=%" topic seq payload count) + null))) + +(set h (.ipc.open "127.0.0.1:5000" 2000)) +(.ipc.send h "(.mc.sub \"ticks\" null)") +``` + +## Minimal Publisher + +```clj +(set h (.ipc.open "127.0.0.1:5000" 2000)) + +(.ipc.send h "(.mc.pub \"ticks\" 123)") +(.ipc.send h "(.mc.pub \"ticks\" (dict ['sym 'price] (list 'AAPL 185.5)))") +``` + +## Stats + +Use `.mc.stats` from any IPC client: + +```clj +(.ipc.send h "(.mc.stats)") +``` + +Example result: + +```clj +{topics:1 subscriptions:1 published:2 delivered:2 dropped:0} +``` + +Fields: + +- `topics`: number of topic records with active subscriptions +- `subscriptions`: number of active topic subscriptions +- `published`: number of publish calls accepted by the module +- `delivered`: number of async messages successfully queued/sent to subscribers +- `dropped`: number of failed subscriber deliveries that caused subscriber removal + +Stats are process-lifetime aggregate state. If several tests or clients reuse one server process, stats include earlier activity. + +## Migrating Existing IPC Fan-Out + +If existing code manually tracks handles and sends to each client: + +```clj +;; old shape +(map (fn [h] (.ipc.post h msg)) clients) +``` + +migrate it as follows. + +First, define `upd` in each client: + +```clj +(set upd (fn [topic seq payload] + (handle-event topic seq payload))) +``` + +Then subscribe each client to the topics it needs: + +```clj +(.ipc.send h "(.mc.sub \"ticks\" null)") +(.ipc.send h "(.mc.sub \"orders\" null)") +``` + +Finally, replace producer-side handle fan-out with one publish call: + +```clj +(.mc.pub "ticks" payload) +``` + +If the producer itself is remote, publish through IPC: + +```clj +(.ipc.send h "(.mc.pub \"ticks\" payload_expr)") +``` + +## Migrating From Legacy Topic Pub/Sub + +The shape is intentionally close to traditional ticker-plant style systems: + +```text +sub(topic) -> (.mc.sub "topic" null) +unsub(topic) -> (.mc.unsub "topic") +pub(topic, data) -> (.mc.pub "topic" data) +upd(topic, data) -> upd(topic, seq, payload) +``` + +Main differences: + +- Rayforce `upd` receives three arguments: `topic`, `seq`, and `payload`. +- `topic` is delivered as a string. +- `seq` is assigned by the server per topic. +- filters and replay are not implemented yet. + +## Recommended Payload Shape + +Prefer self-describing dict payloads for application events: + +```clj +(dict ['sym 'ts 'price 'size] + (list 'AAPL 2026.09.03D10:00:00.000000000 185.5 100)) +``` + +For topic dispatch, keep `upd` small and delegate to topic-specific handlers: + +```clj +(set onTick (fn [x] ...)) +(set onOrder (fn [x] ...)) + +(set upd (fn [topic seq payload] + (if (== topic "ticks") + (onTick payload) + (if (== topic "orders") + (onOrder payload) + null)))) +``` + +## Operational Notes + +- `.mc.sub` must run in an inbound IPC evaluation context because it uses the current IPC handle. +- Local `.mc.sub` outside IPC returns `domain`. +- `.mc.pub` returns the assigned sequence number. +- `.mc.pub` returns `0` when there is no active subscriber for the topic; it does not create an orphan topic. +- Duplicate subscription of the same handle to the same topic is idempotent. +- Async delivery is non-blocking. If the socket cannot accept the whole frame immediately, the remaining bytes are queued on that IPC handle and flushed when it becomes writable. +- If async delivery fails or the per-connection TX backlog exceeds the IPC frame budget, that subscriber is removed, its IPC handle is closed, and `dropped` increments. +- Closing an IPC handle removes its subscriptions. +- Restricted IPC clients can subscribe but cannot publish. + +## Real Test Scenarios + +Manual end-to-end scenarios live under `test/scenarios/` and require a separately started IPC server. + +Example: + +```sh +./rayforce -p 5000 rayforce.log 2>&1 & +./rayforce test/scenarios/mcast_real_e2e.rfl -- --addr 127.0.0.1:5000 +``` + +Available scenarios: + +- `test/scenarios/mcast_real_e2e.rfl`: two clients, fan-out, unsubscribe, stats +- `test/scenarios/mcast_real_payloads.rfl`: i64, vector, symbol, and dict payloads +- `test/scenarios/mcast_real_negative.rfl`: publish without subscribers and negative API cases + +The regular C regression suite can be run with: + +```sh +make test TEST_FILTER=mcast +``` diff --git a/src/app/main.c b/src/app/main.c index 06155c9eb..652fd2dbf 100644 --- a/src/app/main.c +++ b/src/app/main.c @@ -265,11 +265,18 @@ int main(int argc, char** argv) { /* Start IPC server if port specified */ if (port > 0) { const char* bh = bind_host[0] ? bind_host : NULL; - if (poll && ray_ipc_listen_at(poll, bh, port) >= 0) + if (poll && ray_ipc_listen_at(poll, bh, port) >= 0) { fprintf(stderr, "listening on %s:%u\n", bh ? bh : "*", port); - else + } else { + /* The process was asked to serve. Carrying on would run the + * script and exit 0 (or sit on its timers) with no listener, + * and a supervisor would learn of it from the first client's + * ECONNREFUSED. Fail like every other server does. */ fprintf(stderr, "failed to listen on %s:%u: %s\n", bh ? bh : "*", port, strerror(errno)); + rc = 1; + goto done; + } } /* Load script if specified */ diff --git a/src/core/epoll.c b/src/core/epoll.c index 17fb05a32..88aab4bcd 100644 --- a/src/core/epoll.c +++ b/src/core/epoll.c @@ -24,6 +24,7 @@ #if defined(__linux__) #include "core/poll.h" +#include "core/mcast.h" #include "core/timer.h" #include "mem/sys.h" #include "mem/heap.h" /* idle decay: bound the wait, sweep after wakeup */ @@ -36,6 +37,22 @@ #define RAY_POLL_MAX_EVENTS 64 #define RAY_POLL_INITIAL_CAP 16 +static uint32_t epoll_selector_events(ray_selector_t* sel) +{ + uint32_t events = EPOLLIN | EPOLLRDHUP; + if (sel && sel->tx.buf) events |= EPOLLOUT; + return events; +} + +static void epoll_selector_mod(ray_poll_t* poll, ray_selector_t* sel) +{ + if (!poll || !sel) return; + struct epoll_event ev; + ev.events = epoll_selector_events(sel); + ev.data.u64 = (uint64_t)sel->id; + epoll_ctl((int)poll->fd, EPOLL_CTL_MOD, (int)sel->fd, &ev); +} + ray_poll_t* ray_poll_create(void) { int fd = epoll_create1(0); @@ -81,6 +98,10 @@ void ray_poll_destroy(ray_poll_t* poll) ray_timers_destroy((ray_timers_t*)poll->timers); poll->timers = NULL; } + if (poll->mcast) { + ray_mcast_destroy((ray_mcast_t*)poll->mcast); + poll->mcast = NULL; + } ray_sys_free(poll); } @@ -130,7 +151,7 @@ int64_t ray_poll_register(ray_poll_t* poll, ray_poll_reg_t* reg) /* Register with epoll */ struct epoll_event ev; - ev.events = EPOLLIN; + ev.events = epoll_selector_events(sel); ev.data.u64 = (uint64_t)id; if (epoll_ctl((int)poll->fd, EPOLL_CTL_ADD, (int)reg->fd, &ev) < 0) { @@ -143,6 +164,16 @@ int64_t ray_poll_register(ray_poll_t* poll, ray_poll_reg_t* reg) return id; } +void ray_poll_tx_request(ray_poll_t* poll, ray_selector_t* sel) +{ + epoll_selector_mod(poll, sel); +} + +void ray_poll_tx_cancel(ray_poll_t* poll, ray_selector_t* sel) +{ + epoll_selector_mod(poll, sel); +} + void ray_poll_deregister(ray_poll_t* poll, int64_t id) { if (!poll || id < 0 || (uint32_t)id >= poll->n_sels) return; @@ -275,6 +306,21 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) } } + if (events[i].events & EPOLLOUT) { + if (eid >= poll->n_sels || !poll->sels[eid]) goto next_event; + sel = poll->sels[eid]; + if (ray_poll_tx_flush(poll, sel) < 0) { + if (eid < poll->n_sels && poll->sels[eid]) { + sel = poll->sels[eid]; + if (sel->error_fn) + sel->error_fn(poll, sel); + else + ray_poll_deregister(poll, sel->id); + } + goto next_event; + } + } + /* Error / hangup — after data is drained */ if (events[i].events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) { /* Re-check: selector may have been freed by data_fn */ diff --git a/src/core/iocp.c b/src/core/iocp.c index 17b64ea54..636c3fed1 100644 --- a/src/core/iocp.c +++ b/src/core/iocp.c @@ -51,6 +51,16 @@ void ray_poll_deregister(ray_poll_t* poll, int64_t id) (void)poll; (void)id; } +void ray_poll_tx_request(ray_poll_t* poll, ray_selector_t* sel) +{ + (void)poll; (void)sel; +} + +void ray_poll_tx_cancel(ray_poll_t* poll, ray_selector_t* sel) +{ + (void)poll; (void)sel; +} + int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) { (void)poll; (void)timeout_ms; diff --git a/src/core/ipc.c b/src/core/ipc.c index dd8032aff..ac6e139c4 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -26,6 +26,7 @@ #endif #include "core/ipc.h" +#include "core/mcast.h" #include "mem/heap.h" #include "mem/sys.h" #include "ops/ops.h" @@ -166,6 +167,7 @@ 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) /* Constant-time comparison — prevents timing side-channel on password. */ static bool ct_eq(const void* a, const void* b, size_t len) { @@ -252,11 +254,15 @@ static void ipc_ctx_set(int64_t handle, ray_poll_t* poll) { __VM->ipc_poll = poll; } -static ray_poll_t* ipc_active_poll(void) { +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(); } +ray_poll_t* ray_ipc_context_poll(void) { + return ipc_ctx_poll(); +} + int64_t ray_ipc_current_handle(void) { return ipc_ctx_handle(); } @@ -350,6 +356,31 @@ static int hook_call_auth(ray_poll_t* poll, int64_t handle, return ok; } +/* A partially-sent multicast frame lives on sel->tx.buf until EPOLLOUT/ + * EVFILT_WRITE drains it. Any OTHER write to the same fd (a sync RESP, an + * async push) must not splice its bytes into the middle of that half-sent + * frame, or the peer parses the two framings into each other and the stream + * for that connection is corrupt. Flush the queued remainder first, blocking + * on write-readiness the way ray_sock_send already does, so the direct write + * that follows starts on a frame boundary. Fast-path returns 0 when nothing + * is queued (the common, non-subscriber case). Returns -1 on socket error. */ +static int conn_tx_drain_blocking(ray_poll_t* poll, ray_selector_t* sel) +{ + if (!sel || !sel->tx.buf) return 0; + while (sel->tx.buf) { + ray_poll_buf_t* buf = sel->tx.buf; + int64_t rem = buf->size - buf->offset; + if (rem > 0 && + ray_sock_send(sel->fd, buf->data + buf->offset, (size_t)rem) < 0) + return -1; + sel->tx.buf = buf->next; + buf->next = NULL; + ray_poll_buf_free(buf); + } + ray_poll_tx_cancel(poll, sel); + return 0; +} + static void send_response(ray_sock_t fd, ray_t* result) { int64_t ser_size = ray_serde_size(result); @@ -692,6 +723,22 @@ static int64_t ipc_recv_fn(int64_t fd, uint8_t* buf, int64_t len) { return ray_sock_recv((ray_sock_t)fd, buf, (size_t)len); } +static int64_t ipc_send_fn(int64_t fd, uint8_t* buf, int64_t len) +{ +#ifdef RAY_OS_WINDOWS + int n = send((ray_sock_t)fd, (const char*)buf, (int)len, 0); + if (n < 0) { + int e = WSAGetLastError(); + if (e == WSAEWOULDBLOCK) errno = EAGAIN; + else if (e == WSAEINTR) errno = EINTR; + } + return n; +#else + return send((ray_sock_t)fd, buf, (size_t)len, + MSG_NOSIGNAL | MSG_DONTWAIT); +#endif +} + /* ── Out-of-band cancel: client Ctrl-C → SIGURG → cancel the running query ── * The server evaluates single-threaded, so while a query runs it is NOT reading * the socket — an ordinary cancel message would sit unread until the query @@ -754,6 +801,7 @@ static ray_t* ipc_accept(ray_poll_t* poll, ray_selector_t* sel) reg.fd = (int64_t)new_fd; reg.type = RAY_SEL_SOCKET; reg.recv_fn = ipc_recv_fn; + reg.send_fn = ipc_send_fn; reg.read_fn = ipc_read_handshake; reg.close_fn = ipc_on_close; reg.data = cd; @@ -972,7 +1020,12 @@ static ray_t* ipc_read_payload(ray_poll_t* poll, ray_selector_t* sel) * selector before writing to its fd. */ if (hdr.msgtype == RAY_IPC_MSG_SYNC) { ray_selector_t* cur = ray_poll_get(poll, id); - if (cur && cur->data == (void*)cd) + /* Flush any multicast frame still queued to this fd before the RESP, + * so the reply lands on a frame boundary instead of splicing into a + * half-sent push. A drain error means the peer is gone — skip the + * write and let the poll/pump layer deregister it. */ + if (cur && cur->data == (void*)cd && + conn_tx_drain_blocking(poll, cur) == 0) send_response((ray_sock_t)cur->fd, result); } if (result != RAY_NULL_OBJ) ray_release(result); @@ -987,7 +1040,7 @@ static ray_t* ipc_read_payload(ray_poll_t* poll, ray_selector_t* sel) static void ipc_on_close(ray_poll_t* poll, ray_selector_t* sel) { - (void)poll; + ray_mcast_on_close(poll, sel ? sel->id : -1); /* Fire `.ipc.on.close` BEFORE tearing the per-conn state down so a * hook reading `.ipc.handle` still sees this connection's id, and * before the listener's own close path (which would otherwise also @@ -1436,7 +1489,8 @@ static int64_t recv_full(ray_sock_t fd, void* buf, size_t len) { size_t total = 0; while (total < len) { int64_t n = ray_sock_recv(fd, (uint8_t*)buf + total, len - total); - if (n <= 0) return -1; + if (n == 0) { errno = ECONNRESET; return -1; } /* peer closed: not a timeout */ + if (n < 0) return -1; total += (size_t)n; } return (int64_t)total; @@ -1448,7 +1502,7 @@ static int64_t recv_full(ray_sock_t fd, void* buf, size_t len) { * integer can never write to a non-IPC fd. */ static ray_selector_t* conn_resolve(ray_poll_t** poll_out, int64_t handle) { - ray_poll_t* poll = ipc_active_poll(); + ray_poll_t* poll = ray_ipc_active_poll(); if (!poll) return NULL; ray_selector_t* sel = ray_poll_get(poll, handle); if (!sel || sel->type != RAY_SEL_SOCKET || !sel->data) return NULL; @@ -1492,18 +1546,21 @@ static int conn_pump(ray_poll_t* poll, int64_t id) } } -/* Serialize + frame + write one message to a connection's fd. - * ray_sock_send loops on partial writes/EAGAIN internally, so this is - * safe on the nonblocking fds the poll owns. Returns 0 on success, - * -1 on serialization or socket failure. */ -static int64_t conn_write_msg(ray_sock_t fd, ray_t* msg, uint8_t msgtype, - uint8_t extra_flags) +static ray_poll_buf_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); - if (ser_size <= 0) return -1; + if (ser_size <= 0) { + if (err_out) *err_out = RAY_ERR_TYPE; + return NULL; + } uint8_t* payload = (uint8_t*)ray_sys_alloc((size_t)ser_size); - if (!payload) return -1; + if (!payload) { + if (err_out) *err_out = RAY_ERR_OOM; + return NULL; + } ray_ser_raw(payload, msg); uint8_t* send_buf = NULL; @@ -1544,15 +1601,68 @@ static int64_t conn_write_msg(ray_sock_t fd, ray_t* msg, uint8_t msgtype, .size = (int64_t)send_len, }; - int64_t rc = ray_sock_send(fd, &hdr, sizeof(hdr)); - if (rc < 0) { ray_sys_free(send_buf); if (payload) ray_sys_free(payload); return -1; } - rc = ray_sock_send(fd, send_buf, send_len); + size_t total = sizeof(hdr) + send_len; + if (total > (size_t)RAY_IPC_TX_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); + if (!frame) { + ray_sys_free(send_buf); + if (payload) ray_sys_free(payload); + if (err_out) *err_out = RAY_ERR_OOM; + return NULL; + } + memcpy(frame->data, &hdr, sizeof(hdr)); + memcpy(frame->data + sizeof(hdr), send_buf, send_len); ray_sys_free(send_buf); if (payload) ray_sys_free(payload); + return frame; +} + +/* Serialize + frame + write one message to a connection's fd. + * ray_sock_send loops on partial writes/EAGAIN internally, so this is + * safe on the nonblocking fds the poll owns. Writes directly and does NOT + * consult sel->tx.buf, so a caller whose fd may carry a queued multicast + * frame must conn_tx_drain_blocking() first (see sync_send / + * ray_ipc_send_async). Returns 0 on success, -1 on serialization or + * socket failure. */ +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); + if (!frame) return -1; + int64_t rc = ray_sock_send(fd, frame->data, (size_t)frame->size); + ray_poll_buf_free(frame); return rc < 0 ? -1 : 0; } +/* Classify a failed connect or handshake step by errno. The connect + * and the two-byte wire handshake share one budget: ray_sock_connect + * installs it as SO_RCVTIMEO / SO_SNDTIMEO once the connect completes, + * so a handshake that the peer never answers surfaces as EAGAIN / + * EWOULDBLOCK — a server that is alive and listening but inside a long + * evaluation. That must not read as "refused", which is what a dead + * port says, instantly. + * -5 no answer within the budget (ETIMEDOUT, EAGAIN, EWOULDBLOCK) + * -1 ECONNREFUSED + * -6 anything else; errno is left holding it for the caller's + * strerror. */ +static int64_t connect_fail_code(int err) { + if (err == ETIMEDOUT || err == EAGAIN) return -5; +#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN + if (err == EWOULDBLOCK) return -5; +#endif + if (err == ECONNREFUSED) return -1; + errno = err; + return -6; +} + int64_t ray_ipc_connect(const char* host, uint16_t port, const char* user, const char* password, int timeout_ms) @@ -1560,25 +1670,27 @@ int64_t ray_ipc_connect(const char* host, uint16_t port, /* The connection lives in the active poll's selector table — its * selector id IS the handle. No poll, no handle namespace: refuse * up front rather than hand out an integer nothing can resolve. */ - ray_poll_t* poll = ipc_active_poll(); + ray_poll_t* poll = ray_ipc_active_poll(); if (!poll) return -1; /* Default the connect/handshake budget to 5s when the caller gives * no explicit timeout, matching the long-standing handshake timeout. */ int connect_to = timeout_ms > 0 ? timeout_ms : 5000; ray_sock_t fd = ray_sock_connect(host, port, connect_to); - if (fd == RAY_INVALID_SOCK) return (errno == ETIMEDOUT) ? -5 : -1; + if (fd == RAY_INVALID_SOCK) return connect_fail_code(errno); uint8_t hs[2] = { RAY_SERDE_WIRE_VERSION, 0x00 }; if (ray_sock_send(fd, hs, 2) < 0) { + int e = errno; /* close() may clobber it */ ray_sock_close(fd); - return -1; + return connect_fail_code(e); } uint8_t resp[2]; if (recv_full(fd, resp, 2) < 0) { + int e = errno; ray_sock_close(fd); - return -1; + return connect_fail_code(e); } /* Refuse a peer that speaks a different wire version. This gives @@ -1651,6 +1763,7 @@ int64_t ray_ipc_connect(const char* host, uint16_t port, reg.fd = (int64_t)fd; reg.type = RAY_SEL_SOCKET; reg.recv_fn = ipc_recv_fn; + reg.send_fn = ipc_send_fn; reg.read_fn = ipc_read_header; reg.close_fn = ipc_on_close; reg.data = cd; @@ -1709,7 +1822,10 @@ static ray_t* sync_send(int64_t handle, ray_t* msg, uint8_t extra_flags) return ray_error("io", "nested sync send on busy handle"); } - if (conn_write_msg((ray_sock_t)sel->fd, msg, RAY_IPC_MSG_SYNC, + /* Drain any half-sent multicast frame queued to this fd before writing the + * sync request, so its bytes can't interleave into the pending frame. */ + if (conn_tx_drain_blocking(poll, sel) < 0 || + conn_write_msg((ray_sock_t)sel->fd, msg, RAY_IPC_MSG_SYNC, extra_flags) < 0) { if (owned) ray_release(msg); return ray_error("io", "ipc send failed"); @@ -1785,14 +1901,114 @@ ray_err_t ray_ipc_send_async(int64_t handle, ray_t* msg) } owned = true; } - ray_selector_t* sel = conn_resolve(NULL, handle); - ray_err_t rc = (!sel || conn_write_msg((ray_sock_t)sel->fd, msg, - RAY_IPC_MSG_ASYNC, 0) < 0) + ray_poll_t* poll; + ray_selector_t* sel = conn_resolve(&poll, handle); + ray_err_t rc = (!sel || conn_tx_drain_blocking(poll, sel) < 0 || + conn_write_msg((ray_sock_t)sel->fd, msg, + RAY_IPC_MSG_ASYNC, 0) < 0) ? RAY_ERR_IO : RAY_OK; if (owned) ray_release(msg); return rc; } +static int64_t conn_tx_pending(ray_selector_t* sel) +{ + int64_t pending = 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; + } + } + return pending; +} + +static int conn_tx_append(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; + + ray_poll_buf_t** tail = &sel->tx.buf; + while (*tail) tail = &(*tail)->next; + *tail = frame; + return 0; +} + +static int conn_try_send_frame(ray_selector_t* sel, ray_poll_buf_t* frame) +{ + while (frame->offset < frame->size) { + int64_t nw = sel->tx.send_fn( + sel->fd, + frame->data + frame->offset, + frame->size - frame->offset); + if (nw < 0) { + if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) return 1; + return -1; + } + if (nw == 0) return -1; + frame->offset += nw; + } + return 0; +} + +ray_err_t ray_ipc_try_send_async(int64_t handle, ray_t* msg) +{ + bool owned = false; + if (ray_is_lazy(msg)) { + ray_retain(msg); + msg = ray_lazy_materialize(msg); + if (RAY_IS_ERR(msg)) { + ray_err_t code = ray_err_from_obj(msg); + ray_error_free(msg); + return code; + } + owned = true; + } + + ray_poll_t* poll; + ray_selector_t* sel = conn_resolve(&poll, handle); + if (!sel) { + if (owned) ray_release(msg); + 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; + } + + int rc = 0; + if (sel->tx.buf) { + rc = 1; + } else { + rc = conn_try_send_frame(sel, frame); + } + + if (rc == 0) { + ray_poll_buf_free(frame); + } else if (rc > 0) { + if (conn_tx_append(sel, frame) < 0) { + ray_poll_buf_free(frame); + if (owned) ray_release(msg); + return RAY_ERR_IO; + } + ray_poll_tx_request(poll, sel); + } else { + ray_poll_buf_free(frame); + } + if (owned) ray_release(msg); + return rc >= 0 ? RAY_OK : RAY_ERR_IO; +} + /* 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 98bce8987..66f8f3c8c 100644 --- a/src/core/ipc.h +++ b/src/core/ipc.h @@ -72,6 +72,8 @@ size_t ray_ipc_decompress(const uint8_t* src, size_t clen, * class keeps the value scoped to the dispatch thread should that ever * change. */ int64_t ray_ipc_current_handle(void); +ray_poll_t* ray_ipc_active_poll(void); +ray_poll_t* ray_ipc_context_poll(void); /* ===== Poll-based IPC (new API) ===== */ @@ -127,6 +129,7 @@ int64_t ray_ipc_connect(const char* host, uint16_t port, void ray_ipc_close(int64_t handle); 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); /* Remote-REPL helper: send a SYNC message with RAY_IPC_FLAG_VERBOSE * set, returning a 2-element list [captured_str, result] where diff --git a/src/core/kqueue.c b/src/core/kqueue.c index b73d89bb1..3b05befa9 100644 --- a/src/core/kqueue.c +++ b/src/core/kqueue.c @@ -24,6 +24,7 @@ #if defined(__APPLE__) #include "core/poll.h" +#include "core/mcast.h" #include "core/timer.h" #include "mem/sys.h" #include "mem/heap.h" /* idle decay: bound the wait, sweep after wakeup */ @@ -36,6 +37,15 @@ #define RAY_POLL_MAX_EVENTS 64 #define RAY_POLL_INITIAL_CAP 16 +static void kqueue_set_write(ray_poll_t* poll, ray_selector_t* sel, int flags) +{ + if (!poll || !sel) return; + struct kevent kev; + EV_SET(&kev, (uintptr_t)sel->fd, EVFILT_WRITE, flags, 0, 0, + (void*)(uintptr_t)sel->id); + kevent((int)poll->fd, &kev, 1, NULL, 0, NULL); +} + ray_poll_t* ray_poll_create(void) { int fd = kqueue(); @@ -70,6 +80,8 @@ void ray_poll_destroy(ray_poll_t* poll) struct kevent kev; EV_SET(&kev, (uintptr_t)sel->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); kevent((int)poll->fd, &kev, 1, NULL, 0, NULL); + EV_SET(&kev, (uintptr_t)sel->fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); + kevent((int)poll->fd, &kev, 1, NULL, 0, NULL); if (sel->rx.buf) ray_poll_buf_free(sel->rx.buf); ray_poll_buf_free(sel->tx.buf); ray_sys_free(sel); @@ -82,9 +94,23 @@ void ray_poll_destroy(ray_poll_t* poll) ray_timers_destroy((ray_timers_t*)poll->timers); poll->timers = NULL; } + if (poll->mcast) { + ray_mcast_destroy((ray_mcast_t*)poll->mcast); + poll->mcast = NULL; + } ray_sys_free(poll); } +void ray_poll_tx_request(ray_poll_t* poll, ray_selector_t* sel) +{ + kqueue_set_write(poll, sel, EV_ADD | EV_ENABLE); +} + +void ray_poll_tx_cancel(ray_poll_t* poll, ray_selector_t* sel) +{ + kqueue_set_write(poll, sel, EV_DELETE); +} + int64_t ray_poll_register(ray_poll_t* poll, ray_poll_reg_t* reg) { if (!poll || !reg) return -1; @@ -153,6 +179,8 @@ void ray_poll_deregister(ray_poll_t* poll, int64_t id) struct kevent kev; EV_SET(&kev, (uintptr_t)sel->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); kevent((int)poll->fd, &kev, 1, NULL, 0, NULL); + EV_SET(&kev, (uintptr_t)sel->fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); + kevent((int)poll->fd, &kev, 1, NULL, 0, NULL); if (sel->close_fn) sel->close_fn(poll, sel); if (sel->rx.buf) ray_poll_buf_free(sel->rx.buf); @@ -277,6 +305,21 @@ int64_t ray_poll_run_for(ray_poll_t* poll, int timeout_ms) } } + if (events[i].filter == EVFILT_WRITE) { + if (eid >= poll->n_sels || !poll->sels[eid]) goto next_event; + sel = poll->sels[eid]; + if (ray_poll_tx_flush(poll, sel) < 0) { + if (eid < poll->n_sels && poll->sels[eid]) { + sel = poll->sels[eid]; + if (sel->error_fn) + sel->error_fn(poll, sel); + else + ray_poll_deregister(poll, sel->id); + } + goto next_event; + } + } + /* EOF / error — after data is drained */ if (events[i].flags & (EV_EOF | EV_ERROR)) { if (eid < poll->n_sels && poll->sels[eid]) { diff --git a/src/core/mcast.c b/src/core/mcast.c new file mode 100644 index 000000000..19ed1bd8c --- /dev/null +++ b/src/core/mcast.c @@ -0,0 +1,378 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + */ + +#include "core/mcast.h" +#include "core/ipc.h" +#include "lang/eval.h" +#include "mem/heap.h" +#include "mem/sys.h" +#include "table/sym.h" +#include + +typedef struct { + int64_t handle; + ray_t* filter; + int64_t last_sent_seq; + int64_t dropped; +} ray_mcast_sub_t; + +typedef struct { + int64_t topic_sym; + int64_t next_seq; + ray_mcast_sub_t* subs; + int32_t n_subs; + int32_t cap_subs; +} ray_mcast_topic_t; + +struct ray_mcast { + ray_mcast_topic_t* topics; + int32_t n_topics; + int32_t cap_topics; + int64_t published; + int64_t delivered; + int64_t dropped; +}; + +static int64_t topic_sym(ray_t* topic) { + if (!topic) return -1; + if (ray_is_atom(topic) && topic->type == -RAY_SYM) return topic->i64; + if (ray_is_atom(topic) && topic->type == -RAY_STR) + return ray_sym_intern(ray_str_ptr(topic), ray_str_len(topic)); + if (topic->type == RAY_STR && ray_len(topic) == 1) { + size_t len = 0; + const char* s = ray_str_vec_get(topic, 0, &len); + return s ? ray_sym_intern(s, len) : -1; + } + if (topic->type == RAY_SYM && ray_len(topic) == 1) { + ray_t* cell = ray_sym_vec_cell(topic, 0); + return cell ? ray_sym_intern(ray_str_ptr(cell), ray_str_len(cell)) : -1; + } + return -1; +} + +ray_mcast_t* ray_mcast_create(void) { + ray_mcast_t* mc = (ray_mcast_t*)ray_sys_alloc(sizeof(ray_mcast_t)); + if (!mc) return NULL; + memset(mc, 0, sizeof(*mc)); + return mc; +} + +void ray_mcast_destroy(ray_mcast_t* mc) { + if (!mc) return; + for (int32_t i = 0; i < mc->n_topics; i++) { + ray_mcast_topic_t* t = &mc->topics[i]; + for (int32_t j = 0; j < t->n_subs; j++) { + if (t->subs[j].filter && t->subs[j].filter != RAY_NULL_OBJ) + ray_release(t->subs[j].filter); + } + if (t->subs) ray_sys_free(t->subs); + } + if (mc->topics) ray_sys_free(mc->topics); + ray_sys_free(mc); +} + +static ray_mcast_t* poll_mcast(ray_poll_t* poll) { + if (!poll) return NULL; + if (!poll->mcast) + poll->mcast = ray_mcast_create(); + return (ray_mcast_t*)poll->mcast; +} + +static ray_mcast_topic_t* find_topic(ray_mcast_t* mc, int64_t sym) { + if (!mc) return NULL; + for (int32_t i = 0; i < mc->n_topics; i++) + if (mc->topics[i].topic_sym == sym) return &mc->topics[i]; + return NULL; +} + +static ray_mcast_topic_t* ensure_topic(ray_mcast_t* mc, int64_t sym) { + ray_mcast_topic_t* t = find_topic(mc, sym); + if (t) return t; + if (mc->n_topics >= mc->cap_topics) { + int32_t new_cap = mc->cap_topics ? mc->cap_topics * 2 : 8; + ray_mcast_topic_t* nt = (ray_mcast_topic_t*)ray_sys_alloc( + (size_t)new_cap * sizeof(ray_mcast_topic_t)); + if (!nt) return NULL; + if (mc->topics) + memcpy(nt, mc->topics, (size_t)mc->n_topics * sizeof(ray_mcast_topic_t)); + memset(nt + mc->n_topics, 0, + (size_t)(new_cap - mc->n_topics) * sizeof(ray_mcast_topic_t)); + ray_sys_free(mc->topics); + mc->topics = nt; + mc->cap_topics = new_cap; + } + t = &mc->topics[mc->n_topics++]; + memset(t, 0, sizeof(*t)); + t->topic_sym = sym; + t->next_seq = 1; + return t; +} + +static void remove_sub(ray_mcast_topic_t* t, int32_t idx) { + if (!t || idx < 0 || idx >= t->n_subs) return; + if (t->subs[idx].filter && t->subs[idx].filter != RAY_NULL_OBJ) + ray_release(t->subs[idx].filter); + if (idx + 1 < t->n_subs) + memmove(&t->subs[idx], &t->subs[idx + 1], + (size_t)(t->n_subs - idx - 1) * sizeof(ray_mcast_sub_t)); + t->n_subs--; +} + +static void remove_topic(ray_mcast_t* mc, int32_t idx) { + if (!mc || idx < 0 || idx >= mc->n_topics) return; + ray_mcast_topic_t* t = &mc->topics[idx]; + for (int32_t j = 0; j < t->n_subs; j++) { + if (t->subs[j].filter && t->subs[j].filter != RAY_NULL_OBJ) + ray_release(t->subs[j].filter); + } + if (t->subs) ray_sys_free(t->subs); + if (idx + 1 < mc->n_topics) + memmove(&mc->topics[idx], &mc->topics[idx + 1], + (size_t)(mc->n_topics - idx - 1) * sizeof(ray_mcast_topic_t)); + mc->n_topics--; +} + +static int32_t topic_index(ray_mcast_t* mc, int64_t sym) { + if (!mc) return -1; + for (int32_t i = 0; i < mc->n_topics; i++) + if (mc->topics[i].topic_sym == sym) return i; + return -1; +} + +static ray_t* make_quoted_payload(ray_t* payload) { + ray_t* q = ray_list_new(2); + if (!q || RAY_IS_ERR(q)) return q ? q : ray_error("oom", NULL); + ray_t* head = ray_sym(ray_sym_intern("quote", 5)); + if (!head || RAY_IS_ERR(head)) { + if (head && RAY_IS_ERR(head)) ray_error_free(head); + ray_release(q); + return ray_error("oom", NULL); + } + q = ray_list_append(q, head); + ray_release(head); + if (RAY_IS_ERR(q)) return q; + q = ray_list_append(q, payload); + return q; +} + +static ray_t* make_upd_msg(int64_t topic, int64_t seq, ray_t* payload) { + ray_t* msg = ray_list_new(4); + if (!msg || RAY_IS_ERR(msg)) return msg ? msg : ray_error("oom", NULL); + + ray_t* topic_name = ray_sym_str(topic); + if (!topic_name || RAY_IS_ERR(topic_name)) { + if (topic_name && RAY_IS_ERR(topic_name)) ray_error_free(topic_name); + ray_release(msg); + return ray_error("domain", ".mc.pub topic is not interned"); + } + + ray_t* head = ray_sym(ray_sym_intern("upd", 3)); + ray_t* top = ray_str(ray_str_ptr(topic_name), ray_str_len(topic_name)); + ray_t* s = ray_i64(seq); + ray_t* body = make_quoted_payload(payload); + if (!head || RAY_IS_ERR(head) || !top || RAY_IS_ERR(top) || !s || RAY_IS_ERR(s)) { + if (head && !RAY_IS_ERR(head)) ray_release(head); + if (top && !RAY_IS_ERR(top)) ray_release(top); + if (s && !RAY_IS_ERR(s)) ray_release(s); + if (body && !RAY_IS_ERR(body)) ray_release(body); + ray_release(msg); + return ray_error("oom", NULL); + } + if (!body || RAY_IS_ERR(body)) { + ray_release(head); + ray_release(top); + ray_release(s); + ray_release(msg); + return body ? body : ray_error("oom", NULL); + } + + msg = ray_list_append(msg, head); ray_release(head); + if (RAY_IS_ERR(msg)) { if (body != payload) ray_release(body); return msg; } + msg = ray_list_append(msg, top); ray_release(top); + if (RAY_IS_ERR(msg)) { if (body != payload) ray_release(body); return msg; } + msg = ray_list_append(msg, s); ray_release(s); + if (RAY_IS_ERR(msg)) { ray_release(body); return msg; } + msg = ray_list_append(msg, body); + ray_release(body); + return msg; +} + +ray_t* ray_mcast_sub(ray_poll_t* poll, int64_t handle, ray_t* topic, ray_t* filter) { + if (handle < 0) return ray_error("domain", ".mc.sub requires an active IPC connection"); + bool no_filter = (filter == RAY_NULL_OBJ) || + (filter && ray_is_atom(filter) && RAY_ATOM_IS_NULL(filter)); + if (!no_filter) + return ray_error("nyi", ".mc.sub filters are not implemented yet; pass null"); + filter = RAY_NULL_OBJ; + + int64_t sym = topic_sym(topic); + if (sym < 0) return ray_error("type", ".mc.sub topic must be a symbol or string"); + + ray_mcast_t* mc = poll_mcast(poll); + if (!mc) return ray_error("oom", NULL); + ray_mcast_topic_t* t = ensure_topic(mc, sym); + if (!t) return ray_error("oom", NULL); + + for (int32_t i = 0; i < t->n_subs; i++) { + if (t->subs[i].handle == handle) { + if (t->subs[i].filter && t->subs[i].filter != RAY_NULL_OBJ) + ray_release(t->subs[i].filter); + t->subs[i].filter = filter; + if (filter != RAY_NULL_OBJ) ray_retain(filter); + return ray_i64(t->next_seq); + } + } + + if (t->n_subs >= t->cap_subs) { + int32_t new_cap = t->cap_subs ? t->cap_subs * 2 : 8; + ray_mcast_sub_t* ns = (ray_mcast_sub_t*)ray_sys_alloc( + (size_t)new_cap * sizeof(ray_mcast_sub_t)); + if (!ns) return ray_error("oom", NULL); + if (t->subs) + memcpy(ns, t->subs, (size_t)t->n_subs * sizeof(ray_mcast_sub_t)); + memset(ns + t->n_subs, 0, + (size_t)(new_cap - t->n_subs) * sizeof(ray_mcast_sub_t)); + ray_sys_free(t->subs); + t->subs = ns; + t->cap_subs = new_cap; + } + + ray_mcast_sub_t* s = &t->subs[t->n_subs++]; + s->handle = handle; + s->filter = filter; + s->last_sent_seq = 0; + s->dropped = 0; + if (filter != RAY_NULL_OBJ) ray_retain(filter); + return ray_i64(t->next_seq); +} + +ray_t* ray_mcast_unsub(ray_poll_t* poll, int64_t handle, ray_t* topic) { + if (handle < 0) return ray_error("domain", ".mc.unsub requires an active IPC connection"); + int64_t sym = topic_sym(topic); + if (sym < 0) return ray_error("type", ".mc.unsub topic must be a symbol or string"); + ray_mcast_t* mc = (ray_mcast_t*)(poll ? poll->mcast : NULL); + int32_t ti = topic_index(mc, sym); + if (ti < 0) return RAY_NULL_OBJ; + ray_mcast_topic_t* t = &mc->topics[ti]; + for (int32_t i = 0; i < t->n_subs; i++) { + if (t->subs[i].handle == handle) { + remove_sub(t, i); + if (t->n_subs == 0) remove_topic(mc, ti); + break; + } + } + return RAY_NULL_OBJ; +} + +ray_t* ray_mcast_pub(ray_poll_t* poll, ray_t* topic, ray_t* payload) { + if (!poll) return ray_error("domain", ".mc.pub requires an active poll"); + int64_t sym = topic_sym(topic); + if (sym < 0) return ray_error("type", ".mc.pub topic must be a symbol or string"); + if (ray_serde_size(payload) <= 0) + return ray_error("type", ".mc.pub payload is not serializable"); + + ray_mcast_t* mc = (ray_mcast_t*)poll->mcast; + ray_mcast_topic_t* t = find_topic(mc, sym); + if (!t || t->n_subs == 0) return ray_i64(0); + + int64_t seq = t->next_seq; + ray_t* msg = make_upd_msg(sym, seq, payload); + if (!msg || RAY_IS_ERR(msg)) return msg ? msg : ray_error("oom", NULL); + + int32_t dead_cap = t->n_subs; + int32_t dead_n = 0; + int64_t* dead_handles = NULL; + if (dead_cap > 0) { + dead_handles = (int64_t*)ray_sys_alloc((size_t)dead_cap * sizeof(int64_t)); + if (!dead_handles) { + ray_release(msg); + return ray_error("oom", NULL); + } + } + + 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); + if (rc == RAY_OK) { + t->subs[i].last_sent_seq = seq; + mc->delivered++; + i++; + } else { + int64_t dead = t->subs[i].handle; + t->subs[i].dropped++; + mc->dropped++; + remove_sub(t, i); + dead_handles[dead_n++] = dead; + } + } + ray_release(msg); + if (t->n_subs == 0) { + int32_t ti = topic_index(mc, sym); + if (ti >= 0) remove_topic(mc, ti); + } + for (int32_t i = 0; i < dead_n; i++) + ray_ipc_close(dead_handles[i]); + if (dead_handles) ray_sys_free(dead_handles); + + return ray_i64(seq); +} + +ray_t* ray_mcast_stats(ray_poll_t* poll) { + ray_mcast_t* mc = (ray_mcast_t*)(poll ? poll->mcast : NULL); + int64_t topics = mc ? mc->n_topics : 0; + int64_t subs = 0; + if (mc) { + for (int32_t i = 0; i < mc->n_topics; i++) + subs += mc->topics[i].n_subs; + } + + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 5); + ray_t* vals = ray_list_new(5); + 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_t* v; + k = ray_sym_intern("topics", 6); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + v = ray_i64(topics); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + k = ray_sym_intern("subscriptions", 13); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + v = ray_i64(subs); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + k = ray_sym_intern("published", 9); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + v = ray_i64(mc ? mc->published : 0); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + k = ray_sym_intern("delivered", 9); keys = ray_vec_append(keys, &k); + if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } + v = ray_i64(mc ? mc->delivered : 0); vals = ray_list_append(vals, v); ray_release(v); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + k = ray_sym_intern("dropped", 7); keys = ray_vec_append(keys, &k); + 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; } + return ray_dict_new(keys, vals); +} + +void ray_mcast_on_close(ray_poll_t* poll, int64_t handle) { + ray_mcast_t* mc = (ray_mcast_t*)(poll ? poll->mcast : NULL); + if (!mc || handle < 0) return; + for (int32_t i = 0; i < mc->n_topics;) { + ray_mcast_topic_t* t = &mc->topics[i]; + for (int32_t j = 0; j < t->n_subs;) { + if (t->subs[j].handle == handle) remove_sub(t, j); + else j++; + } + if (t->n_subs == 0) remove_topic(mc, i); + else i++; + } +} diff --git a/src/core/mcast.h b/src/core/mcast.h new file mode 100644 index 000000000..1062196c4 --- /dev/null +++ b/src/core/mcast.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + */ + +#ifndef RAY_MCAST_H +#define RAY_MCAST_H + +#include +#include "core/poll.h" + +typedef struct ray_mcast ray_mcast_t; + +ray_mcast_t* ray_mcast_create(void); +void ray_mcast_destroy(ray_mcast_t* mc); + +ray_t* ray_mcast_sub(ray_poll_t* poll, int64_t handle, ray_t* topic, ray_t* filter); +ray_t* ray_mcast_unsub(ray_poll_t* poll, int64_t handle, ray_t* topic); +ray_t* ray_mcast_pub(ray_poll_t* poll, ray_t* topic, ray_t* payload); +ray_t* ray_mcast_stats(ray_poll_t* poll); +void ray_mcast_on_close(ray_poll_t* poll, int64_t handle); + +#endif /* RAY_MCAST_H */ diff --git a/src/core/poll.c b/src/core/poll.c index df7eddadf..74ff0d7e4 100644 --- a/src/core/poll.c +++ b/src/core/poll.c @@ -23,6 +23,7 @@ #include "core/poll.h" #include "mem/sys.h" +#include /* ===== Shared (platform-independent) poll helpers ===== */ @@ -77,3 +78,33 @@ void ray_poll_rx_request(ray_poll_t* poll, ray_selector_t* sel, int64_t size) } sel->rx.buf = ray_poll_buf_new(size); } + +int ray_poll_tx_flush(ray_poll_t* poll, ray_selector_t* sel) +{ + if (!poll || !sel || !sel->tx.send_fn) return -1; + + while (sel->tx.buf) { + ray_poll_buf_t* buf = sel->tx.buf; + while (buf->offset < buf->size) { + int64_t nw = sel->tx.send_fn( + sel->fd, + buf->data + buf->offset, + buf->size - buf->offset); + if (nw < 0) { + if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) + return 0; + return -1; + } + if (nw == 0) return -1; + buf->offset += nw; + } + + sel->tx.buf = buf->next; + buf->next = NULL; + ray_poll_buf_free(buf); + } + + ray_poll_tx_cancel(poll, sel); + return 1; +} diff --git a/src/core/poll.h b/src/core/poll.h index 543d90be5..6290d5c1f 100644 --- a/src/core/poll.h +++ b/src/core/poll.h @@ -98,6 +98,7 @@ struct ray_poll { 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 */ }; /* ===== API ===== */ @@ -116,5 +117,8 @@ 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); +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); #endif /* RAY_POLL_H */ diff --git a/src/core/sock.c b/src/core/sock.c index b462aa8ed..661d8ff27 100644 --- a/src/core/sock.c +++ b/src/core/sock.c @@ -173,8 +173,10 @@ ray_sock_t ray_sock_connect(const char* host, uint16_t port, int timeout_ms) char port_str[8]; snprintf(port_str, sizeof(port_str), "%u", (unsigned)port); - if (getaddrinfo(host, port_str, &hints, &res) != 0 || !res) + if (getaddrinfo(host, port_str, &hints, &res) != 0 || !res) { + errno = EHOSTUNREACH; /* not a refusal, and not a timeout */ return RAY_INVALID_SOCK; + } /* Try every resolved address in turn, not just the first. `localhost` * commonly resolves to BOTH ::1 (IPv6, often first) and 127.0.0.1; a diff --git a/src/core/timer.c b/src/core/timer.c index ad1112fa0..ae8c8bb40 100644 --- a/src/core/timer.c +++ b/src/core/timer.c @@ -29,6 +29,7 @@ #endif #include "core/timer.h" +#include "core/runtime.h" /* ray_error_msg */ #include "lang/internal.h" #include "mem/sys.h" #include @@ -191,30 +192,32 @@ uint32_t ray_timers_fire_expired(ray_timers_t* t) { ray_release(arg); if (result) { if (RAY_IS_ERR(result)) { - ray_t* msg = ray_fmt(result, 0); - if (msg && ray_str_ptr(msg)) { - fprintf(stderr, "timer %lld: %.*s\n", - (long long)timer->id, - (int)ray_str_len(msg), - ray_str_ptr(msg)); - } - if (msg) ray_release(msg); + /* An error formats as its code alone; the message lives + * in the runtime's last-error slot. Print both, as the + * REPL does, so a failing poll names its peer and cause. */ + char code[8] = {0}; + memcpy(code, result->sdata, result->slen < 7 ? result->slen : 7); + const char* detail = ray_error_msg(); + fprintf(stderr, "timer %lld: error: %s%s%s\n", + (long long)timer->id, code, + detail ? ": " : "", detail ? detail : ""); ray_error_free(result); } else { ray_release(result); } } - /* Re-schedule or free. */ - if (timer->num == 0) { - /* Forever: re-push. */ - timer->exp_ms += timer->tic_ms; - t->heap[t->n] = timer; - heap_up(t->heap, t->n); - t->n++; - } else if (timer->num > 1) { - timer->num--; + /* Re-schedule or free. Re-arm from the schedule, so the cadence + * stays exact while callbacks are cheap, but never into the past: + * a callback that overran its period would otherwise leave the + * timer T/tic deadlines behind, and this loop would fire it that + * many times back-to-back before the poll loop served any I/O. + * Missed intervals are skipped, not replayed. */ + if (timer->num == 0 || timer->num > 1) { + if (timer->num > 1) timer->num--; + now = ray_time_now_ms(); timer->exp_ms += timer->tic_ms; + if (timer->exp_ms <= now) timer->exp_ms = now + timer->tic_ms; t->heap[t->n] = timer; heap_up(t->heap, t->n); t->n++; diff --git a/src/io/csv.c b/src/io/csv.c index ebe7338f6..800f810c9 100644 --- a/src/io/csv.c +++ b/src/io/csv.c @@ -504,14 +504,15 @@ RAY_INLINE int32_t civil_to_days(int y, int m, int d) { return (int32_t)(era * 146097 + doe - 719468 - 10957); } -/* Strict YYYY-MM-DD: exactly 10 chars, '-' separators at offsets 4/7, and - * digits in every field. Mirrors detect_type() and csv_write_date() so that - * typed .csv.read [DATE] round-trips the writer's output while rejecting - * malformed separators or trailing garbage (e.g. "2024/01/02", "2024x01x02", - * "2024-01-02junk") as null instead of silently coercing them to a bogus - * date. fast_timestamp() reuses this on the leading date (passing len 10). */ +/* Strict date parser: exactly 10 chars, either YYYY-MM-DD (CSV writer output) + * or YYYY.MM.DD (Rayfall display form), with matching separators at offsets + * 4/7 and digits in every field. Reject malformed separators or trailing + * garbage (e.g. "2024/01/02", "2024x01x02", "2024-01-02junk") as null instead + * of silently coercing them to a bogus date. fast_timestamp() reuses this on + * the leading date (passing len 10). */ RAY_INLINE int32_t fast_date(const char* p, size_t len, bool* is_null) { - if (RAY_UNLIKELY(len != 10 || p[4] != '-' || p[7] != '-')) { *is_null = true; return 0; } + bool sep_ok = len == 10 && (p[4] == '-' || p[4] == '.') && p[7] == p[4]; + if (RAY_UNLIKELY(!sep_ok)) { *is_null = true; return 0; } if (RAY_UNLIKELY((unsigned)(p[0]-'0') > 9u || (unsigned)(p[1]-'0') > 9u || (unsigned)(p[2]-'0') > 9u || (unsigned)(p[3]-'0') > 9u || (unsigned)(p[5]-'0') > 9u || (unsigned)(p[6]-'0') > 9u || @@ -662,10 +663,21 @@ RAY_INLINE bool parse_tz_offset(const char* p, size_t len, int64_t* out_ns, size } RAY_INLINE int64_t fast_timestamp(const char* p, size_t len, bool* is_null) { - /* Require "YYYY-MM-DD" + 'T'|'t'|' ' separator + "HH:MM:SS" (>=19 chars), - * matching detect_type() and csv_write_timestamp(). A malformed date/time - * separator (e.g. "2024x01x02D01:02:03") is rejected as null. */ - if (RAY_UNLIKELY(len < 19 || (p[10] != 'T' && p[10] != 't' && p[10] != ' '))) { *is_null = true; return 0; } + /* Require a strict date + separator + "HH:MM:SS" (>=19 chars). Accept the + * CSV writer's ISO-ish separators ('T'|'t'|' ') and Rayfall display's + * dotted-date + 'D' form. Malformed date/time separators (e.g. + * "2024x01x02D01:02:03" or "2024-01-02D01:02:03") reject as null. + * + * Grammar note: 'T'|'t'|' ' are accepted after either date form, so a + * dotted date paired with one of them ("2024.01.02T01:02:03") also infers + * TIMESTAMP even though no writer emits that mixed shape; only 'D' is tied + * to the dotted date. This is deliberate leniency on input, not a form we + * produce. */ + if (RAY_UNLIKELY(len < 19)) { *is_null = true; return 0; } + bool rayfall_sep = (p[10] == 'D'); + bool dt_sep_ok = p[10] == 'T' || p[10] == 't' || p[10] == ' ' || + (rayfall_sep && p[4] == '.'); + if (RAY_UNLIKELY(!dt_sep_ok)) { *is_null = true; return 0; } *is_null = false; int32_t days = fast_date(p, 10, is_null); if (*is_null) return 0; diff --git a/src/lang/env.c b/src/lang/env.c index 53dce1f8a..2aeefd733 100644 --- a/src/lang/env.c +++ b/src/lang/env.c @@ -114,6 +114,20 @@ static struct { int32_t ray_env_scope_depth(void) { return __VM ? __VM->scope_depth : 0; } int32_t ray_env_global_count(void) { return g_env.count; } +/* Reverse-map a builtin function object to the symbol it is bound under in the + * global environment. Builtins inline only the first 13 bytes of their name + * (see fn_set_name / ray_fn_name), so serialization — which must round-trip the + * full name — cannot read it off the object. Every builtin, dotted reserved + * names included, is also bound flat in g_env (see reg_bind's ray_env_bind_flat + * call), so a pointer scan recovers the full name. Returns the sym_id, or -1 + * if `fn` is not a registered global builtin. */ +int64_t ray_env_builtin_sym(const ray_t* fn) { + if (!fn) return -1; + for (int32_t i = 0; i < g_env.count; i++) + if (g_env.vals[i] == fn) return g_env.keys[i]; + return -1; +} + /* Query scopes are synthetic and must not eclipse a caller's lexical * parameter/let binding. Other query frames are deliberately ignored so * an inner query can bind a same-named column over an outer query column. diff --git a/src/lang/env.h b/src/lang/env.h index 6af49f573..95ccad7d3 100644 --- a/src/lang/env.h +++ b/src/lang/env.h @@ -132,6 +132,12 @@ int32_t ray_env_list_user(int64_t* sym_ids, ray_t** vals, int32_t max_entries); * user). Useful for sizing buffers before ray_env_list. */ int32_t ray_env_global_count(void); +/* Reverse-map a builtin function object to the sym_id it is bound under in the + * global env, or -1 if it is not a registered global builtin. Serialization + * uses this to recover a builtin's full name, which the object only inlines to + * 13 bytes (ray_fn_name). */ +int64_t ray_env_builtin_sym(const ray_t* fn); + /* Local scope stack for lexical binding (let, do, lambda) */ ray_err_t ray_env_push_scope(void); ray_err_t ray_env_push_query_scope(void); diff --git a/src/lang/eval.c b/src/lang/eval.c index 29369e1cf..e99c299e9 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -3335,7 +3335,7 @@ static void ray_register_builtins(void) { register_unary("guid", RAY_FN_NONE, ray_guid_fn); /* In-place mutation */ - register_vary("alter", RAY_FN_SPECIAL_FORM, ray_alter_fn); + register_vary("alter", RAY_FN_SPECIAL_FORM | RAY_FN_RESTRICTED, ray_alter_fn); /* Pattern matching */ register_binary("like", RAY_FN_NONE, ray_like_fn); @@ -3401,6 +3401,13 @@ static void ray_register_builtins(void) { * Variadic for the `(.ipc.handle)` / `(.ipc.handle 0)` convention. */ register_vary( ".ipc.handle", RAY_FN_NONE, ray_ipc_handle_fn); + /* Multicast/pub-sub over IPC. Subscriptions are allowed under + * restricted IPC; publishing stays privileged. */ + register_vary( ".mc.sub", RAY_FN_NONE, ray_mc_sub_fn); + register_unary( ".mc.unsub", RAY_FN_NONE, ray_mc_unsub_fn); + register_binary(".mc.pub", RAY_FN_RESTRICTED, ray_mc_pub_fn); + register_vary( ".mc.stats", RAY_FN_NONE, ray_mc_stats_fn); + /* Remote-REPL session control under `.repl.*`. Once .repl.connect * succeeds, the local REPL line-loop reroutes each subsequent input * through ray_ipc_send_verbose() until .repl.disconnect. See @@ -3417,7 +3424,7 @@ static void ray_register_builtins(void) { * startup; these builtins expose the same machinery to Rayfall code * for manual control (open from a script, snapshot on demand, etc). */ register_vary(".log.open", RAY_FN_RESTRICTED, ray_log_open_fn); - register_unary(".log.write", RAY_FN_NONE, ray_log_write_fn); + register_unary(".log.write", RAY_FN_RESTRICTED, ray_log_write_fn); register_unary(".log.replay", RAY_FN_RESTRICTED, ray_log_replay_fn); register_unary(".log.validate",RAY_FN_NONE, ray_log_validate_fn); register_vary(".log.roll", RAY_FN_RESTRICTED, ray_log_roll_fn); @@ -3484,17 +3491,17 @@ static void ray_register_builtins(void) { register_vary("pull", RAY_FN_NONE, ray_pull_fn); /* Datalog */ - register_vary("rule", RAY_FN_SPECIAL_FORM, ray_rule_fn); + register_vary("rule", RAY_FN_SPECIAL_FORM | RAY_FN_RESTRICTED, ray_rule_fn); register_vary("query", RAY_FN_SPECIAL_FORM, ray_query_fn); /* Programmatic Datalog API */ register_vary("dl-program", RAY_FN_NONE, ray_dl_program_fn); - register_vary("dl-add-edb", RAY_FN_NONE, ray_dl_add_edb_fn); - register_unary("dl-stratify", RAY_FN_NONE, ray_dl_stratify_fn); - register_unary("dl-eval", RAY_FN_NONE, ray_dl_eval_fn); + register_vary("dl-add-edb", RAY_FN_RESTRICTED, ray_dl_add_edb_fn); + register_unary("dl-stratify", RAY_FN_RESTRICTED, ray_dl_stratify_fn); + register_unary("dl-eval", RAY_FN_RESTRICTED, ray_dl_eval_fn); register_binary("dl-query", RAY_FN_NONE, ray_dl_query_fn); register_binary("dl-provenance", RAY_FN_NONE, ray_dl_provenance_fn); - register_unary("dl-free", RAY_FN_NONE, ray_dl_free_fn); + register_unary("dl-free", RAY_FN_RESTRICTED, ray_dl_free_fn); /* Vector similarity / embeddings / HNSW */ register_binary("cos-dist", RAY_FN_NONE, ray_cos_dist_fn); @@ -3504,7 +3511,7 @@ static void ray_register_builtins(void) { register_vary ("knn", RAY_FN_NONE, ray_knn_fn); register_vary ("hnsw-build", RAY_FN_NONE, ray_hnsw_build_fn); register_vary ("ann", RAY_FN_NONE, ray_ann_fn); - register_unary ("hnsw-free", RAY_FN_NONE, ray_hnsw_free_fn); + register_unary ("hnsw-free", RAY_FN_RESTRICTED, ray_hnsw_free_fn); register_binary("hnsw-save", RAY_FN_RESTRICTED, ray_hnsw_save_fn); register_unary ("hnsw-load", RAY_FN_RESTRICTED, ray_hnsw_load_fn); register_unary ("hnsw-info", RAY_FN_NONE, ray_hnsw_info_fn); @@ -3536,7 +3543,7 @@ static void ray_register_builtins(void) { * Lifecycle handles auto-free on rc→0 (see RAY_ATTR_GRAPH branch in * src/mem/heap.c). */ register_vary (".graph.build", RAY_FN_NONE, ray_graph_build_fn); - register_unary(".graph.free", RAY_FN_NONE, ray_graph_free_fn); + register_unary(".graph.free", RAY_FN_RESTRICTED, ray_graph_free_fn); register_unary(".graph.info", RAY_FN_NONE, ray_graph_info_fn); register_vary (".graph.pagerank", RAY_FN_NONE, ray_graph_pagerank_fn); register_vary (".graph.connected", RAY_FN_NONE, ray_graph_connected_fn); diff --git a/src/lang/internal.h b/src/lang/internal.h index f5e19b6c2..e653f97d5 100644 --- a/src/lang/internal.h +++ b/src/lang/internal.h @@ -645,6 +645,10 @@ 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_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); +ray_t* ray_mc_stats_fn(ray_t** args, int64_t n); ray_t* ray_set_splayed_fn(ray_t** args, int64_t n); ray_t* ray_get_splayed_fn(ray_t** args, int64_t n); ray_t* ray_get_parted_fn(ray_t** args, int64_t n); diff --git a/src/ops/graph.c b/src/ops/graph.c index 63d29d056..b65536346 100644 --- a/src/ops/graph.c +++ b/src/ops/graph.c @@ -204,6 +204,18 @@ void ray_graph_free(ray_graph_t* g) { * Source ops * -------------------------------------------------------------------------- */ +/* A column of a parted table carries its type in a wrapper. Nothing that + * reads a node's out_type knows about wrappers — the promotion ladders match + * none of their cases and fall out the bottom as RAY_BOOL, and the SYM + * override in ray_if compares against a bare RAY_SYM — so the node reports + * the base type and the wrapper stays where it belongs, on the column. The + * executor decides how to read a parted column from the column itself, never + * from the node. */ +static int8_t scan_out_type(int8_t col_type) { + return RAY_IS_PARTED(col_type) ? (int8_t)RAY_PARTED_BASETYPE(col_type) + : col_type; +} + ray_op_t* ray_scan(ray_graph_t* g, const char* col_name) { ray_op_ext_t* ext = graph_alloc_ext_node(g); if (!ext) return NULL; @@ -219,7 +231,7 @@ ray_op_t* ray_scan(ray_graph_t* g, const char* col_name) { if (g->table) { ray_t* col = ray_table_get_col(g->table, sym_id); if (col) { - ext->base.out_type = col->type; + ext->base.out_type = scan_out_type(col->type); ext->base.est_rows = (uint32_t)col->len; } } @@ -1292,7 +1304,7 @@ ray_op_t* ray_scan_table(ray_graph_t* g, uint16_t table_id, const char* col_name if (tbl) { ray_t* col = ray_table_get_col(tbl, sym_id); if (col) { - ext->base.out_type = col->type; + ext->base.out_type = scan_out_type(col->type); ext->base.est_rows = (uint32_t)col->len; } } diff --git a/src/ops/group.c b/src/ops/group.c index a44816596..a16f63771 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -1554,7 +1554,6 @@ typedef struct { const int64_t* row_gid; int64_t n_rows; int64_t n_groups; - bool has_nulls; uint64_t p_mask; /* P - 1, P = number of partitions */ /* Pass 1 outputs / pass 2 inputs. Per-task counters: each worker * writes to its own slice of hist[task_id * P] / cursor[task_id * P] @@ -1577,41 +1576,10 @@ typedef struct { int64_t* odata; /* n_groups, atomic per-group distinct count */ } cdpg_ctx_t; -/* Type-correct null check for the column row r. Mirrors sentinel_is_null - * but specialised for cdpg's pre-resolved (base, in_type, esz) ctx so the - * hot loop avoids the ray_t pointer indirection. */ -static inline bool cdpg_is_null(const void* base, int64_t r, - int8_t in_type, uint8_t esz) { - switch (in_type) { - case RAY_F64: { double f = ((const double*)base)[r]; return f != f; } - case RAY_F32: { float f = ((const float*) base)[r]; return f != f; } - case RAY_I64: case RAY_TIMESTAMP: - return ((const int64_t*)base)[r] == NULL_I64; - case RAY_I32: case RAY_DATE: case RAY_TIME: - return ((const int32_t*)base)[r] == NULL_I32; - case RAY_I16: - return ((const int16_t*)base)[r] == NULL_I16; - case RAY_SYM: - if (esz == 1) return ((const uint8_t*)base)[r] == 0; - if (esz == 2) return ((const uint16_t*)base)[r] == 0; - if (esz == 4) return ((const uint32_t*)base)[r] == 0; - return ((const int64_t*)base)[r] == 0; - default: /* BOOL / U8 — non-nullable */ - return false; - } -} - /* Read column row r as int64. Width-typed fast path; F64 bitcasts. */ static inline int64_t cdpg_read(const void* base, int64_t r, int8_t in_type, uint8_t esz) { - if (in_type == RAY_F64) { - double fv = ((const double*)base)[r]; - if (fv != fv) fv = (double)NAN; - else fv = clear_neg_zero(fv); - int64_t v; - memcpy(&v, &fv, sizeof(int64_t)); - return v; - } + if (in_type == RAY_F64) return canon_f64_key(((const double*)base)[r]); switch (esz) { case 1: return (int64_t)((const uint8_t*)base)[r]; case 2: return (int64_t)((const int16_t*)base)[r]; @@ -1624,7 +1592,6 @@ static void cdpg_hist_fn(void* ctx_, uint32_t worker_id, int64_t start, int64_t end) { (void)worker_id; cdpg_ctx_t* x = (cdpg_ctx_t*)ctx_; - uint8_t esz = ray_sym_elem_size(x->in_type, x->in_attrs); uint64_t p_mask = x->p_mask; /* Per-task private hist slot — task_id is derived from `start` so * scat_fn computes the SAME task_id and reads cursor[task_id*P+p] @@ -1634,13 +1601,11 @@ static void cdpg_hist_fn(void* ctx_, uint32_t worker_id, for (int64_t r = start; r < end; r++) { int64_t gid = x->row_gid[r]; if (gid < 0 || gid >= x->n_groups) continue; - if (x->has_nulls && cdpg_is_null(x->base, r, x->in_type, esz)) continue; /* Partition by gid (not gid×val) so the dedup pass can write to * odata[gid] without atomics. */ uint64_t h = CDPG_PART_HASH(gid + 1); my_hist[h & p_mask]++; } - (void)esz; } static void cdpg_scat_fn(void* ctx_, uint32_t worker_id, @@ -1657,7 +1622,6 @@ static void cdpg_scat_fn(void* ctx_, uint32_t worker_id, for (int64_t r = start; r < end; r++) { int64_t gid = x->row_gid[r]; if (gid < 0 || gid >= x->n_groups) continue; - if (x->has_nulls && cdpg_is_null(x->base, r, x->in_type, esz)) continue; int64_t val = cdpg_read(x->base, r, x->in_type, esz); int64_t gid_p1 = gid + 1; uint64_t h = CDPG_PART_HASH(gid_p1); @@ -1751,7 +1715,6 @@ static ray_t* count_distinct_per_group_parallel( .row_gid = row_gid, .n_rows = n_rows, .n_groups = n_groups, - .has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0, .p_mask = p_mask, .odata = (int64_t*)ray_data(out), }; @@ -2004,7 +1967,6 @@ ray_t* ray_count_distinct_per_group(ray_t* src, const int64_t* row_gid, } void* base = ray_data(src); - bool has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0; /* Per-type read width — hoist the type dispatch out of the hot loop. * read_col_i64 was branching on `in_type` every iteration plus paying @@ -2036,20 +1998,19 @@ ray_t* ray_count_distinct_per_group(ray_t* src, const int64_t* row_gid, /* Specialised per-type loops. Each version reads the column with a * width-typed pointer dereference instead of dispatching through - * read_col_i64 every row. The has_nulls / no-nulls split keeps the - * fast path branch-free for the common no-null SYM/I64 columns. */ - if (!has_nulls) { + * read_col_i64 every row. They run whether or not the column has + * nulls: a null is one distinct value like any other, and every null + * reads back as a single key — the sentinels are ordinary nonzero + * integers, a SYM null is id 0, and canon_f64_key folds every NaN to + * one. The has-nulls fallback that used to sit here computed the same + * keys through a slower per-row dispatch. */ + { if (in_type == RAY_F64) { const double* d = (const double*)base; for (int64_t r = 0; r < n_rows; r++) { int64_t gid = row_gid[r]; if (gid < 0 || gid >= n_groups) continue; - double fv = d[r]; - if (fv != fv) fv = (double)NAN; - else fv = clear_neg_zero(fv); - int64_t v; - memcpy(&v, &fv, sizeof(int64_t)); - CD_INSERT(v); + CD_INSERT(canon_f64_key(d[r])); } } else if (esz == 8) { const int64_t* d = (const int64_t*)base; @@ -2080,29 +2041,6 @@ ray_t* ray_count_distinct_per_group(ray_t* src, const int64_t* row_gid, CD_INSERT((int64_t)d[r]); } } - } else { - /* Has-nulls fallback: keep the per-row null bitmap probe and - * the generic read_col_i64 dispatch. Adding eight specialised - * has-nulls loops costs more code than the small gain on - * already-rare null-bearing columns. */ - for (int64_t r = 0; r < n_rows; r++) { - int64_t gid = row_gid[r]; - if (gid < 0 || gid >= n_groups) continue; - if (cdpg_is_null(base, r, in_type, esz)) continue; - /* Use a different name from the macro's inner `val` so - * clang doesn't see an `int64_t val = (val);` self-init - * after macro expansion. */ - int64_t row_val; - if (in_type == RAY_F64) { - double fv = ((double*)base)[r]; - if (fv != fv) fv = (double)NAN; - else fv = clear_neg_zero(fv); - memcpy(&row_val, &fv, sizeof(int64_t)); - } else { - row_val = read_col_i64(base, r, in_type, src->attrs); - } - CD_INSERT(row_val); - } } #undef CD_INSERT @@ -4163,15 +4101,25 @@ static inline uint64_t hash_keys_inline(const int64_t* keys, const int8_t* key_t uint16_t n_keys, void* const* key_data, const ght_layout_t* ly, const void* const* key_pool) { + /* A null key is stored as a zeroed slot with its null-mask bit set, and + * every phase-1 builder hashes it as ray_hash_i64(0) REGARDLESS of the + * key's type. Consult the mask before reading the slot back by type: + * a zeroed inline-STR descriptor would otherwise hash as the empty + * string, and a zeroed wide (GUID) slot as source row 0 — neither is + * what the entry was created under, so after the first rehash the group + * would sit under a hash no probe computes and never be found again. */ if (ly->any_inline_str) { /* Inline-STR layout: key offsets are shifted by 16-byte descriptors, * so address every key via key_off[k] and hash the inline descriptor. */ uint64_t h = 0; + const int64_t* nullw = (const int64_t*)((const char*)keys + ly->key_off[n_keys]); + const bool nullable = ly->null_words != 0; for (uint32_t k = 0; k < n_keys; k++) { - uint64_t kh = inline_layout_key_hash(ly, k, key_types, keys, key_data, key_pool); + uint64_t kh = (nullable && ((uint64_t)nullw[k >> 6] >> (k & 63)) & 1u) + ? ray_hash_i64(0) + : inline_layout_key_hash(ly, k, key_types, keys, key_data, key_pool); h = (k == 0) ? kh : ray_hash_combine(h, kh); } - const int64_t* nullw = (const int64_t*)((const char*)keys + ly->key_off[n_keys]); return ght_hash_null_words(h, nullw, ly->null_words); } /* Packed tuple: one avalanche over the whole key region. MUST stay in @@ -4180,10 +4128,15 @@ static inline uint64_t hash_keys_inline(const int64_t* keys, const int8_t* key_t if (ly->packed_key) return ght_hash_lanes(keys, (uint32_t)n_keys + ly->null_words); const uint8_t* const kflags = ly->key_flags; + const bool nullable = ly->null_words != 0; uint64_t h = 0; for (uint32_t k = 0; k < n_keys; k++) { uint64_t kh; - if (kflags[k] & GHT_KEYF_WIDE) { + if (nullable && ((uint64_t)keys[n_keys + (k >> 6)] >> (k & 63)) & 1u) { + /* Null key (see above): the builder stored 0 and hashed + * ray_hash_i64(0), whatever the key type. */ + kh = ray_hash_i64(0); + } else if (kflags[k] & GHT_KEYF_WIDE) { /* Wide key: keys[k] is the source row index. Resolve + hash the * actual bytes (GUID fixed / STR SSO via pool). */ kh = wide_key_hash_at(ly, k, key_data, key_pool, keys[k]); diff --git a/src/ops/internal.h b/src/ops/internal.h index deda017ca..e49c017c5 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -1721,4 +1721,20 @@ static inline double clear_neg_zero(double v) { return v; } +/* One F64 value as one hash key. Every NaN payload folds to the same + * canonical NaN and -0.0 to +0.0, so a null counts once however it was + * produced and 0.0 keys the same whichever sign it carries. + * + * Shared rather than open-coded because agreement between kernels is the + * point: count-distinct answers from a serial loop, a partitioned one and a + * per-group buffer depending on the row and group counts, and they have to + * key a value identically or the count depends on the shape of the data. */ +static inline int64_t canon_f64_key(double v) { + if (v != v) v = (double)NAN; + else v = clear_neg_zero(v); + int64_t k; + memcpy(&k, &v, sizeof(int64_t)); + return k; +} + #endif /* RAY_EXEC_INTERNAL_H */ diff --git a/src/ops/pivot.c b/src/ops/pivot.c index 8587d9d35..8a2b5d0a5 100644 --- a/src/ops/pivot.c +++ b/src/ops/pivot.c @@ -273,25 +273,54 @@ static int64_t if_value_index(ray_t* v, int64_t* ids, int64_t j, return -1; } +/* A double with no integer image — a NaN (the F64 null) or a magnitude past + * the int64 range — must not be cast. The cast is undefined, and where it + * does not trap the result differs per target, so a null would narrow into a + * different arbitrary number on each platform. The integer null is the one + * in-band value that means "no representable answer", so use it for both. */ +static inline int64_t if_f64_to_i64(double x) { + if (!(x >= -9223372036854775808.0 && x < 9223372036854775808.0)) + return NULL_I64; + return (int64_t)x; +} + static int64_t if_atom_i64(ray_t* v) { switch (-v->type) { case RAY_I64: case RAY_TIMESTAMP: return v->i64; case RAY_I32: case RAY_DATE: case RAY_TIME: return v->i32; case RAY_I16: return v->i16; case RAY_BOOL: case RAY_U8: return v->b8; - case RAY_F64: case RAY_F32: return (int64_t)v->f64; + case RAY_F64: case RAY_F32: return if_f64_to_i64(v->f64); default: return 0; } } +/* A null atom stays null across the widths. Converting the value instead — + * an I64 sentinel read as a double — produces an ordinary huge number, so + * `(if c f 0N)` over an F64 column wrote -9.22e18 where a null belongs. */ static double if_atom_f64(ray_t* v) { + if (RAY_ATOM_IS_NULL(v)) return (double)NAN; return (v->type == -RAY_F64 || v->type == -RAY_F32) ? v->f64 : (double)if_atom_i64(v); } +/* Does this branch value contribute a null to the output? A vector says so + * with its attr; an atom says so by BEING the sentinel, and nothing sets the + * attr for it — so `(if x d 0Nd)` wrote the sentinel and then rendered it as + * an ordinary date, since the formatter reads the attr, not the value. */ +static bool if_val_has_null(ray_t* v) { + if (!v) return false; + if (!ray_is_atom(v)) return (v->attrs & RAY_ATTR_HAS_NULLS) != 0; + /* RAY_ATOM_IS_NULL answers for the atom's OWN type, which is the right + * question: keying off out_type missed a null whose sentinel is a + * different width from the promoted result, so `(if c f 0N)` over an F64 + * column wrote the I64 sentinel as a number with no null marked. */ + return RAY_ATOM_IS_NULL(v); +} + static int64_t if_vec_i64(ray_t* v, int64_t idx) { - if (v->type == RAY_F64) return (int64_t)((double*)ray_data(v))[idx]; - if (v->type == RAY_F32) return (int64_t)((float*)ray_data(v))[idx]; + if (v->type == RAY_F64) return if_f64_to_i64(((double*)ray_data(v))[idx]); + if (v->type == RAY_F32) return if_f64_to_i64((double)((float*)ray_data(v))[idx]); return read_col_i64(ray_data(v), idx, v->type, v->attrs); } @@ -316,27 +345,90 @@ static int8_t if_value_type(ray_t* v) { return (t == RAY_F32) ? RAY_F64 : t; } -static int8_t if_promote_type(int8_t a, int8_t b) { - if (a == 0) return b; - if (b == 0) return a; - if (a == RAY_STR || b == RAY_STR) return RAY_STR; - if (a == RAY_SYM || b == RAY_SYM) return RAY_SYM; - if (a == RAY_F64 || b == RAY_F64 || a == RAY_F32 || b == RAY_F32) - return RAY_F64; - if (a == RAY_I64 || b == RAY_I64 || - a == RAY_TIMESTAMP || b == RAY_TIMESTAMP) - return RAY_I64; - if (a == RAY_I32 || b == RAY_I32 || - a == RAY_DATE || b == RAY_DATE || a == RAY_TIME || b == RAY_TIME) - return RAY_I32; - if (a == RAY_I16 || b == RAY_I16) return RAY_I16; - if (a == RAY_U8 || b == RAY_U8) return RAY_U8; - return RAY_BOOL; + + +/* The graph already promoted the two branch types into op->out_type, and that + * is the answer — with one exception it cannot know statically. A branch that + * ends up supplying no rows never materialises its type, so an F64 demanded by + * a float branch that never ran should not survive: the integer side keeps its + * own width. That is the whole of the narrowing this arm does, and it is why + * (if (> v 0) v (sqrt s)) sums to 15 rather than 15.0 when every row is + * positive. + * + * And only where the eager arm could not have handled the node at all — a STR + * output, or a branch it cannot fill elementwise. Where it could, it fills + * every row from op->out_type and never narrows, so narrowing here would make + * the same expression answer differently by worker count, which is the defect + * being fixed. + * + * Anything beyond that was a second promotion ladder living beside the graph's, + * and the two had drifted: it folded two matching temporal types down to their + * integer storage, so the same expression answered TIMESTAMP or I64 depending + * on which arm of exec_if ran. */ +/* How wide a value of this type is as a hash/store key, for the widen-only + * merge below. Only the numeric ladder is ordered; anything else answers 0 + * and is never used to widen. */ +static int if_type_rank(int8_t t) { + switch (t) { + case RAY_BOOL: return 1; + case RAY_U8: return 2; + case RAY_I16: return 3; + case RAY_I32: return 4; + case RAY_I64: return 5; + case RAY_F64: return 6; + default: return 0; + } } -static int8_t if_selected_type(ray_t* then_v, ray_t* else_v, int8_t fallback) { - int8_t t = if_promote_type(if_value_type(then_v), if_value_type(else_v)); - return t ? t : fallback; +/* The graph promoted the branch types into op->out_type, but it promoted the + * declared types of the branch EXPRESSIONS, and arithmetic widens beyond + * them: (* a a) over an I32 column is computed and stored as I64, and calling + * the result I32 truncates every value. So the declared type is a floor, not + * an answer — whichever of it and the materialised values is wider wins. + * + * Narrowing is only ever right for a branch that supplied no rows, where the + * type it would have contributed never materialised; even then it is limited + * to nodes the eager arm could not have taken, since that arm fills from + * op->out_type and never narrows, and the two answering differently by worker + * count is the defect this is all about. */ +static int8_t if_selected_type(ray_t* then_v, ray_t* else_v, int8_t declared, + bool eager_possible) { + int8_t tt = if_value_type(then_v); + int8_t et = if_value_type(else_v); + + /* Narrowing is for a branch that supplied no rows, and only where the + * declared type came FROM that branch — otherwise it is not narrowing but + * disagreeing with the eager arm. Two shapes qualify: + * + * a float branch that never ran, leaving integers that keep their own + * width — this is what makes (if (> v 0) v (sqrt s)) sum to 15 and not + * 15.0; + * + * a string branch that never ran, leaving a number that would otherwise + * be written into a string column and read back as empty. + * + * Two temporal branches do not qualify: their I64 comes from the pair, not + * from either one, so narrowing to the survivor made a nested-if branch + * answer DATE where the same expression with a bare column answered I64. */ + if (!eager_possible && (!then_v || !else_v)) { + int8_t live = then_v ? tt : et; + int lr = if_type_rank(live); + bool float_branch_absent = declared == RAY_F64 && + lr && lr < if_type_rank(RAY_F64); + bool string_branch_absent = (declared == RAY_STR || declared == RAY_SYM) && + lr > 0; + if (float_branch_absent || string_branch_absent) return live; + } + + int dr = if_type_rank(declared); + if (dr) { + int8_t widest = declared; + int wr = dr; + if (if_type_rank(tt) > wr) { widest = tt; wr = if_type_rank(tt); } + if (if_type_rank(et) > wr) { widest = et; } + return widest; + } + return declared; } static bool if_scatter_numeric(ray_t* result, ray_t* value, int64_t* ids, @@ -496,13 +588,19 @@ static ray_t* exec_if_selected(ray_graph_t* g, ray_op_t* op, ray_t* cond_v) { * here. Only when workers exist: with a 0-worker pool (-c 1) the * eager fill runs serially over ALL rows for BOTH branches, which * loses to the selected path's touch-only-passing-rows scheme. */ + /* Whether the eager arm is even a candidate for this node — not whether + * it runs, which also depends on the pool. Where it is, this arm must + * answer exactly as it would, or the same expression gets two types + * depending on the worker count. Where it is not, this arm is the only + * one there is and may report the type the rows actually have. */ + bool eager_possible = op->out_type != RAY_STR && + if_branch_trivial(g, then_op) && + if_branch_trivial(g, else_op) && + if_type_eager_ok(then_op->out_type, op->out_type) && + if_type_eager_ok(else_op->out_type, op->out_type); { ray_pool_t* rp = ray_pool_get(); - if (rp && rp->n_workers > 0 && - op->out_type != RAY_STR && - if_branch_trivial(g, then_op) && if_branch_trivial(g, else_op) && - if_type_eager_ok(then_op->out_type, op->out_type) && - if_type_eager_ok(else_op->out_type, op->out_type)) + if (rp && rp->n_workers > 0 && eager_possible) return NULL; } @@ -544,7 +642,7 @@ static ray_t* exec_if_selected(ray_graph_t* g, ray_op_t* op, ray_t* cond_v) { return else_v; } - int8_t out_type = if_selected_type(then_v, else_v, op->out_type); + int8_t out_type = if_selected_type(then_v, else_v, op->out_type, eager_possible); if (!if_lazy_supported_type(out_type)) { if (then_v) ray_release(then_v); if (else_v) ray_release(else_v); @@ -560,6 +658,8 @@ static ray_t* exec_if_selected(ray_graph_t* g, ray_op_t* op, ray_t* cond_v) { return result; } result->len = nrows; + if (if_val_has_null(then_v) || if_val_has_null(else_v)) + result->attrs |= RAY_ATTR_HAS_NULLS; if (out_type == RAY_STR) memset(ray_data(result), 0, (size_t)nrows * sizeof(ray_str_t)); else @@ -695,6 +795,26 @@ static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op) { return else_v; } + /* A scalar condition has one cell, and the fills below index it per row — + * reading past it, so `(if false f 1.0)` returned a mixture of both + * branches. Expand it once so every consumer sees a full-length mask; + * the selected arm declines a scalar condition outright, which is why + * this only ever mattered here. */ + if (ray_is_atom(cond_v)) { + int64_t n = ray_is_atom(then_v) ? (ray_is_atom(else_v) ? 1 : else_v->len) + : then_v->len; + uint8_t on = cond_v->b8 ? 1 : 0; + ray_t* mask = ray_vec_new(RAY_BOOL, n); + if (!mask || RAY_IS_ERR(mask)) { + ray_release(cond_v); ray_release(then_v); ray_release(else_v); + return mask ? mask : ray_error("oom", NULL); + } + memset(ray_data(mask), on, (size_t)n); + mask->len = n; + ray_release(cond_v); + cond_v = mask; + } + int64_t len = cond_v->len; bool then_scalar = ray_is_atom(then_v) || (then_v->type > 0 && then_v->len == 1); bool else_scalar = ray_is_atom(else_v) || (else_v->type > 0 && else_v->len == 1); @@ -708,6 +828,11 @@ static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op) { return result; } result->len = len; + /* Same reason as the selected arm: an atom null is the sentinel value and + * carries no attr of its own, so without this the sentinel is rendered as + * an ordinary date or timestamp. */ + if (if_val_has_null(then_v) || if_val_has_null(else_v)) + result->attrs |= RAY_ATTR_HAS_NULLS; uint8_t* cond_p = (uint8_t*)ray_data(cond_v); diff --git a/src/ops/query.c b/src/ops/query.c index e33347932..4934d118c 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -3373,14 +3373,19 @@ static ray_t* aggr_med_per_group_buf(ray_t* expr, ray_t* tbl, * no intermediate compaction. * * Specialised on element width (1/2/4/8 bytes + F64) so the inner read - * folds to a typed pointer dereference. Has-nulls falls through to - * ray_count_distinct_per_group_buf serial path (acceptable: null-bearing - * columns are rare in wide analytical aggregates). */ + * folds to a typed pointer dereference. + * + * A null counts as one distinct value, matching the serial path and the + * ungrouped builtin — `distinct` keeps at most one null, so `count` over it + * sees exactly one. Nothing special is needed to make that happen: an + * integer null is INT_MIN, nonzero and unique once widened, so it hashes as + * an ordinary key; canon_f64_key folds every NaN payload to one; and a SYM + * null is id 0, which the table cannot hold and which therefore rides the + * side flag the literal 0 already uses. */ typedef struct { int8_t in_type; uint8_t in_attrs; const void* base; - bool has_nulls; uint8_t esz; /* 1/2/4/8 */ bool is_f64; const int64_t* idx_buf; @@ -3455,52 +3460,28 @@ static void cdpg_buf_par_fn(void* vctx, uint32_t worker_id, int64_t distinct = 0; int saw_zero = 0; - bool has_nulls = ctx->has_nulls; if (ctx->is_f64) { const double* d = (const double*)ctx->base; for (int64_t i = 0; i < cnt; i++) { int64_t r = idxs[i]; - double fv = d[r]; - if (has_nulls && fv != fv) continue; - fv = clear_neg_zero(fv); - int64_t vbits = 0; - memcpy(&vbits, &fv, sizeof(int64_t)); - CDPG_BUF_INSERT(vbits); + CDPG_BUF_INSERT(canon_f64_key(d[r])); } } else if (ctx->esz == 8) { + /* The null sentinels are INT_MIN: nonzero, and unique once widened + * to int64_t, so they hash as an ordinary key and a null counts + * exactly once with no special case. */ const int64_t* d = (const int64_t*)ctx->base; - if (has_nulls) { - for (int64_t i = 0; i < cnt; i++) { - int64_t v = d[idxs[i]]; - if (v == NULL_I64) continue; - CDPG_BUF_INSERT(v); - } - } else { - for (int64_t i = 0; i < cnt; i++) { - CDPG_BUF_INSERT(d[idxs[i]]); - } - } + for (int64_t i = 0; i < cnt; i++) + CDPG_BUF_INSERT(d[idxs[i]]); } else if (ctx->esz == 4) { const int32_t* d = (const int32_t*)ctx->base; - if (has_nulls) { - for (int64_t i = 0; i < cnt; i++) { - int32_t v = d[idxs[i]]; - if (v == NULL_I32) continue; - CDPG_BUF_INSERT((int64_t)v); - } - } else { - for (int64_t i = 0; i < cnt; i++) { - CDPG_BUF_INSERT((int64_t)d[idxs[i]]); - } - } + for (int64_t i = 0; i < cnt; i++) + CDPG_BUF_INSERT((int64_t)d[idxs[i]]); } else if (ctx->esz == 2) { const int16_t* d = (const int16_t*)ctx->base; - for (int64_t i = 0; i < cnt; i++) { - int16_t v = d[idxs[i]]; - if (has_nulls && v == NULL_I16) continue; - CDPG_BUF_INSERT((int64_t)v); - } + for (int64_t i = 0; i < cnt; i++) + CDPG_BUF_INSERT((int64_t)d[idxs[i]]); } else { /* esz == 1 — BOOL/U8 are non-nullable */ const uint8_t* d = (const uint8_t*)ctx->base; for (int64_t i = 0; i < cnt; i++) { @@ -4030,7 +4011,6 @@ static ray_t* count_distinct_per_group_buf(ray_t* inner_expr, ray_t* tbl, .in_type = st, .in_attrs = src->attrs, .base = ray_data(src), - .has_nulls = (src->attrs & RAY_ATTR_HAS_NULLS) != 0, .esz = ray_sym_elem_size(st, src->attrs), .is_f64 = (st == RAY_F64), .idx_buf = idx_buf, @@ -11544,6 +11524,403 @@ static ray_t* append_boxed_table_col(ray_t* orig_col, ray_t* payload, * and replace those column values. Returns a new table. */ /* Forward declarations */ +/* ---- update with WHERE, in place (#475 follow-up) ------------------- + * The WHERE arm below evaluates the predicate and every update + * expression over the whole table and then rebuilds each updated column + * cell by cell, so a keyed update into a named table costs O(rows + * present) per call with a large constant, and an attached hash index + * on the key column is never consulted. When the binding is the sole + * owner, this path resolves the rows first — through a fresh hash index + * when the predicate is a plain equality on an indexed column, otherwise + * through the same mask the legacy arm computes — gathers just those + * rows into a sub-table, evaluates the update expressions there, and + * scatters the results into the live columns in place. + * + * Only elementwise expressions take this path (see + * update_expr_elementwise); anything else, and a predicate matching no + * row, keeps the legacy arm. Every result is type-checked before + * anything is written, + * so a mistyped or wrong-length value leaves the table untouched; only + * an allocation failure inside a STR write can interrupt the scatter. */ + +static bool upsert_col_ok(ray_t* col); /* defined with the upsert path below */ +static int64_t upsert_atom_int(ray_t* a); + +/* The sub-table evaluation is only equivalent to the legacy whole-table + * evaluation for elementwise expressions. Accept a call only when its + * head resolves to a builtin flagged RAY_FN_ATOMIC and every argument is + * a column of `tbl`, a literal, a quoted symbol, or such a call. A bare + * symbol that is not a column (a free variable, possibly a table-length + * vector), an order-dependent function (deltas, sums, ...), an + * aggregate, a special form, or a lambda call keeps the legacy arm. */ +static bool update_expr_elementwise(ray_t* e, ray_t* tbl) { + if (!e || RAY_IS_ERR(e)) return false; + if (e->type == -RAY_SYM) { + if (e->attrs & ATTR_QUOTED) return true; + return ray_table_get_col(tbl, e->i64) != NULL; + } + if (e->type < 0) return true; + if (e->type != RAY_LIST) return false; + int64_t n = ray_len(e); + if (n < 2) return false; + ray_t** el = (ray_t**)ray_data(e); + ray_t* head = el[0]; + if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return false; + ray_t* fn = ray_env_get(head->i64); + if (!fn || RAY_IS_ERR(fn)) return false; + if (fn->type != RAY_UNARY && fn->type != RAY_BINARY && fn->type != RAY_VARY) return false; + if (!(fn->attrs & RAY_FN_ATOMIC)) return false; + for (int64_t i = 1; i < n; i++) + if (!update_expr_elementwise(el[i], tbl)) return false; + return true; +} + +/* Rows matching `(== col atom)` through a fresh hash index on col. + * Returns 1 with rows copied into *rows (n in *n_out), 0 when the + * predicate is not of that shape or the index cannot answer. */ +static int update_where_index_rows(ray_t* tbl, ray_t* where_expr, + ray_t** rows_hdr, int64_t** rows, int64_t* n_out) { + if (!where_expr || where_expr->type != RAY_LIST || ray_len(where_expr) != 3) return 0; + ray_t** el = (ray_t**)ray_data(where_expr); + if (!el[0] || el[0]->type != -RAY_SYM) return 0; + if (el[0]->i64 != ray_sym_intern("==", 2)) return 0; + ray_t* col = NULL; ray_t* val_node = NULL; + for (int side = 1; side <= 2 && !col; side++) { + ray_t* a = el[side]; + if (a && a->type == -RAY_SYM && ray_table_get_col(tbl, a->i64)) { + col = ray_table_get_col(tbl, a->i64); + val_node = el[3 - side]; + } + } + if (!col || !val_node || RAY_IS_ERR(val_node)) return 0; + /* The other side must be a value: a literal, a quoted symbol, or a + * variable — never a column name (that is a column-column compare). */ + if (val_node->type == -RAY_SYM && ray_table_get_col(tbl, val_node->i64)) return 0; + if (!ray_is_atom(val_node)) return 0; + if (col->attrs & RAY_ATTR_HAS_NULLS) return 0; + if (ray_index_kind(col) != RAY_IDX_HASH) return 0; + if (col->type == RAY_F64 || col->type == RAY_STR || col->type == RAY_GUID) return 0; + ray_t* v = ray_eval(val_node); + if (!v) return 0; + if (RAY_IS_ERR(v)) { ray_error_free(v); return 0; } + int ok = ray_is_atom(v) && !RAY_ATOM_IS_NULL(v) && + (col->type == RAY_SYM ? v->type == -RAY_SYM + : (v->type == -col->type || v->type == -RAY_I64 || + v->type == -RAY_I32 || v->type == -RAY_I16 || + v->type == -RAY_U8)); + int64_t key = ok ? (col->type == RAY_SYM ? v->i64 : upsert_atom_int(v)) : 0; + ray_release(v); + if (!ok) return 0; + const int64_t* ids = NULL; int64_t n = 0; + int hit = ray_index_hash_group(col, key, &ids, &n); + if (hit < 0) return 0; + int64_t* out = (int64_t*)scratch_alloc(rows_hdr, (size_t)(n > 0 ? n : 1) * sizeof(int64_t)); + if (!out) return 0; + if (n > 0) memcpy(out, ids, (size_t)n * sizeof(int64_t)); + *rows = out; *n_out = n; + return 1; +} + +/* Legacy-shaped mask evaluation (DAG, then eval with column bindings). */ +static ray_t* update_where_mask_vec(ray_t* tbl, ray_t* where_expr) { + ray_t* mask_vec = NULL; + ray_graph_t* g = ray_graph_new(tbl); + if (g) { + ray_op_t* pred = compile_expr_dag(g, where_expr); + if (pred) { + pred = ray_optimize(g, pred); + mask_vec = ray_execute(g, pred); + } + ray_graph_free(g); + } + if (!mask_vec || RAY_IS_ERR(mask_vec)) { + int64_t ncols = ray_table_ncols(tbl); + ray_env_push_query_scope(); + for (int64_t c = 0; c < ncols; c++) + ray_env_set_query_local(ray_table_col_name(tbl, c), ray_table_get_col_idx(tbl, c)); + mask_vec = ray_eval(where_expr); + ray_env_pop_scope(); + } + if (!mask_vec) return ray_error("type", "update: `where:` predicate evaluation failed"); + if (RAY_IS_ERR(mask_vec)) return mask_vec; + if (mask_vec->type != RAY_BOOL || mask_vec->len != ray_table_nrows(tbl)) { + int8_t mask_t = mask_vec->type; + ray_release(mask_vec); + return ray_error("type", "update: `where:` must produce a bool mask matching row count, got %s", ray_type_name(mask_t)); + } + return mask_vec; +} + +static ray_t* update_eval_on(ray_t* sub, ray_t* expr) { + ray_t* out = NULL; + ray_graph_t* g = ray_graph_new(sub); + if (g) { + ray_op_t* op = compile_expr_dag(g, expr); + if (op) { + op = ray_optimize(g, op); + out = ray_execute(g, op); + } + ray_graph_free(g); + } + if (!out || RAY_IS_ERR(out)) { + if (out) ray_error_free(out); + int64_t ncols = ray_table_ncols(sub); + ray_env_push_query_scope(); + for (int64_t c = 0; c < ncols; c++) + ray_env_set_query_local(ray_table_col_name(sub, c), ray_table_get_col_idx(sub, c)); + out = ray_eval(expr); + ray_env_pop_scope(); + } + if (!out) return ray_error("type", "update: failed to evaluate column update expression"); + if (RAY_IS_ERR(out)) return out; + if (ray_is_lazy(out)) out = ray_lazy_materialize(out); + return out; +} + +static bool update_numeric_promo(int8_t ct, int8_t et) { + return (ct == RAY_I64 || ct == RAY_I32 || ct == RAY_F64) && + (et == RAY_I64 || et == RAY_I32 || et == RAY_F64); +} + +/* Validate one evaluated update value against its column: NULL on ok, + * the error otherwise. Mirrors the legacy WHERE arm's acceptance. */ +static ray_t* update_value_check(ray_t* col, ray_t* val, int64_t k) { + int8_t ct = col->type; + if (val->type < 0) { + int ok = (val->type == -ct) || + (ct == RAY_F64 && val->type == -RAY_I64) || + (ct == RAY_LIST && val->type == -RAY_SYM); + if (!ok) return ray_error("type", "update: cannot assign %s value to %s column", + ray_type_name(val->type), ray_type_name(ct)); + return NULL; + } + if (!ray_is_vec(val) && val->type != RAY_LIST) + return ray_error("type", "update: cannot assign %s expression to %s column", + ray_type_name(val->type), ray_type_name(ct)); + if (ray_len(val) != k) + return ray_error("length", "update: expression yields %lld values for %lld matched rows", + (long long)ray_len(val), (long long)k); + if (val->type == ct) return NULL; + if (update_numeric_promo(ct, val->type)) return NULL; + return ray_error("type", "update: expression type %s does not match %s column", + ray_type_name(val->type), ray_type_name(ct)); +} + +static double update_cell_f64(ray_t* v, int64_t i) { + switch (v->type) { + case RAY_F64: return ((const double*)ray_data(v))[i]; + case RAY_I32: return (double)((const int32_t*)ray_data(v))[i]; + default: return (double)((const int64_t*)ray_data(v))[i]; + } +} + +/* Scatter `val` (checked) into slots[c] at rows[0..k). */ +static ray_t* update_scatter(ray_t** slots, int64_t c, const int64_t* rows, int64_t k, ray_t* val) { + ray_t* col = slots[c]; + int8_t ct = col->type; + if (ct == RAY_LIST) { + ray_t** cells = (ray_t**)ray_data(col); + for (int64_t i = 0; i < k; i++) { + ray_t* nv = (val->type < 0) ? val : ((ray_t**)ray_data(val))[i]; + ray_t* old = cells[rows[i]]; + if (nv) ray_retain(nv); + cells[rows[i]] = nv; + if (old) ray_release(old); + } + return NULL; + } + ray_index_drop(&slots[c]); + col = slots[c]; + if (RAY_IS_ERR(col)) return col; + col->attrs &= (uint8_t)~RAY_ATTR_SORTED; + + if (ct == RAY_STR) { + for (int64_t i = 0; i < k; i++) { + const char* sp; size_t sl; + if (val->type < 0) { sp = ray_str_ptr(val); sl = ray_str_len(val); } + else { sl = 0; sp = ray_str_vec_get(val, i, &sl); } + ray_t* res = ray_str_vec_set(col, rows[i], sp ? sp : "", sp ? sl : 0); + if (RAY_IS_ERR(res)) return res; + slots[c] = col = res; + } + return NULL; + } + + size_t esz = ray_sym_elem_size(ct, col->attrs); + uint8_t* d = (uint8_t*)ray_data(col); + if (val->type < 0) { + /* Atom broadcast: one encoded cell, written k times. */ + uint8_t elem[16] = {0}; + bool is_null = RAY_ATOM_IS_NULL(val); + if (ct == RAY_GUID) { + if (val->obj) memcpy(elem, ray_data(val->obj), 16); + } else if (ct == RAY_F64 && val->type == -RAY_I64) { + double p = (double)val->i64; memcpy(elem, &p, sizeof p); + } else { + memcpy(elem, &val->i64, esz); + } + for (int64_t i = 0; i < k; i++) { + if (is_null) ray_vec_set_null(col, rows[i], true); + else { + memcpy(d + (size_t)rows[i] * esz, elem, esz); + if (ct == RAY_SYM && val->i64 == 0) col->attrs |= RAY_ATTR_HAS_NULLS; + } + } + return NULL; + } + + if (val->type != ct) { + /* Numeric promotion among I64 / I32 / F64, null-aware. */ + void* p = ray_data(col); + for (int64_t i = 0; i < k; i++) { + int64_t r = rows[i]; + if (ray_vec_is_null(val, i)) { ray_vec_set_null(col, r, true); continue; } + if (ct == RAY_F64) { + ((double*)p)[r] = update_cell_f64(val, i); + } else if (val->type == RAY_F64) { + double x = ((const double*)ray_data(val))[i]; + if (ct == RAY_I64) ((int64_t*)p)[r] = ray_cast_f64_to_i64_null(x); + else ((int32_t*)p)[r] = ray_cast_f64_to_i32_null(x); + if (ray_vec_is_null(col, r)) col->attrs |= RAY_ATTR_HAS_NULLS; + } else if (ct == RAY_I64) { + ((int64_t*)p)[r] = (int64_t)((const int32_t*)ray_data(val))[i]; + } else { + ((int32_t*)p)[r] = (int32_t)((const int64_t*)ray_data(val))[i]; + } + } + return NULL; + } + + if (ct == RAY_SYM) { + int64_t* ids = (int64_t*)ray_data(col); + for (int64_t i = 0; i < k; i++) { + int64_t id = sym_cell_runtime_id(val, i); + ids[rows[i]] = id; + if (id == 0) col->attrs |= RAY_ATTR_HAS_NULLS; + } + return NULL; + } + const uint8_t* s = (const uint8_t*)ray_data(val); + bool vn = payload_may_have_nulls(val); + for (int64_t i = 0; i < k; i++) { + if (vn && ray_vec_is_null(val, i)) { ray_vec_set_null(col, rows[i], true); continue; } + memcpy(d + (size_t)rows[i] * esz, s + (size_t)i * esz, esz); + } + return NULL; +} + +static ray_t* update_where_inplace(ray_t* tbl, int64_t inplace_sym, ray_t* dict, + ray_t* where_expr, bool* handled) { + *handled = false; + int64_t ncols = ray_table_ncols(tbl); + if (inplace_sym < 0 || ncols <= 0) return NULL; + if (tbl->rc != 2 || tbl->mmod != 0 || (tbl->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA))) return NULL; + ray_t* live_cols = ((ray_t**)ray_data(tbl))[1]; + if (!live_cols || live_cols->rc != 1 || live_cols->len != ncols) return NULL; + ray_t** slots = (ray_t**)ray_data(live_cols); + for (int64_t c = 0; c < ncols; c++) + if (slots[c]->rc != 1 || !upsert_col_ok(slots[c])) return NULL; + + DICT_VIEW_DECL(updf); + DICT_VIEW_OPEN(dict, updf); + if (DICT_VIEW_OVERFLOW(updf)) { DICT_VIEW_CLOSE(updf); *handled = true; return ray_error("oom", NULL); } + int64_t from_id = ray_sym_intern("from", 4); + int64_t where_id = ray_sym_intern("where", 5); + int64_t by_id = ray_sym_intern("by", 2); + + /* One update per target column, first dict entry wins (legacy order). */ + ray_t* ucol_hdr = NULL; ray_t* uexpr_hdr = NULL; ray_t* uval_hdr = NULL; + int64_t* ucol = (int64_t*)scratch_alloc(&ucol_hdr, (size_t)ncols * sizeof(int64_t)); + ray_t** uexpr = (ray_t**)scratch_alloc(&uexpr_hdr, (size_t)ncols * sizeof(ray_t*)); + ray_t** uval = (ray_t**)scratch_alloc(&uval_hdr, (size_t)ncols * sizeof(ray_t*)); + if (!ucol || !uexpr || !uval) { + if (ucol_hdr) scratch_free(ucol_hdr); + if (uexpr_hdr) scratch_free(uexpr_hdr); + if (uval_hdr) scratch_free(uval_hdr); + DICT_VIEW_CLOSE(updf); *handled = true; return ray_error("oom", NULL); + } + int64_t nu = 0; + bool rowwise = true; + for (int64_t c = 0; c < ncols; c++) { + int64_t cn = ray_table_col_name(tbl, c); + for (int64_t d = 0; d + 1 < updf_n; d += 2) { + int64_t kid = updf[d]->i64; + if (kid == from_id || kid == where_id || kid == by_id) continue; + if (kid != cn) continue; + ucol[nu] = c; uexpr[nu] = updf[d + 1]; uval[nu] = NULL; nu++; + if (!update_expr_elementwise(updf[d + 1], tbl)) rowwise = false; + break; + } + } + if (!rowwise) { + scratch_free(ucol_hdr); scratch_free(uexpr_hdr); scratch_free(uval_hdr); + DICT_VIEW_CLOSE(updf); + return NULL; + } + *handled = true; + + /* Matched rows: index probe, else the legacy mask. */ + ray_t* rows_hdr = NULL; int64_t* rows = NULL; int64_t k = 0; + ray_t* err = NULL; + if (!update_where_index_rows(tbl, where_expr, &rows_hdr, &rows, &k)) { + ray_t* mask = update_where_mask_vec(tbl, where_expr); + if (RAY_IS_ERR(mask)) err = mask; + else { + int64_t nrows = mask->len; + const uint8_t* m = (const uint8_t*)ray_data(mask); + int64_t cnt = 0; + for (int64_t r = 0; r < nrows; r++) cnt += (m[r] != 0); + rows = (int64_t*)scratch_alloc(&rows_hdr, (size_t)(cnt > 0 ? cnt : 1) * sizeof(int64_t)); + if (!rows) err = ray_error("oom", NULL); + else for (int64_t r = 0; r < nrows; r++) if (m[r]) rows[k++] = r; + ray_release(mask); + } + } + + /* No matched row: the legacy arm still evaluates every expression + * over the table and reports its errors; evaluating over an empty + * sub-table could raise where it would not, so leave it to them. */ + if (!err && k == 0) { + if (rows_hdr) scratch_free(rows_hdr); + scratch_free(ucol_hdr); scratch_free(uexpr_hdr); scratch_free(uval_hdr); + DICT_VIEW_CLOSE(updf); + *handled = false; + return NULL; + } + + /* Sub-table of the matched rows; expressions evaluate against it. */ + ray_t* idxv = NULL; ray_t* sub = NULL; + if (!err && nu > 0) { + idxv = ray_vec_new(RAY_I64, k); + if (RAY_IS_ERR(idxv)) { err = idxv; idxv = NULL; } + else { + ray_t* r2 = ray_vec_append_raw(idxv, rows, k); + if (RAY_IS_ERR(r2)) { err = r2; } else idxv = r2; + } + if (!err) { + sub = ray_at_fn(tbl, idxv); + if (!sub || RAY_IS_ERR(sub)) { err = sub ? sub : ray_error("oom", NULL); sub = NULL; } + } + } + for (int64_t u = 0; u < nu && !err; u++) { + ray_t* v = update_eval_on(sub, uexpr[u]); + if (RAY_IS_ERR(v)) { err = v; break; } + uval[u] = v; + err = update_value_check(slots[ucol[u]], v, k); + } + for (int64_t u = 0; u < nu && !err; u++) + err = update_scatter(slots, ucol[u], rows, k, uval[u]); + + for (int64_t u = 0; u < nu; u++) if (uval[u]) ray_release(uval[u]); + if (sub) ray_release(sub); + if (idxv) ray_release(idxv); + if (rows_hdr) scratch_free(rows_hdr); + scratch_free(ucol_hdr); scratch_free(uexpr_hdr); scratch_free(uval_hdr); + DICT_VIEW_CLOSE(updf); + if (err) return err; + return ray_sym(inplace_sym); +} + ray_t* ray_update_fn(ray_t** args, int64_t n) { return ray_update(args, n); } @@ -11854,6 +12231,12 @@ ray_t* ray_update(ray_t** args, int64_t n) { int64_t nrows = ray_table_nrows(tbl); uint8_t* mask = NULL; + if (where_expr) { + bool fast_handled = false; + ray_t* fast = update_where_inplace(tbl, inplace_sym, dict, where_expr, &fast_handled); + if (fast_handled) { ray_release(tbl); return fast; } + } + if (where_expr) { /* Try DAG compilation first, fall back to eval-level */ ray_t* mask_vec = NULL; @@ -12605,9 +12988,14 @@ static bool parted_segment_attrs_valid(int8_t base, uint8_t attrs) { if (base == RAY_SYM) allowed |= RAY_SYM_W_MASK; if (base == RAY_I32 || base == RAY_I64) allowed |= RAY_ATTR_HAS_LINK; + /* SYM/STR nulls (the empty symbol / empty string) are in-band — the bit + * only marks their presence, the payload is unchanged — and the store + * carries it across a save, so every mapped partition holding one blank + * cell arrives here with it set. */ if (base == RAY_I16 || base == RAY_I32 || base == RAY_I64 || base == RAY_F32 || base == RAY_F64 || base == RAY_DATE || - base == RAY_TIME || base == RAY_TIMESTAMP || base == RAY_GUID) + base == RAY_TIME || base == RAY_TIMESTAMP || base == RAY_GUID || + base == RAY_SYM || base == RAY_STR) allowed |= RAY_ATTR_HAS_NULLS; return (attrs & (uint8_t)~allowed) == 0; } @@ -14279,6 +14667,497 @@ ray_t* ray_insert(ray_t** args, int64_t n) { /* (upsert table key_col (list val1 val2 ...)) — update row if key matches, else insert. * Special form: first arg may be 'sym for in-place, other args are evaluated. */ +/* ---- Upsert one-pass path (#475) ------------------------------------ + * The legacy arms below find the target row with a linear key scan and + * rebuild the whole table to write one cell — per payload row, so a + * named-table upsert costs O(rows present) per row and a batch costs + * the same as the equivalent loop. This path does one pass per call: + * matched rows have their cells written in place, missing keys append + * (amortized, as in insert's #455 path), and a batch resolves its keys + * through one hash over the target built once per call. A single-row + * call consults a fresh hash index on the key column when one is + * attached, and otherwise runs one typed scan. + * + * When the binding is the sole owner the live columns are mutated; + * otherwise (a value target, or a shared table/column) the columns are + * copied once and the same pass runs on the copy, which keeps the + * value semantics of the rebuild at O(rows + payload) per call rather + * than per row. Any gate miss returns NULL with *handled = false and + * the legacy arms run unchanged. + * + * Every cell is type-checked before anything is written, so a bad + * payload leaves the table untouched. Only an allocation failure can + * interrupt the pass; appended rows are then rolled back, while cells + * already overwritten in place keep their new values. */ + +static bool upsert_key_type_ok(int8_t t) { + switch (t) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_F64: case RAY_SYM: case RAY_STR: case RAY_GUID: + return true; + default: + return false; + } +} + +static bool upsert_col_ok(ray_t* col) { + if (!col || RAY_IS_ERR(col)) return false; + /* An EMPTY LIST column is typeless — the legacy insert arm adopts a + * concrete type from the first payload; a non-empty LIST column is + * genuinely boxed and is written like any other. */ + if (col->type == RAY_LIST && ray_len(col) == 0) return false; + if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) return false; + if (col->mmod != 0) return false; + if (col->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)) return false; + /* Cells are written as W64 runtime-domain ids (append_atom_to_col); + * a narrow or store-domain column needs the legacy re-expression. */ + if (col->type == RAY_SYM && + ((col->attrs & RAY_SYM_W_MASK) != RAY_SYM_W64 || + col->sym_domain != ray_sym_runtime_domain())) + return false; + return true; +} + +/* Integer-family cell widened to int64 through its storage width. */ +static int64_t upsert_int_cell(const ray_t* col, int64_t r) { + const void* d = ray_data((ray_t*)col); + switch (col->type) { + case RAY_BOOL: case RAY_U8: return (int64_t)((const uint8_t*)d)[r]; + case RAY_I16: return (int64_t)((const int16_t*)d)[r]; + case RAY_I32: case RAY_DATE: case RAY_TIME: + return (int64_t)((const int32_t*)d)[r]; + default: return ((const int64_t*)d)[r]; + } +} + +static int64_t upsert_atom_int(ray_t* a) { + return a->type == -RAY_BOOL ? (int64_t)a->b8 : elem_as_i64(a); +} + +static uint64_t upsert_hash_cell(ray_t* col, int64_t r) { + switch (col->type) { + case RAY_F64: return ray_hash_f64(((const double*)ray_data(col))[r]); + case RAY_SYM: return ray_hash_i64(ray_read_sym(ray_data(col), r, col->type, col->attrs)); + case RAY_STR: { + size_t n = 0; + const char* s = ray_str_vec_get(col, r, &n); + return ray_hash_bytes(s ? s : "", n); + } + case RAY_GUID: return ray_hash_bytes((const uint8_t*)ray_data(col) + r * 16, 16); + default: return ray_hash_i64(upsert_int_cell(col, r)); + } +} + +static uint64_t upsert_hash_atom(int8_t ct, ray_t* a) { + static const uint8_t zero_guid[16] = {0}; + switch (ct) { + case RAY_F64: return ray_hash_f64(as_f64(a)); + case RAY_SYM: return ray_hash_i64(a->i64); + case RAY_STR: { + const char* s = ray_str_ptr(a); + return ray_hash_bytes(s ? s : "", ray_str_len(a)); + } + case RAY_GUID: return ray_hash_bytes(a->obj ? ray_data(a->obj) : zero_guid, 16); + default: return ray_hash_i64(upsert_atom_int(a)); + } +} + +/* Cell-vs-atom equality with the legacy scan's semantics: F64 by value + * (NaN never matches, so a null F64 key always appends), SYM by raw id, + * STR by bytes, integers widened. */ +static bool upsert_cell_eq_atom(ray_t* col, int64_t r, ray_t* a) { + static const uint8_t zero_guid[16] = {0}; + switch (col->type) { + case RAY_F64: return ((const double*)ray_data(col))[r] == as_f64(a); + case RAY_SYM: return ray_read_sym(ray_data(col), r, col->type, col->attrs) == a->i64; + case RAY_STR: { + size_t n = 0; + const char* s = ray_str_vec_get(col, r, &n); + size_t m = ray_str_len(a); + const char* p = ray_str_ptr(a); + return n == m && (m == 0 || (s && p && memcmp(s, p, m) == 0)); + } + case RAY_GUID: + return memcmp((const uint8_t*)ray_data(col) + r * 16, + a->obj ? ray_data(a->obj) : zero_guid, 16) == 0; + default: return upsert_int_cell(col, r) == upsert_atom_int(a); + } +} + +#define UPSERT_HASH_SEED 0x9E3779B97F4A7C15ULL + +static uint64_t upsert_hash_row(ray_t** slots, const int64_t* kci, int64_t nk, int64_t r) { + uint64_t h = UPSERT_HASH_SEED; + for (int64_t k = 0; k < nk; k++) + h = ray_hash_combine(h, upsert_hash_cell(slots[kci[k]], r)); + return h; +} + +static uint64_t upsert_hash_atoms(ray_t** slots, const int64_t* kci, int64_t nk, ray_t** cells) { + uint64_t h = UPSERT_HASH_SEED; + for (int64_t k = 0; k < nk; k++) + h = ray_hash_combine(h, upsert_hash_atom(slots[kci[k]]->type, cells[kci[k]])); + return h; +} + +static bool upsert_row_eq_atoms(ray_t** slots, const int64_t* kci, int64_t nk, int64_t r, ray_t** cells) { + for (int64_t k = 0; k < nk; k++) + if (!upsert_cell_eq_atom(slots[kci[k]], r, cells[kci[k]])) return false; + return true; +} + +/* Open-addressing map from key tuple to row: slots hold row+1, 0 is + * empty. Every target row is entered in row order, so a probe walking + * from the hash slot meets duplicates lowest-row first — the same row + * the legacy scan picks. Rows appended during the pass are entered as + * they land, so a key repeated inside one batch updates the row its + * first occurrence appended. */ +typedef struct { + ray_t* hdr; + int64_t* slot; + uint64_t mask; +} upsert_map_t; + +static bool upsert_map_init(upsert_map_t* mp, int64_t entries) { + uint64_t cap = 16; + while (cap < (uint64_t)entries * 2) cap <<= 1; + mp->slot = (int64_t*)scratch_alloc(&mp->hdr, cap * sizeof(int64_t)); + if (!mp->slot) return false; + memset(mp->slot, 0, cap * sizeof(int64_t)); + mp->mask = cap - 1; + return true; +} + +static void upsert_map_put(upsert_map_t* mp, uint64_t h, int64_t row) { + uint64_t s = h & mp->mask; + while (mp->slot[s] != 0) s = (s + 1) & mp->mask; + mp->slot[s] = row + 1; +} + +static int64_t upsert_map_find(upsert_map_t* mp, uint64_t h, ray_t** slots, + const int64_t* kci, int64_t nk, ray_t** cells) { + uint64_t s = h & mp->mask; + for (;;) { + int64_t e = mp->slot[s]; + if (e == 0) return -1; + if (upsert_row_eq_atoms(slots, kci, nk, e - 1, cells)) return e - 1; + s = (s + 1) & mp->mask; + } +} + +/* Single-row lookup: a fresh hash index on a lone key column answers in + * O(1); otherwise one typed scan. */ +static int64_t upsert_find_row(ray_t** slots, const int64_t* kci, int64_t nk, + ray_t** cells, int64_t nrows) { + if (nk == 1) { + ray_t* col = slots[kci[0]]; + ray_t* a = cells[kci[0]]; + int8_t t = col->type; + if (t == RAY_SYM || (t != RAY_F64 && t != RAY_STR && t != RAY_GUID)) { + int64_t key = (t == RAY_SYM) ? a->i64 : upsert_atom_int(a); + int64_t hit = ray_index_find_row(col, key); + if (hit >= -1) return hit; + if (t == RAY_I64 || t == RAY_TIMESTAMP || t == RAY_SYM) { + const int64_t* d = (const int64_t*)ray_data(col); + for (int64_t r = 0; r < nrows; r++) if (d[r] == key) return r; + return -1; + } + if (t == RAY_I32 || t == RAY_DATE || t == RAY_TIME) { + const int32_t* d = (const int32_t*)ray_data(col); + for (int64_t r = 0; r < nrows; r++) if ((int64_t)d[r] == key) return r; + return -1; + } + } + } + for (int64_t r = 0; r < nrows; r++) + if (upsert_row_eq_atoms(slots, kci, nk, r, cells)) return r; + return -1; +} + +/* Would append_atom_to_col accept `cell` for a column of type `ct`? + * NULL on yes, the error it would raise otherwise. */ +static ray_t* upsert_cell_fits(int8_t ct, ray_t* cell) { + if (ct == RAY_LIST) return NULL; + if (!ray_is_atom(cell)) + return ray_error("type", "upsert: %s column requires an atom value, got %s", + ray_type_name(ct), ray_type_name(cell->type)); + if (RAY_ATOM_IS_NULL(cell)) return NULL; + int8_t at = cell->type; + bool is_int = (at == -RAY_I64 || at == -RAY_I32 || at == -RAY_I16 || at == -RAY_U8); + bool ok; + switch (ct) { + case RAY_BOOL: ok = (at == -RAY_BOOL); break; + case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + ok = is_int; break; + case RAY_F64: ok = (at == -RAY_F64 || is_int); break; + case RAY_DATE: ok = (at == -RAY_DATE); break; + case RAY_TIME: ok = (at == -RAY_TIME); break; + case RAY_TIMESTAMP: ok = (at == -RAY_TIMESTAMP); break; + case RAY_GUID: ok = (at == -RAY_GUID); break; + case RAY_SYM: ok = (at == -RAY_SYM); break; + case RAY_STR: ok = (at == -RAY_STR); break; + default: + return ray_error("type", "upsert: unsupported column type %s", ray_type_name(ct)); + } + if (ok) return NULL; + return ray_error("type", "upsert: value type %s does not match %s column", + ray_type_name(at), ray_type_name(ct)); +} + +/* Overwrite one cell of slots[c] with `cell`. Boxed columns swap the + * pointer; STR columns write through ray_str_vec_set; fixed-width + * columns append through append_atom_to_col (which owns the coercion + * and null encoding) and move the new tail cell into place. Any + * attached index is dropped first: an overwritten cell would otherwise + * leave a fresh-looking index answering with stale rows. */ +static ray_t* upsert_write_cell(ray_t** slots, int64_t c, int64_t row, ray_t* cell) { + ray_t* col = slots[c]; + if (col->type == RAY_LIST) { + ray_t** cells = (ray_t**)ray_data(col); + ray_t* old = cells[row]; + ray_retain(cell); + cells[row] = cell; + if (old) ray_release(old); + return NULL; + } + ray_index_drop(&slots[c]); + col = slots[c]; + if (RAY_IS_ERR(col)) return col; + col->attrs &= (uint8_t)~RAY_ATTR_SORTED; + ray_t* res; + if (col->type == RAY_STR) { + res = RAY_ATOM_IS_NULL(cell) + ? ray_str_vec_set(col, row, "", 0) + : ray_str_vec_set(col, row, ray_str_ptr(cell), ray_str_len(cell)); + if (RAY_IS_ERR(res)) return res; + slots[c] = res; + return NULL; + } + int64_t tail = col->len; + res = append_atom_to_col(col, cell); + if (RAY_IS_ERR(res)) return res; + slots[c] = res; + size_t esz = ray_sym_elem_size(res->type, res->attrs); + uint8_t* d = (uint8_t*)ray_data(res); + memcpy(d + (size_t)row * esz, d + (size_t)tail * esz, esz); + res->len = tail; + return NULL; +} + +/* Append one row; a NULL cell lands as the column's null (a NULL slot + * for a boxed column), mirroring the legacy insert arm. */ +static ray_t* upsert_append_row(ray_t** slots, int64_t ncols, ray_t** cells) { + for (int64_t c = 0; c < ncols; c++) { + ray_t* col = slots[c]; + ray_t* cell = cells[c]; + ray_t* res; + if (col->type == RAY_LIST) { + res = ray_list_append(col, cell); + } else if (!cell) { + ray_t* na = ray_typed_null(-col->type); + res = append_atom_to_col(col, na); + ray_release(na); + } else { + res = append_atom_to_col(col, cell); + } + if (RAY_IS_ERR(res)) return res; + slots[c] = res; + } + return NULL; +} + +static void upsert_rollback_appends(ray_t** slots, int64_t ncols, int64_t nrows0) { + for (int64_t c = 0; c < ncols; c++) { + ray_t* col = slots[c]; + if (col->type == RAY_LIST) { + ray_t** cells = (ray_t**)ray_data(col); + for (int64_t k = nrows0; k < col->len; k++) + if (cells[k]) ray_release(cells[k]); + } + col->len = nrows0; + } +} + +/* One-pass upsert. `kci[nk]` are the key column positions. The + * payload is either `src_cols` (ncols collections-or-NULL, each `m` + * rows) or, when src_cols is NULL, `atoms` (ncols atoms-or-NULL, m==1). + * `tbl` is borrowed. Returns the result (the binding's symbol, or a + * fresh table) or an error, and sets *handled; returns NULL with + * *handled false when a gate misses and the legacy arms should run. */ +static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, + const int64_t* kci, int64_t nk, + ray_t** src_cols, ray_t** atoms, int64_t m, + bool* handled) { + *handled = false; + int64_t ncols = ray_table_ncols(tbl); + int64_t nrows0 = ray_table_nrows(tbl); + if (ncols <= 0 || m <= 0) return NULL; + + for (int64_t c = 0; c < ncols; c++) + if (!upsert_col_ok(ray_table_get_col_idx(tbl, c))) return NULL; + for (int64_t k = 0; k < nk; k++) { + ray_t* kc = ray_table_get_col_idx(tbl, kci[k]); + if (!upsert_key_type_ok(kc->type)) return NULL; + } + + /* Sole-owner check, as in insert's in-place path: the binding holds + * one reference and the caller the other; the column list and every + * column must be unshared so a write cannot be observed elsewhere. */ + bool inplace = inplace_sym >= 0 && tbl->rc == 2 && tbl->mmod == 0 && + !(tbl->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)); + ray_t* live_cols = NULL; + if (inplace) { + live_cols = ((ray_t**)ray_data(tbl))[1]; + if (!live_cols || live_cols->rc != 1 || live_cols->len != ncols) + inplace = false; + } + for (int64_t c = 0; inplace && c < ncols; c++) + if (((ray_t**)ray_data(live_cols))[c]->rc != 1) inplace = false; + + /* Materialize the payload cells once: cells[r*ncols + c], with a + * parallel ownership byte for atoms allocated out of typed vectors. */ + ray_t* cells_hdr = NULL; ray_t* owned_hdr = NULL; + size_t ncell = (size_t)m * (size_t)ncols; + ray_t** cells = (ray_t**)scratch_alloc(&cells_hdr, ncell * sizeof(ray_t*)); + uint8_t* owned = cells ? (uint8_t*)scratch_alloc(&owned_hdr, ncell) : NULL; + if (!cells || !owned) { + if (cells_hdr) scratch_free(cells_hdr); + if (owned_hdr) scratch_free(owned_hdr); + *handled = true; + return ray_error("oom", NULL); + } + memset(cells, 0, ncell * sizeof(ray_t*)); + memset(owned, 0, ncell); + + ray_t* err = NULL; + upsert_map_t map = { NULL, NULL, 0 }; + ray_t* work = NULL; + + if (src_cols) { + for (int64_t c = 0; c < ncols && !err; c++) { + ray_t* sc = src_cols[c]; + if (!sc) continue; + if (!is_collection(sc)) { + err = ray_error("type", "upsert: multi-row value for column %lld must be a list or vector, got %s", + (long long)c, ray_type_name(sc->type)); + break; + } + if (ray_len(sc) != m) { + err = ray_error("length", "upsert: column %lld has %lld values, key has %lld", + (long long)c, (long long)ray_len(sc), (long long)m); + break; + } + for (int64_t r = 0; r < m; r++) { + int alloc = 0; + ray_t* e = collection_elem(sc, r, &alloc); + if (e && RAY_IS_ERR(e)) { err = e; break; } + cells[(size_t)r * ncols + c] = e; + owned[(size_t)r * ncols + c] = (uint8_t)(alloc && e); + } + } + } else { + for (int64_t c = 0; c < ncols; c++) cells[c] = atoms[c]; + } + + /* Type-check every cell before writing anything. */ + for (int64_t r = 0; r < m && !err; r++) { + ray_t** rc = cells + (size_t)r * ncols; + for (int64_t k = 0; k < nk && !err; k++) { + ray_t* kc = ray_table_get_col_idx(tbl, kci[k]); + ray_t* a = rc[kci[k]]; + if (!a) { + err = ray_error("domain", "upsert: key value missing"); + } else if (kc->type == RAY_STR && a->type != -RAY_STR) { + err = ray_error("type", "upsert: key column is str but key value is %s", ray_type_name(a->type)); + } else if (kc->type == RAY_SYM && a->type != -RAY_SYM) { + err = ray_error("type", "upsert: key column is sym but key value is %s", ray_type_name(a->type)); + } + } + for (int64_t c = 0; c < ncols && !err; c++) + if (rc[c]) err = upsert_cell_fits(ray_table_get_col_idx(tbl, c)->type, rc[c]); + } + + /* Work table: the live columns, or a private copy of them. */ + ray_t** slots = NULL; + if (!err) { + if (inplace) { + slots = (ray_t**)ray_data(live_cols); + } else { + work = ray_table_new(ncols); + if (RAY_IS_ERR(work)) { err = work; work = NULL; } + for (int64_t c = 0; c < ncols && !err; c++) { + ray_t* orig = ray_table_get_col_idx(tbl, c); + ray_retain(orig); + ray_t* cp = ray_cow(orig); + if (!cp || RAY_IS_ERR(cp)) { + ray_release(orig); /* ray_cow leaves the input alive on failure */ + err = cp ? cp : ray_error("oom", NULL); + break; + } + work = ray_table_add_col(work, ray_table_col_name(tbl, c), cp); + ray_release(cp); + if (RAY_IS_ERR(work)) { err = work; work = NULL; } + } + if (!err) slots = (ray_t**)ray_data(((ray_t**)ray_data(work))[1]); + } + } + + if (!err && m > 1) { + if (!upsert_map_init(&map, nrows0 + m)) err = ray_error("oom", NULL); + for (int64_t r = 0; r < nrows0 && !err; r++) + upsert_map_put(&map, upsert_hash_row(slots, kci, nk, r), r); + } + + int64_t nrows = nrows0; + for (int64_t r = 0; r < m && !err; r++) { + ray_t** rc = cells + (size_t)r * ncols; + uint64_t h = 0; + int64_t hit; + if (map.slot) { + h = upsert_hash_atoms(slots, kci, nk, rc); + hit = upsert_map_find(&map, h, slots, kci, nk, rc); + } else { + hit = upsert_find_row(slots, kci, nk, rc, nrows); + } + if (hit >= 0) { + for (int64_t c = 0; c < ncols && !err; c++) { + if (!rc[c]) continue; /* partial payload: keep */ + bool is_key = false; + for (int64_t k = 0; k < nk; k++) if (kci[k] == c) { is_key = true; break; } + if (is_key) continue; /* matched: already equal */ + err = upsert_write_cell(slots, c, hit, rc[c]); + } + } else { + err = upsert_append_row(slots, ncols, rc); + if (!err) { + if (map.slot) upsert_map_put(&map, h, nrows); + nrows++; + } + } + } + + if (err && slots) upsert_rollback_appends(slots, ncols, nrows0); + + if (map.hdr) scratch_free(map.hdr); + for (size_t i = 0; i < ncell; i++) if (owned[i] && cells[i]) ray_release(cells[i]); + scratch_free(cells_hdr); + scratch_free(owned_hdr); + + *handled = true; + if (err) { + if (work) ray_release(work); + return err; + } + if (inplace) return ray_sym(inplace_sym); + if (inplace_sym >= 0) { + ray_env_set(inplace_sym, work); + ray_release(work); + return ray_sym(inplace_sym); + } + return work; +} + ray_t* ray_upsert_fn(ray_t** args, int64_t n) { return ray_upsert(args, n); } @@ -14403,19 +15282,47 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { return ray_error("value", NULL); } } + /* Key column positions in the target. Every key name is a + * payload column, and each payload column matches exactly one + * target column (checked above), so each resolves uniquely. */ + ray_t* tkci_hdr = NULL; + int64_t* tkci = (int64_t*)scratch_alloc(&tkci_hdr, (size_t)n_key * sizeof(int64_t)); + if (!tkci) { scratch_free(keynames_hdr); ray_release(tbl); ray_release(key_sym); ray_release(row); return ray_error("oom", NULL); } + for (int64_t k = 0; k < n_key; k++) { + tkci[k] = -1; + for (int64_t c = 0; c < ncols; c++) + if (ray_table_col_name(tbl, c) == key_names[k]) { tkci[k] = c; break; } + if (tkci[k] < 0) { + scratch_free(tkci_hdr); scratch_free(keynames_hdr); + ray_release(tbl); ray_release(key_sym); ray_release(row); + return ray_error("domain", "upsert: key column not found in target table"); + } + } scratch_free(keynames_hdr); /* Gather source columns in target order (now guaranteed 1-to-1). */ - ray_t* src_cols[64]; - for (int64_t c = 0; c < ncols && c < 64; c++) { + ray_t* srcs_hdr = NULL; + ray_t** src_cols = (ray_t**)scratch_alloc(&srcs_hdr, (size_t)ncols * sizeof(ray_t*)); + if (!src_cols) { scratch_free(tkci_hdr); ray_release(tbl); ray_release(key_sym); ray_release(row); return ray_error("oom", NULL); } + for (int64_t c = 0; c < ncols; c++) { int64_t cn = ray_table_col_name(tbl, c); src_cols[c] = ray_table_get_col(row, cn); } + + bool fast_handled = false; + ray_t* fast = upsert_apply(tbl, inplace_sym, tkci, n_key, src_cols, NULL, src_nrows, &fast_handled); + scratch_free(tkci_hdr); + if (fast_handled) { + scratch_free(srcs_hdr); + ray_release(tbl); ray_release(key_sym); ray_release(row); + return fast; + } + ray_t* cur_tbl = tbl; ray_retain(cur_tbl); for (int64_t r = 0; r < src_nrows; r++) { ray_t* single = ray_alloc(ncols * sizeof(ray_t*)); - if (!single) { ray_release(cur_tbl); ray_release(tbl); ray_release(key_sym); ray_release(row); return ray_error("oom", NULL); } + if (!single) { scratch_free(srcs_hdr); ray_release(cur_tbl); ray_release(tbl); ray_release(key_sym); ray_release(row); return ray_error("oom", NULL); } single->type = RAY_LIST; single->len = ncols; ray_t** sr = (ray_t**)ray_data(single); @@ -14430,9 +15337,10 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { single->len = 0; ray_free(single); ray_release(cur_tbl); - if (RAY_IS_ERR(new_tbl)) { ray_release(tbl); ray_release(key_sym); ray_release(row); return new_tbl; } + if (RAY_IS_ERR(new_tbl)) { scratch_free(srcs_hdr); ray_release(tbl); ray_release(key_sym); ray_release(row); return new_tbl; } cur_tbl = new_tbl; } + scratch_free(srcs_hdr); ray_release(tbl); ray_release(key_sym); ray_release(row); @@ -14537,6 +15445,19 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { /* Multi-row upsert: if row values are vectors, iterate row-by-row */ ray_t* key_elem = row_elems[key_col_indices[0]]; + if (!key_elem) { scratch_free(kci_hdr); ray_release(tbl); ray_release(key_sym); ray_release(row); return ray_error("domain", "upsert: key value missing"); } + { + bool multi = ray_is_vec(key_elem) || key_elem->type == RAY_LIST; + bool fast_handled = false; + ray_t* fast = multi + ? upsert_apply(tbl, inplace_sym, key_col_indices, n_key_cols, row_elems, NULL, ray_len(key_elem), &fast_handled) + : upsert_apply(tbl, inplace_sym, key_col_indices, n_key_cols, NULL, row_elems, 1, &fast_handled); + if (fast_handled) { + scratch_free(kci_hdr); + ray_release(tbl); ray_release(key_sym); ray_release(row); + return fast; + } + } if (ray_is_vec(key_elem) || key_elem->type == RAY_LIST) { int64_t new_nrows = ray_len(key_elem); ray_t* cur_tbl = tbl; diff --git a/src/ops/system.c b/src/ops/system.c index c3fe450ef..5a876732b 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -38,6 +38,7 @@ #include "store/splay.h" #include "store/part.h" #include "core/ipc.h" +#include "core/mcast.h" #include "core/poll.h" #include "core/timer.h" @@ -1468,7 +1469,9 @@ ray_t* ray_hopen_fn(ray_t** args, int64_t n) { int64_t h = ray_ipc_connect(host, (uint16_t)port, us_ptr, pw_ptr, timeout_ms); if (h == -2) return ray_error("access", "server requires authentication"); if (h == -3) return ray_error("access", "authentication failed"); + if (h == -4) return ray_error("io", "wire version mismatch: %s:%d", host, port); if (h == -5) return ray_error("io", "connection timed out: %s:%d", host, port); + if (h == -6) return ray_error("io", "connect failed: %s:%d: %s", host, port, strerror(errno)); if (h < 0) return ray_error("io", "connection refused: %s:%d", host, port); return make_i64(h); @@ -1519,3 +1522,27 @@ ray_t* ray_ipc_handle_fn(ray_t** args, int64_t n) { (void)args; (void)n; return make_i64(ray_ipc_current_handle()); } + +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 (!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* ray_mc_unsub_fn(ray_t* topic) { + if (!ray_ipc_context_poll()) + return ray_error("domain", ".mc.unsub requires a poll IPC context"); + return ray_mcast_unsub(ray_ipc_active_poll(), ray_ipc_current_handle(), topic); +} + +ray_t* ray_mc_pub_fn(ray_t* topic, ray_t* payload) { + return ray_mcast_pub(ray_ipc_active_poll(), topic, payload); +} + +ray_t* ray_mc_stats_fn(ray_t** args, int64_t n) { + (void)args; + if (n != 0) return ray_error("domain", ".mc.stats takes no arguments"); + return ray_mcast_stats(ray_ipc_active_poll()); +} diff --git a/src/store/serde.c b/src/store/serde.c index cc74e706c..f6676f3be 100644 --- a/src/store/serde.c +++ b/src/store/serde.c @@ -131,6 +131,26 @@ static int64_t ser_schema_names(uint8_t* buf, ray_t* schema) { return c; } +/* Builtins inline only the first 13 bytes of their name (ray_fn_name), so a + * longer registered name cannot be read off the object. Recover the full name + * from the global-env binding; the returned pointer is borrowed from the sym + * table (stable through the read-only serialization phase — no release). Sets + * *nlen to the byte length and returns the bytes. Falls back to the object's + * inline name for anything not found as a registered global builtin. */ +static const char* serde_builtin_name(ray_t* obj, size_t* nlen) { + int64_t sym = ray_env_builtin_sym(obj); + if (sym >= 0) { + ray_t* s = ray_sym_str(sym); + if (s && !RAY_IS_ERR(s)) { + *nlen = ray_str_len(s); + return ray_str_ptr(s); + } + } + const char* name = ray_fn_name(obj); + *nlen = strlen(name); + return name; +} + /* -------------------------------------------------------------------------- * ray_serde_size — calculate serialized size (excluding IPC header) * -------------------------------------------------------------------------- */ @@ -239,9 +259,12 @@ int64_t ray_serde_size(ray_t* obj) { case RAY_UNARY: case RAY_BINARY: case RAY_VARY: { - /* Serialize by name (null-terminated string in aux) */ - const char* name = ray_fn_name(obj); - size_t nlen = strlen(name); if (nlen > 15) nlen = 15; + /* Serialize by name: type + full NUL-terminated name. The name comes + * from the env binding (serde_builtin_name), not the object's 13-byte + * inline copy, so a long builtin name round-trips instead of resolving + * to a truncated, non-existent name on decode. */ + size_t nlen; + (void)serde_builtin_name(obj, &nlen); return 1 + (int64_t)nlen + 1; /* type + name + null terminator */ } case RAY_ERROR: @@ -487,9 +510,12 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { case RAY_UNARY: case RAY_BINARY: case RAY_VARY: { - /* Serialize builtin by name (null-terminated) */ - const char* name = ray_fn_name(obj); - size_t nlen = strlen(name); if (nlen > 15) nlen = 15; + /* Serialize builtin by its full NUL-terminated name, recovered from the + * env binding (the object only inlines 13 bytes). ray_serde_size + * reserves 1 + nlen + 1 the same way; the decoder resolves the name in + * the global environment. */ + size_t nlen; + const char* name = serde_builtin_name(obj, &nlen); memcpy(buf, name, nlen); buf[nlen] = 0; return 1 + (int64_t)nlen + 1; diff --git a/test/main.c b/test/main.c index b82a72769..583f2ab38 100644 --- a/test/main.c +++ b/test/main.c @@ -141,6 +141,7 @@ extern const test_entry_t lftj_entries[]; extern const test_entry_t list_entries[]; extern const test_entry_t meta_entries[]; extern const test_entry_t morsel_entries[]; +extern const test_entry_t mcast_entries[]; extern const test_entry_t numparse_entries[]; extern const test_entry_t opt_entries[]; extern const test_entry_t partition_exec_entries[]; @@ -191,6 +192,7 @@ static const test_entry_t* const compiled_groups[] = { journal_entries, lang_entries, link_entries, lftj_entries, list_entries, meta_entries, morsel_entries, + mcast_entries, numparse_entries, opt_entries, partition_exec_entries, pipe_entries, platform_entries, pool_entries, progress_entries, diff --git a/test/rfl/agg/count_distinct_extras.rfl b/test/rfl/agg/count_distinct_extras.rfl index 272479b8e..466cdf152 100644 --- a/test/rfl/agg/count_distinct_extras.rfl +++ b/test/rfl/agg/count_distinct_extras.rfl @@ -96,55 +96,57 @@ ;; 51000 groups in unspecified order, so pin g==0 with where:. (at (at (select {n: (count (distinct v)) from: Tcd-f64 by: g where: (== g 0)}) 'n) 0) -- 1 -;; ────────── has_nulls fallback (group.c L1204-1227) ────────── +;; ────────── null-bearing columns through ray_count_distinct_per_group ── ;; Build a null-bearing I64 column: cast a small null-bearing prefix ;; and concat with a plain-I64 tail. `[1 0Nl 2 0Nl 3]` is an I64 vec ;; with HAS_NULLS attr (see distinct.rfl L22); concat preserves the ;; null bitmap into the merged vector (see distinct.rfl L37-40). (set Vnull (concat [0Nl 1 0Nl 2 0Nl] (% (til (- Nser 5)) 7))) (set Tcd-null (table [g v] (list Ggrp Vnull))) -;; 11) has_nulls arm with I64 data — exercises the read_col_i64 fallback -;; at L1223 inside the has_nulls block (esz==8, in_type==RAY_I64). -;; CONVENTION: the per-group count(distinct) has_nulls kernel SKIPS -;; nulls (does NOT count a null as a distinct value). Probed here: -;; group 0 = {0Nl, 0}; were the null counted this would be 2, but the -;; kernel returns 1 (the lone non-null 0). This differs from the -;; scalar `(count (distinct [1 0N ...]))` which keeps one null -;; (null/distinct.rfl:3) — a per-group-vs-scalar behavior difference. +;; 11) an I64 column carrying nulls, through the typed esz==8 loop. There +;; used to be a separate has-nulls arm here going through read_col_i64 +;; per row; it computed the same keys, so it is gone. +;; A null is one distinct value, the same rule the scalar +;; `(count (distinct [1 0N ...]))` follows (null/distinct.rfl). The +;; per-group kernels used to skip nulls instead, and this block pinned +;; that as a deliberate per-group-vs-scalar difference — but it made the +;; answer depend on the core count and on the group count, since the +;; three kernels disagreed among themselves. One rule now. ;; ;; Layout: Vnull[i] = (i-5)%7 for i>=5, prefix [null 1 null 2 null]. ;; Group k<9000 = rows {k, k+51000}; partner value = k%7 (because ;; (k+51000-5)%7 = k%7). Per-group distinct values: -;; g0 row0=null, partner 0%7=0 → {0} = 1 +;; g0 row0=null, partner 0%7=0 → {null,0} = 2 ;; g1 row1=1, partner 1%7=1 → {1} = 1 -;; g2 row2=null, partner 2%7=2 → {2} = 1 +;; g2 row2=null, partner 2%7=2 → {null,2} = 2 ;; g3 row3=2, partner 3%7=3 → {2,3} = 2 -;; g4 row4=null, partner 4%7=4 → {4} = 1 +;; g4 row4=null, partner 4%7=4 → {null,4} = 2 ;; g5..g8999 (bulk 2-row): (k-5)%7 vs k%7 differ → 2 each (8995*2) ;; g9000..g50999 (1-row): (k-5)%7 → 1 each (42000*1) -;; Sum = 6 + 8995*2 + 42000 = 59996. +;; Sum = 9 + 8995*2 + 42000 = 59999. (set Rcdnull (select {n: (count (distinct v)) from: Tcd-null by: g})) (count Rcdnull) -- 51000 -;; Group 0 = {0Nl, 0} → null skipped → 1 distinct. -(at (at Rcdnull 'n) 0) -- 1 +;; Group 0 = {0Nl, 0} → the null is one value → 2 distinct. +(at (at Rcdnull 'n) 0) -- 2 ;; Group 3 = {2, 3} → no null, two values → 2 distinct. (at (at Rcdnull 'n) 3) -- 2 ;; Group 5 = bulk 2-row {(0)%7=0, 5%7=5} → 2 distinct. (at (at Rcdnull 'n) 5) -- 2 -(sum (at Rcdnull 'n)) -- 59996 +(sum (at Rcdnull 'n)) -- 59999 ;; 12) has_nulls arm with F64 data — exercises the F64 NaN / -0.0 ;; normalisation inside the has_nulls block. Same group structure -;; and same null-skip convention; 0Nf (NaN) rows are skipped. +;; and the same rule; every NaN payload folds to one canonical NaN, so a +;; null counts once here too. (set Vnullf (as 'F64 Vnull)) (set Tcd-fnull (table [g v] (list Ggrp Vnullf))) (set Rcdfnull (select {n: (count (distinct v)) from: Tcd-fnull by: g})) (count Rcdfnull) -- 51000 -;; Group 0 = {0Nf, 0.0} → NaN skipped → 1 distinct. -(at (at Rcdfnull 'n) 0) -- 1 +;; Group 0 = {0Nf, 0.0} → the null is one value → 2 distinct. +(at (at Rcdfnull 'n) 0) -- 2 ;; Group 3 = {2.0, 3.0} → 2 distinct. (at (at Rcdfnull 'n) 3) -- 2 -(sum (at Rcdfnull 'n)) -- 59996 +(sum (at Rcdfnull 'n)) -- 59999 ;; ────────── count_distinct_per_group_groups (eval-fallback) ────────── ;; STR or LIST by-key flips use_eval_group=1 at query.c:4498, which diff --git a/test/rfl/group/null_str_key_rehash.rfl b/test/rfl/group/null_str_key_rehash.rfl new file mode 100644 index 000000000..08b235ada --- /dev/null +++ b/test/rfl/group/null_str_key_rehash.rfl @@ -0,0 +1,67 @@ +;; null_str_key_rehash.rfl — a null key must hash identically wherever the +;; hash is computed (#466). +;; +;; Regression: every phase-1 key builder stores a null key as a zeroed slot +;; plus a null-mask bit and hashes it as ray_hash_i64(0). hash_keys_inline +;; (rehash / lookup / partial-table merge) read the stored slot back BY TYPE: +;; a zeroed inline-STR descriptor hashed as the empty string and a zeroed +;; wide (GUID) slot as source row 0. After the table's first growth the +;; rehashed group sat under a hash no probe computes, so every later row +;; with the same keys opened a fresh group — one group per null-keyed row, +;; silently wrong aggregates, no error. + +;; ─── the reported shape: long STR keys beside an all-null STR column ──── +(set G1 "c0f1979caacf5d1021f8cc8fbd5a67aea133f9851c4100e1f6939baf939901cf") +(set KA "5e3ceb01534e06c927d06cb03492aafca56057df49937395af4f6ad7a4763c4c") +(set KB "971723c2bc887c9f7b67f8f399a05944f31a6c7f9010ee9232d8a80478c4f37a") +(set PAD (take (enlist "") 3)) +(set R (table [g1 g2 g3 v] (list (list G1 G1 G1) (list KA KB KB) PAD [1 2 3]))) +(set Q (select {n: (count v) from: R by: [g1 g2 g3]})) +(count Q) -- 2 +(sum (at Q 'n)) -- 3 +(max (at Q 'n)) -- 2 +;; the same rows in the other order fold too +(set Rb (table [g1 g2 g3 v] (list (list G1 G1 G1) (list KB KB KA) PAD [2 3 1]))) +(count (select {n: (count v) from: Rb by: [g1 g2 g3]})) -- 2 +;; two keys, null column second +(count (select {n: (count v) from: R by: [g2 g3]})) -- 2 +;; the null column alone, and without the null column — unchanged +(count (select {n: (count v) from: R by: g3})) -- 1 +(count (select {n: (count v) from: R by: [g1 g2]})) -- 2 + +;; ─── short (SSO) strings behave the same ───────────────────────────── +(set Rs (table [g1 g2 g3 v] (list (list "x" "x" "x") (list "a" "b" "b") PAD [1 2 3]))) +(count (select {n: (count v) from: Rs by: [g1 g2 g3]})) -- 2 + +;; ─── sorted keys and a copying select take the same path ───────────── +(count (select {n: (count v) from: (xasc R [g1 g2 g3]) by: [g1 g2 g3]})) -- 2 +(set Rc (select {g1: g1 g2: g2 g3: g3 v: v from: R})) +(count (select {n: (count v) from: Rc by: [g1 g2 g3]})) -- 2 + +;; ─── one null among real values in the second key ──────────────────── +(set Rm (table [g1 g2 v] (list (list "x" "x" "x" "x") (list "" "" "x" "") [1 2 3 4]))) +(set Qm (select {n: (count v) from: Rm by: [g1 g2]})) +(count Qm) -- 2 +(max (at Qm 'n)) -- 3 + +;; ─── many rows: several rehashes between equal null-keyed rows ─────── +;; 20000 rows over 300 distinct (I64, STR) pairs; the STR key is null on +;; every third row so a third of the groups carry a null key. +(set N 20000) +(set Kn (as 'I64 (% (til N) 300))) +(set Ks (take (list "" "a" "b") N)) +(set Rbig (table [k s v] (list Kn Ks (as 'I64 (til N))))) +(set Qbig (select {n: (count v) from: Rbig by: [k s]})) +(count Qbig) -- 300 +(sum (at Qbig 'n)) -- 20000 +(min (at Qbig 'n)) -- 66 +(max (at Qbig 'n)) -- 67 +;; STR key first, so it is key 0 in the layout +(count (select {n: (count v) from: Rbig by: [s k]})) -- 300 + +;; ─── a null GUID key beside a STR key (wide slot must not read as row 0) ─ +(set Gg (as 'GUID (list "00000000-0000-0000-0000-000000000001" "" "" "00000000-0000-0000-0000-000000000001"))) +(set Rg (table [g s v] (list Gg (list "a" "a" "a" "a") [1 2 3 4]))) +(set Qg (select {n: (count v) from: Rg by: [g s]})) +(count Qg) -- 2 +(max (at Qg 'n)) -- 2 diff --git a/test/rfl/io/csv_rayfall_temporal.rfl b/test/rfl/io/csv_rayfall_temporal.rfl new file mode 100644 index 000000000..5163c1923 --- /dev/null +++ b/test/rfl/io/csv_rayfall_temporal.rfl @@ -0,0 +1,9 @@ +;; CSV type inference must recognize Rayfall's display temporal forms. +;; These are the forms users see when DATE/TIMESTAMP values are printed. +(.sys.exec "printf 'd,ts\n2024.01.02,2024.01.02D01:02:03.004005006\n' > rf_test_csv_rayfall_temporal.csv") -- 0 +(set T (.csv.read "rf_test_csv_rayfall_temporal.csv")) +(type (at T 'd)) -- 'DATE +(type (at T 'ts)) -- 'TIMESTAMP +(at (at T 'd) 0) -- 2024.01.02 +(at (at T 'ts) 0) -- 2024.01.02D01:02:03.004005006 +(.sys.exec "rm -f rf_test_csv_rayfall_temporal.csv") -- 0 diff --git a/test/rfl/null/distinct.rfl b/test/rfl/null/distinct.rfl index 529f54062..1623dd893 100644 --- a/test/rfl/null/distinct.rfl +++ b/test/rfl/null/distinct.rfl @@ -6,3 +6,72 @@ ;; Idempotent under nulls (count (distinct (distinct [1 0N 2 0N]))) -- (count (distinct [1 0N 2 0N])) + +;; The same rule has to survive a grouped count, and specifically the parallel +;; per-group kernel — a different implementation from the ungrouped builtin +;; above and from the serial fallback beside it. It is selected only when the +;; pool has at least two workers and the query has at least four groups, so the +;; shapes below are built to reach it: the suite runs with TEST_CORES=2, and +;; each has four groups. The kernel used to drop nulls rather than fold them, +;; which made the answer depend on the core count. +;; +;; group 0 -> 10, 0N, 10 = {10, null} = 2 +;; group 1 -> 0N, 20, 20 = {20, null} = 2 +;; group 2 -> 20, 0N, 30 = {20, 30, null} = 3 +;; group 3 -> 30, 30, 0N = {30, null} = 2 +(set _dn (table [k v] (list [0 1 2 3 0 1 2 3 0 1 2 3] [10 0N 20 30 0N 20 0N 30 10 20 30 0N]))) +(at (select {d: (count (distinct v)) by: k from: _dn}) 'd) -- [2 2 3 2] + +;; A group whose every value is null still holds one distinct value, not zero. +(set _dz (table [k v] (list [0 1 2 3 0 1 2 3] [0N 1 2 3 0N 1 2 3]))) +(at (select {d: (count (distinct v)) by: k from: _dz}) 'd) -- [1 1 1 1] + +;; F64 nulls take a separate arm of the same kernel. +(set _df (table [k v] (list [0 1 2 3 0 1 2 3] [1.5 0Nf 2.5 3.5 0Nf 0Nf 2.5 0Nf]))) +(at (select {d: (count (distinct v)) by: k from: _df}) 'd) -- [2 1 1 2] + +;; A SYM null is the empty symbol. It was already counted, through the flag the +;; table keeps for the literal 0 — pinned so the two arms stay in step. +(set _ds (table [k v] (list [0 1 2 3 0 1 2 3] (as 'SYM ["a" "" "b" "c" "" "" "b" "c"])))) +(at (select {d: (count (distinct v)) by: k from: _ds}) 'd) -- [2 1 1 1] + +;; Above 50000 groups the query leaves the kernel above entirely and routes to +;; ray_count_distinct_per_group in group.c. That one has two loops of its own, +;; and which runs depends on the ROW count, not the group count: below 200000 +;; rows the serial one, at or above it the partitioned one. Both sides of both +;; boundaries must answer alike, or the count depends on the shape of the data. +;; +;; These two stay under 200000 rows on purpose — they pin the serial loop. 120002 rows alternating {10, null}: every group holds one +;; value and one null, so every group counts 2. +(set _dg (table [k v] (list (% (til 120002) 60001) (at [10 0N] (% (til 120002) 2))))) +(distinct (at (select {d: (count (distinct v)) by: k from: _dg}) 'd)) -- [2] + +;; The same data below the boundary, through the other kernel. +(set _dl (table [k v] (list (% (til 120002) 40001) (at [10 0N] (% (til 120002) 2))))) +(distinct (at (select {d: (count (distinct v)) by: k from: _dl}) 'd)) -- [2] + +;; A column that is entirely null still holds one distinct value per group on +;; both sides — it read 0 above the boundary and 1 below it. +(set _dan (table [k v] (list (% (til 120002) 60001) (take [0N] 120002)))) +(distinct (at (select {d: (count (distinct v)) by: k from: _dan}) 'd)) -- [1] + +;; And these cross 200000 rows as well, so the partitioned loop runs: its +;; histogram and scatter passes skipped nulls too, and a regression there would +;; otherwise pass the whole suite. 60001 groups keeps it above the group +;; boundary; 240002 rows puts it above the row one. +(set _dp (table [g v] (list (% (til 240002) 60001) (at [10 0N] (% (til 240002) 2))))) +(distinct (at (select {d: (count (distinct v)) by: g from: _dp}) 'd)) -- [2] + +;; An entirely null column through the same path: one distinct value per group, +;; not zero. +(set _dpn (table [g v] (list (% (til 240002) 60001) (take [0N] 240002)))) +(distinct (at (select {d: (count (distinct v)) by: g from: _dpn}) 'd)) -- [1] + +;; F64 takes a separate arm of the partitioned kernel — its null is a NaN, and +;; every NaN payload has to fold to the same key for the count to be one. +(set _dpf (table [g v] (list (% (til 240002) 60001) (at [10.5 0Nf] (% (til 240002) 2))))) +(distinct (at (select {d: (count (distinct v)) by: g from: _dpf}) 'd)) -- [2] + +;; A SYM null is the empty symbol, which is a legal key rather than a sentinel. +(set _dps (table [g v] (list (% (til 240002) 60001) (at (as 'SYM ["a" ""]) (% (til 240002) 2))))) +(distinct (at (select {d: (count (distinct v)) by: g from: _dps}) 'd)) -- [2] diff --git a/test/rfl/ops/pivot_coverage.rfl b/test/rfl/ops/pivot_coverage.rfl index a3e27fdc3..2378d0142 100644 --- a/test/rfl/ops/pivot_coverage.rfl +++ b/test/rfl/ops/pivot_coverage.rfl @@ -663,3 +663,144 @@ RDatedead -- [2024.01.01 2023.01.02] (count RTimedead) -- 2 (type RTimedead) -- 'TIME RTimedead -- [09:30:00.000 11:00:00.000] + +;; ── (if …) and the two arms of exec_if ──────────────────────────────── +;; exec_if picks between an eager arm, which fills every row from the node's +;; static out_type, and a selected arm, which touches only the rows each +;; branch supplies and reports the type those rows actually have. The eager +;; arm is a candidate only for a non-STR output whose branches are both +;; trivial column reads, and it is taken only when workers exist — so the two +;; arms have to agree wherever both could apply, or an expression answers +;; differently depending on the core count. +;; +;; NOTE on shape: both branches below are deliberately NON-trivial (a nested +;; if), which keeps the eager arm out of the picture at any core count. With +;; bare column scans the eager arm answers under the default TEST_CORES=2 and +;; the selected arm is never reached, so such a case passes with or without +;; the fix — it tests nothing. +;; +;; An `if` selects a value, it does not compute one, so two branches of one +;; temporal type yield that type. The selected arm used to re-derive it with +;; a promotion ladder of its own, which folded a temporal down to the integer +;; it is stored as — right for arithmetic, since the difference of two +;; timestamps is a span, wrong for a choice between two of them. +(set TIF (table [x d tm ts] (list [true false true] (as 'DATE [1 2 3]) (as 'TIME [10 20 30]) (as 'TIMESTAMP [100 200 300])))) +(type (at (select {r: (if x ts (if x ts ts)) from: TIF}) 'r)) -- 'TIMESTAMP +(type (at (select {r: (if x d (if x d d)) from: TIF}) 'r)) -- 'DATE +(type (at (select {r: (if x tm (if x tm tm)) from: TIF}) 'r)) -- 'TIME +;; values are untouched by the type rule +(as 'I64 (at (select {r: (if x ts (if x ts ts)) from: TIF}) 'r)) -- [100 200 300] +;; branches of DIFFERENT temporal types have no shared meaning — still widened +(type (at (select {r: (if x d (if x ts ts)) from: TIF}) 'r)) -- 'I64 + +;; A branch that supplies no rows must not change the answer either. With an +;; all-true condition the else branch is empty, and the selected arm used to +;; adopt the surviving branch's raw type — so these read TIMESTAMP/DATE +;; serially and I64/F64 under workers. Both branches are trivial here, so +;; the eager arm could handle them: the answer must be its answer. +(set TAT (table [x ts d] (list [true true true] (as 'TIMESTAMP [100 200 300]) (as 'DATE [1 2 3])))) +(type (at (select {r: (if x ts 5) from: TAT}) 'r)) -- 'I64 +(type (at (select {r: (if x ts 5.5) from: TAT}) 'r)) -- 'F64 +(type (at (select {r: (if x d ts) from: TAT}) 'r)) -- 'I64 + +;; ── a null branch value must still read as a null ─────────────────────── +;; An atom null IS the sentinel value and carries no attribute of its own, so +;; nothing marked the output as null-bearing. `nil?` still answered true — it +;; reads the value — but the vector formatter reads the attribute, so the +;; sentinel came out as an ordinary date. Rendering is what has to be pinned; +;; a value comparison passes either way and would test nothing. +;; +;; Both arms of exec_if had to learn this: the trivial branches put the eager +;; arm in charge under workers, the nested-if forms force the selected one. +(set TN (table [x d ts] (list [true false true] (as 'DATE [1 2 3]) (as 'TIMESTAMP [100 200 300])))) +(format "%s" (at (select {r: (if x d 0Nd) from: TN}) 'r)) -- "[2000.01.02 0Nd 2000.01.04]s" +(format "%s" (at (select {r: (if x (if x d d) 0Nd) from: TN}) 'r)) -- "[2000.01.02 0Nd 2000.01.04]s" +(nil? (at (at (select {r: (if x ts 0Np) from: TN}) 'r) 1)) -- true +;; the non-null rows are untouched +(as 'I64 (at (at (select {r: (if x d 0Nd) from: TN}) 'r) 0)) -- 1 + +;; ── an empty branch, whichever one it is ─────────────────────────────── +;; The narrowing looks at whichever branch survived, so an all-false condition +;; has to be pinned alongside the all-true one: either side can be the empty +;; one. +(set TT (table [x ts] (list [true true true] (as 'TIMESTAMP [100 200 300])))) +(set TFa (table [x ts] (list [false false false] (as 'TIMESTAMP [100 200 300])))) +(type (at (select {r: (if x ts 5) from: TT}) 'r)) -- 'I64 +(type (at (select {r: (if x 5 ts) from: TFa}) 'r)) -- 'I64 +(type (at (select {r: (if x ts 5.5) from: TT}) 'r)) -- 'F64 +(type (at (select {r: (if x 5.5 ts) from: TFa}) 'r)) -- 'F64 + +;; ── a column of a parted table carries a wrapped type ────────────────── +;; graph.c's promotion ladder knows nothing about the wrapper, so a wrapped +;; type matched none of its cases and fell through to RAY_BOOL: the result +;; claimed B8 and every value was truncated to a byte. It hit any type, not +;; only temporal ones, and printing the B8 column aborted under UBSan. +;; +;; NOTE on shape: the condition must be a literal. With a computed predicate +;; the branch types arrive already unwrapped and the case passes on the parent +;; commit, testing nothing. Two partitions are needed for the same reason. +(.sys.exec "rm -rf /tmp/rfl_ifpt") +(.db.splayed.set "/tmp/rfl_ifpt/2024.01.01/t/" (table [ts v] (list (as 'TIMESTAMP [100 200 300]) [1 2 3]))) +(.db.splayed.set "/tmp/rfl_ifpt/2024.01.02/t/" (table [ts v] (list (as 'TIMESTAMP [45 145 245]) [4 5 6]))) +(set PT (.db.parted.get "/tmp/rfl_ifpt/" 't)) +(type (at (select {r: (if true v v) from: PT}) 'r)) -- 'I64 +(type (at (select {r: (if true ts ts) from: PT}) 'r)) -- 'TIMESTAMP +(at (select {r: (if true v v) from: PT}) 'r) -- [1 2 3 4 5 6] +(as 'I64 (at (select {r: (if true ts ts) from: PT}) 'r)) -- [100 200 300 45 145 245] +(.sys.exec "rm -rf /tmp/rfl_ifpt") + +;; ── the declared type is a floor, not the answer ─────────────────────── +;; The graph promotes the declared types of the branch EXPRESSIONS, but +;; arithmetic widens past them: (* a a) over an I32 column is computed and +;; stored as I64. Reporting the declared I32 does not relabel the result, it +;; truncates every value. Non-trivial branches keep the eager arm away, so +;; this is the selected arm's own answer. +(set TW (table [c a b] (list [true false true] (as 'I32 [100000 100000 100000]) (as 'I16 [30000 30000 30000])))) +(at (select {r: (if c (* a a) (* a a)) from: TW}) 'r) -- [10000000000 10000000000 10000000000] +(at (select {r: (if c (+ b b) (+ b b)) from: TW}) 'r) -- [60000 60000 60000] + +;; ── narrowing belongs to the branch that supplied nothing ────────────── +;; Two temporal branches promote to I64 because of the pair, not because of +;; either one, so an empty branch must not hand the answer to the survivor: +;; the nested form and the plain form are the same expression. +(set TD (table [x d ts] (list [true true true] (as 'DATE [1 2 3]) (as 'TIMESTAMP [100 200 300])))) +(type (at (select {r: (if x (if x d d) ts) from: TD}) 'r)) -- 'I64 +(type (at (select {r: (if x d ts) from: TD}) 'r)) -- 'I64 + +;; ── a null atom stays null when the width changes ────────────────────── +;; 0N is the I64 sentinel; converting it into an F64 column as a number gave +;; -9.22e18. Both spellings have to land as the F64 null. +(set TZ (table [c f] (list [true false true] [1.5 2.5 3.5]))) +(format "%s" (at (select {r: (if c f 0N) from: TZ}) 'r)) -- "[1.5 0Nf 3.5]s" +(format "%s" (at (select {r: (if c f 0Nf) from: TZ}) 'r)) -- "[1.5 0Nf 3.5]s" + +;; ── a scalar condition applies to every row ──────────────────────────── +;; It has one cell and the eager fill indexed it per row, reading past it, so +;; the result mixed both branches. The selected arm declines a scalar +;; condition outright, which is why only the eager one was affected. +(at (select {r: (if false f 1.0) from: TZ}) 'r) -- [1.0 1.0 1.0] +(at (select {r: (if true f 1.0) from: TZ}) 'r) -- [1.5 2.5 3.5] + + +;; ── the null symbol needs no width handling ─────────────────────────── +;; SYM has no typed null and no `0Ns` literal (parse.c): the empty symbol `'` +;; IS the null, in-band, so it survives the branch as a SYM instead of being +;; widened the way the out-of-band integer and float sentinels had to be. +(set TN (table [c s] (list [true false true] (as 'SYM ["a" "b" "c"])))) +(type (at (select {r: (if c s ') from: TN}) 'r)) -- 'SYM +(format "%s" (at (select {r: (if c s ') from: TN}) 'r)) -- "[a null c]s" + +;; ── a parted column answers as the same data flattened does ──────────── +;; Its type is carried in a wrapper that no promotion ladder knows, so the +;; wrapper is stripped at the scan node: arithmetic through an if kept its +;; width, and the SYM override in ray_if — which compares against a bare +;; RAY_SYM — fires again instead of leaking dictionary ids. +(.sys.exec "rm -rf /tmp/rfl_ifpw") +(.db.splayed.set "/tmp/rfl_ifpw/2024.01.01/t/" (table [ts v sy] (list (as 'TIMESTAMP [100 200 300]) [1 2 3] (as 'SYM ["a" "b" "c"])))) +(.db.splayed.set "/tmp/rfl_ifpw/2024.01.02/t/" (table [ts v sy] (list (as 'TIMESTAMP [45 145 245]) [4 5 6] (as 'SYM ["d" "e" "f"])))) +(set PW (.db.parted.get "/tmp/rfl_ifpw/" 't)) +(set FW (table [ts v sy] (list (as 'TIMESTAMP [100 200 300 45 145 245]) [1 2 3 4 5 6] (as 'SYM ["a" "b" "c" "d" "e" "f"])))) +(at (select {r: (if (> v 2) sy sy) from: PW}) 'r) -- (at (select {r: (if (> v 2) sy sy) from: FW}) 'r) +(at (select {r: (if (> v 2) (+ v v) (+ v v)) from: PW}) 'r) -- [2 4 6 8 10 12] +(type (at (select {r: (if (> v 0) v 1.5) from: PW}) 'r)) -- (type (at (select {r: (if (> v 0) v 1.5) from: FW}) 'r)) +(.sys.exec "rm -rf /tmp/rfl_ifpw") diff --git a/test/rfl/store/parted_insert_symstr_nulls.rfl b/test/rfl/store/parted_insert_symstr_nulls.rfl new file mode 100644 index 000000000..347403d3b --- /dev/null +++ b/test/rfl/store/parted_insert_symstr_nulls.rfl @@ -0,0 +1,56 @@ +;; parted_insert_symstr_nulls.rfl — a live `insert` into a parted table must +;; accept SYM/STR segments carrying HAS_NULLS (#465). +;; +;; Regression: since the empty symbol / empty string became their types' +;; canonical nulls, the store carries RAY_ATTR_HAS_NULLS for them across a +;; save, so every mapped partition holding one blank SYM/STR cell arrives with +;; the bit set. parted_segment_attrs_valid (src/ops/query.c) allowed the bit +;; only for the numeric, temporal and GUID bases, so the whole insert was +;; refused as `corrupt: insert: segment metadata/length/type mismatch`. +;; The null is in-band — the payload is what it always was — so nothing about +;; the append changes. +(.sys.exec "rm -rf /tmp/rfl_pins_nulls") + +;; ─── 1. same process: first batch into a NEW day holds a blank ─────────── +;; one clean day on disk so the parted root exists +(.db.splayed.set "/tmp/rfl_pins_nulls/a/2026.01.01/t/" (table ['d 's 'x 'n] (list [2026.01.01] (as 'SYM ['a]) (list "p") [1]))) +(.db.parted.fill "/tmp/rfl_pins_nulls/a/") +(set W (.db.parted.get "/tmp/rfl_pins_nulls/a/" 't)) +;; first live batch into a new day, blank STR — materialises the partition, +;; which maps back with HAS_NULLS set +(insert 'W 2026.01.02 (table ['d 's 'x 'n] (list [2026.01.02] (as 'SYM ['a]) (list "") [2]))) +;; the day's second batch (no blanks at all) was the one refused +(insert 'W 2026.01.02 (table ['d 's 'x 'n] (list [2026.01.02] (as 'SYM ['b]) (list "r") [3]))) +;; and a blank SYM in a later batch +(insert 'W 2026.01.02 (table ['d 's 'x 'n] (list [2026.01.02] (as 'SYM [']) (list "q") [4]))) +(insert 'W 2026.01.02 (table ['d 's 'x 'n] (list [2026.01.02] (as 'SYM ['c]) (list "s") [5]))) +(count (select {from: W})) -- 5 +(sum (at (select {from: W}) 'n)) -- 15 +(count (select {from: W where: (== x "")})) -- 1 +(count (select {from: W where: (nil? s)})) -- 1 +(first (at (select {from: W where: (== n 3)}) 'x)) -- "r" + +;; ─── 2. across a reopen: a day saved with a blank, then inserted into ───── +(.db.splayed.set "/tmp/rfl_pins_nulls/sym/2026.01.01/t/" (table ['d 's 'x 'n] (list [2026.01.01 2026.01.01] (as 'SYM ['a ']) (list "p" "q") [1 2]))) +(.db.parted.fill "/tmp/rfl_pins_nulls/sym/") +(set Vs (.db.parted.get "/tmp/rfl_pins_nulls/sym/" 't)) +(insert 'Vs 2026.01.01 (table ['d 's 'x 'n] (list [2026.01.01] (as 'SYM ['z]) (list "zz") [9]))) +(count (select {from: Vs})) -- 3 +(sum (at (select {from: Vs}) 'n)) -- 12 +(count (select {from: Vs where: (nil? s)})) -- 1 + +(.db.splayed.set "/tmp/rfl_pins_nulls/str/2026.01.01/t/" (table ['d 's 'x 'n] (list [2026.01.01 2026.01.01] (as 'SYM ['a 'b]) (list "p" "") [1 2]))) +(.db.parted.fill "/tmp/rfl_pins_nulls/str/") +(set Vx (.db.parted.get "/tmp/rfl_pins_nulls/str/" 't)) +(insert 'Vx 2026.01.01 (table ['d 's 'x 'n] (list [2026.01.01] (as 'SYM ['z]) (list "zz") [9]))) +(count (select {from: Vx})) -- 3 +(sum (at (select {from: Vx}) 'n)) -- 12 +(count (select {from: Vx where: (== x "")})) -- 1 + +;; ─── 3. the numeric-null case that always worked stays accepted ─────────── +(.db.splayed.set "/tmp/rfl_pins_nulls/i64/2026.01.01/t/" (table ['d 's 'x 'n] (list [2026.01.01 2026.01.01] (as 'SYM ['a 'b]) (list "p" "q") [1 0Nl]))) +(.db.parted.fill "/tmp/rfl_pins_nulls/i64/") +(set Vn (.db.parted.get "/tmp/rfl_pins_nulls/i64/" 't)) +(insert 'Vn 2026.01.01 (table ['d 's 'x 'n] (list [2026.01.01] (as 'SYM ['z]) (list "zz") [9]))) +(count (select {from: Vn})) -- 3 +(.sys.exec "rm -rf /tmp/rfl_pins_nulls") -- 0 diff --git a/test/rfl/system/ipc_open_errors.rfl b/test/rfl/system/ipc_open_errors.rfl new file mode 100644 index 000000000..525da04fd --- /dev/null +++ b/test/rfl/system/ipc_open_errors.rfl @@ -0,0 +1,36 @@ +;; ipc_open_errors.rfl — `.ipc.open` names the failure it actually hit. +;; +;; Regression (#472): the connect and the wire handshake share one budget, +;; installed as SO_RCVTIMEO/SO_SNDTIMEO after the connect. A server that +;; is alive and listening but inside a long evaluation completes the TCP +;; handshake in the kernel and never answers the wire handshake, so the +;; recv timed out — and ray_ipc_connect returned the generic -1 that +;; `.ipc.open` printed as "connection refused", byte-identical to a dead +;; port that fails instantly. +;; +;; Server lifecycle is shell-driven like ipc_diff.rfl (by pid, so no pattern +;; can match the shell that runs it): a second rayforce +;; on port 19976 whose script sleeps, so the listener is up (-p binds +;; before the script runs) and nobody serves the handshake. +(.sys.exec "[ -f /tmp/rfl_ipc_deaf.pid ] && kill $(cat /tmp/rfl_ipc_deaf.pid) 2>/dev/null; rm -f /tmp/rfl_ipc_deaf.pid; true") +(.sys.exec "printf '(.sys.exec \"sleep 6\")\n' > /tmp/rfl_ipc_deaf.rfl") +(.sys.exec "./rayforce -p 19976 /tmp/rfl_ipc_deaf.rfl /dev/null 2>&1 & echo $! > /tmp/rfl_ipc_deaf.pid") +;; the kernel accepts into the backlog even though nobody answers +(.sys.exec "for i in $(seq 50); do bash -c '(echo > /dev/tcp/127.0.0.1/19976) 2>/dev/null' && exit 0; sleep 0.1; done; exit 1") -- 0 + +(.sys.exec "printf '(println (.ipc.open \"127.0.0.1:19976\" 300))\n' > /tmp/rfl_ipc_c1.rfl") +(.sys.exec "printf '(println (.ipc.open \"127.0.0.1:19975\" 300))\n' > /tmp/rfl_ipc_c2.rfl") +(.sys.exec "printf '(println (.ipc.open \"no-such-host.invalid:19975\" 300))\n' > /tmp/rfl_ipc_c3.rfl") + +;; listening but not answering: the budget expires, and the line says so +(.ipc.open "127.0.0.1:19976" 300) !- io +(.sys.exec "./rayforce /tmp/rfl_ipc_c1.rfl &1 | grep -q 'error: io: connection timed out: 127.0.0.1:19976'") -- 0 + +;; nothing bound: refused, and instantly +(.ipc.open "127.0.0.1:19975" 300) !- io +(.sys.exec "./rayforce /tmp/rfl_ipc_c2.rfl &1 | grep -q 'error: io: connection refused: 127.0.0.1:19975'") -- 0 + +;; a host that does not resolve is neither +(.sys.exec "./rayforce /tmp/rfl_ipc_c3.rfl &1 | grep -q 'error: io: connect failed: no-such-host.invalid:19975: '") -- 0 + +(.sys.exec "kill $(cat /tmp/rfl_ipc_deaf.pid) 2>/dev/null; for i in $(seq 50); do bash -c '(echo > /dev/tcp/127.0.0.1/19976) 2>/dev/null' || break; sleep 0.1; done; rm -f /tmp/rfl_ipc_deaf.pid /tmp/rfl_ipc_deaf.rfl /tmp/rfl_ipc_c1.rfl /tmp/rfl_ipc_c2.rfl /tmp/rfl_ipc_c3.rfl; true") diff --git a/test/rfl/system/listen_fatal.rfl b/test/rfl/system/listen_fatal.rfl new file mode 100644 index 000000000..7417ae327 --- /dev/null +++ b/test/rfl/system/listen_fatal.rfl @@ -0,0 +1,25 @@ +;; listen_fatal.rfl — a `-p` that cannot bind is fatal (#473). +;; +;; Regression: when ray_ipc_listen_at failed, main printed +;; `failed to listen on HOST:PORT: ...` and carried on — loaded the +;; script, ran it, and exited 0 (or kept running its timers with no +;; listener). A supervisor that asked for a server got a process that +;; was not one, with a zero exit code. +;; +;; A first rayforce holds port 19978 (server-only, started by pid so the +;; cleanup cannot match any shell); a second one asked for the same port +;; must exit non-zero without running its script. +(.sys.exec "[ -f /tmp/rfl_lf.pid ] && kill $(cat /tmp/rfl_lf.pid) 2>/dev/null; rm -f /tmp/rfl_lf.pid; true") +(.sys.exec "./rayforce -p 19978 /dev/null 2>&1 & echo $! > /tmp/rfl_lf.pid") +(.sys.exec "for i in $(seq 50); do bash -c '(echo > /dev/tcp/127.0.0.1/19978) 2>/dev/null' && exit 0; sleep 0.1; done; exit 1") -- 0 +(.sys.exec "printf '(println \"script ran\")\n' > /tmp/rfl_lf_plain.rfl") + +;; the second process must exit 1 with the diagnostic and without running +;; its script (.sys.exec returns the raw wait status, so fold to 0/1 here) +(.sys.exec "./rayforce -p 19978 /tmp/rfl_lf_plain.rfl /tmp/rfl_lf.out 2>&1; rc=$?; grep -q 'script ran' /tmp/rfl_lf.out && exit 99; grep -q 'failed to listen on \\*:19978' /tmp/rfl_lf.out || exit 98; [ $rc -eq 1 ]") -- 0 + +;; the same script on a free port still runs (the process then serves, so +;; it is started in the background and killed by pid once the marker shows) +(.sys.exec "./rayforce -p 19977 /tmp/rfl_lf_plain.rfl /tmp/rfl_lf2.out 2>&1 & p=$!; for i in $(seq 50); do grep -q 'script ran' /tmp/rfl_lf2.out && break; sleep 0.1; done; kill $p; grep -q 'script ran' /tmp/rfl_lf2.out") -- 0 + +(.sys.exec "kill $(cat /tmp/rfl_lf.pid) 2>/dev/null; rm -f /tmp/rfl_lf.pid /tmp/rfl_lf_plain.rfl /tmp/rfl_lf.out /tmp/rfl_lf2.out; true") diff --git a/test/rfl/system/serde.rfl b/test/rfl/system/serde.rfl index ba45f7d27..9f788d32b 100644 --- a/test/rfl/system/serde.rfl +++ b/test/rfl/system/serde.rfl @@ -33,3 +33,16 @@ ;; columns, dict keys-vs-values) is covered in test/test_store.c ;; (store/serde_container_count_mismatch), which builds frames via ;; sizeof(ray_ipc_header_t) rather than hard-coding the wire layout. + +;; ────────────── builtins serialize by their FULL name ────────────── +;; Regression: the encoder capped builtin names at 15 bytes, so a longer name +;; was written truncated and failed to resolve on decode. Both of these +;; registered builtins exceed 15 chars. Prove the round-trip BEHAVIOURALLY — +;; the decoded value is the real function, so calling it reaches that +;; function's own argument check; before the fix decode raised a 'name error. +;; A `-- .db.parted.tables` golden could NOT prove this: the formatter renders +;; a builtin through ray_fn_name's 13-byte inline copy, so both sides would +;; read `.db.parted.ta` and match on dev too. Pointer identity is asserted at +;; the C level in test_store.c (store/serde_builtin_name_roundtrip). +((de (ser .db.parted.tables)) 123) !- type +((de (ser .sys.querylog.enable)) 1 2) !- domain diff --git a/test/rfl/system/timer_overrun.rfl b/test/rfl/system/timer_overrun.rfl new file mode 100644 index 000000000..9bd677297 --- /dev/null +++ b/test/rfl/system/timer_overrun.rfl @@ -0,0 +1,23 @@ +;; timer_overrun.rfl — a periodic timer does not replay missed intervals, +;; and a failing callback's line carries the message (#474). +;; +;; Regression 1: a forever timer was re-pushed with exp += tic and the +;; firing loop ran while exp <= now, so a callback that overran by T +;; fired T/tic more times back-to-back before the poll loop served any +;; I/O. Regression 2: the error arm printed ray_fmt(err), which is the +;; code alone (`timer 0: error: io`), dropping the message. +;; +;; Timers only fire inside ray_poll_run, so both halves run a server +;; subprocess for a bounded time (backgrounded and killed by pid, since +;; macOS has no `timeout`) and read its output. A 100 ms timer +;; whose first fire sleeps 1 s: with replay the ten missed fires land +;; back-to-back (about 23 fires in 2.4 s); without, it resumes its cadence +;; after the sleep (about 13). Bounds are wide for slow builds. +(.sys.exec "printf '%s\n' '(set N 0)' '(.time.timer.set 100 0 (fn [t] (do (set N (+ N 1)) (if (== N 1) (.sys.exec \"sleep 1\") 0) (println \"fire\"))))' > /tmp/rfl_timer_ov.rfl") +(.sys.exec "./rayforce -p 19979 /tmp/rfl_timer_ov.rfl /tmp/rfl_timer_ov.out 2>/dev/null & p=$!; sleep 2.4; kill $p; wait $p 2>/dev/null; n=$(grep -c ^fire /tmp/rfl_timer_ov.out); [ \"$n\" -ge 4 ] && [ \"$n\" -le 17 ]") -- 0 + +;; the error line names the cause, not just the code +(.sys.exec "printf '%s\n' '(.time.timer.set 50 1 (fn [t] (.ipc.open \"127.0.0.1:19974\" 200)))' > /tmp/rfl_timer_err.rfl") +(.sys.exec "./rayforce -p 19979 /tmp/rfl_timer_err.rfl /tmp/rfl_timer_err.out 2>&1 & p=$!; sleep 1.5; kill $p; wait $p 2>/dev/null; grep -q 'timer 0: error: io: connection refused: 127.0.0.1:19974' /tmp/rfl_timer_err.out") -- 0 + +(.sys.exec "rm -f /tmp/rfl_timer_ov.rfl /tmp/rfl_timer_err.rfl /tmp/rfl_timer_ov.out /tmp/rfl_timer_err.out; true") diff --git a/test/rfl/table/update_where_inplace.rfl b/test/rfl/table/update_where_inplace.rfl new file mode 100644 index 000000000..cfd73a661 --- /dev/null +++ b/test/rfl/table/update_where_inplace.rfl @@ -0,0 +1,127 @@ +;; update_where_inplace.rfl — a where-update into a named table writes the +;; matched rows in place (#475 follow-up: update must carry realtime +;; ingestion like insert and upsert). +;; +;; Regression: ray_update with `where:` evaluated the predicate and every +;; update expression over the whole table, then rebuilt every updated column +;; cell by cell — O(rows present) per call with a large constant, and an +;; attached .idx.hash on the key column was never consulted. These lines pin +;; the observable semantics the in-place path must preserve. + +;; ── basic: only matched rows change, returns the symbol ── +(set b (table [px sz side] (list [10 20 30] [1 2 3] ['bid 'ask 'bid]))) +(update {from: 'b sz: 99 where: (== px 20)}) -- 'b +(at b 'sz) -- [1 99 3] +(at b 'side) -- [bid ask bid] +;; a shared owner sees the pre-update value +(set alias b) +(update {from: 'b sz: 0 where: (== px 10)}) +(at b 'sz) -- [0 99 3] +(at alias 'sz) -- [1 99 3] + +;; ── row-wise expressions over the matched rows, several columns at once ── +(set b (table [px sz side] (list [10 20 30 40] [1 2 3 4] ['bid 'ask 'bid 'ask]))) +(update {from: 'b sz: (+ sz 100) side: 'ask where: (> px 15)}) +(at b 'sz) -- [1 102 103 104] +(at b 'side) -- [bid ask ask ask] +(update {from: 'b sz: (* px 2) where: (== side 'bid)}) +(at b 'sz) -- [20 102 103 104] + +;; ── atoms and promotions ── +(set p (table [k i f s] (list [1 2 3] [10 20 30] [1.5 2.5 3.5] (list "a" "b" "c")))) +(update {from: 'p f: 7 where: (== k 2)}) +(at p 'f) -- [1.5 7.0 3.5] +(update {from: 'p i: 2.9 where: (== k 2)}) !- type +(update {from: 'p i: (* f 2) where: (== k 3)}) +(at p 'i) -- [10 20 7] +(update {from: 'p f: (+ i 1) where: (== k 1)}) +(at p 'f) -- [11.0 7.0 3.5] +(update {from: 'p s: "zz" where: (== k 3)}) +(at p 's) -- (list "a""b""zz") +(update {from: 'p s: 5 where: (== k 3)}) !- type +(at p 's) -- (list "a""b""zz") +(update {from: 'p i: 0Nl where: (== k 1)}) +(nil? (at (at p 'i) 0)) -- true +(sum (at p 'i)) -- 27 +(update {from: 'p f: 0Nf where: (== k 2)}) +(nil? (at (at p 'f) 1)) -- true +(sum (at p 'f)) -- 14.5 + +;; ── every row, no row ── +(set e (table [k v] (list [1 2 3] [1 2 3]))) +(update {from: 'e v: 0 where: (> k 0)}) +(at e 'v) -- [0 0 0] +(update {from: 'e v: 9 where: (== k 99)}) +(at e 'v) -- [0 0 0] +(count e) -- 3 + +;; ── errors leave the table untouched ── +(set e (table [k v] (list [1 2 3] [1 2 3]))) +(update {from: 'e v: 'sym where: (== k 2)}) !- type +(at e 'v) -- [1 2 3] + +;; ── non-elementwise expressions keep their whole-table meaning, and the +;; named and value spellings agree ── +(set a (table [k v] (list [1 2 3] [10 30 20]))) +(update {from: 'a v: (max v) where: (== k 1)}) +(at a 'v) -- [30 30 20] +(set d (table [k v] (list [1 2 1 2] [1 2 3 4]))) +(at (update {from: d v: (deltas v) where: (== k 2)}) 'v) -- [1 1 3 1] +(update {from: 'd v: (deltas v) where: (== k 2)}) +(at d 'v) -- [1 1 3 1] +(set off [10 20 30 40]) +(at (update {from: d v: (+ v off) where: (== k 1)}) 'v) -- [11 1 33 1] +(update {from: 'd v: (+ v off) where: (== k 1)}) +(at d 'v) -- [11 1 33 1] +(update {from: 'd v: (sums v) where: (== k 2)}) +(at d 'v) -- [11 12 33 46] +(update {from: 'd v: (if (> v 20) 9 0) where: (== k 1)}) +(at d 'v) -- [0 12 9 46] +(update {from: 'd v: (abs (- 0 v)) where: (== k 2)}) +(at d 'v) -- [0 12 9 46] + +;; ── boxed and sym columns ── +(set l (table [k v s] (list [1 2] (list [1 2] "x") ['a 'b]))) +(update {from: 'l v: 'tag where: (== k 2)}) +(at (at l 'v) 1) -- 'tag +(at (at l 'v) 0) -- [1 2] +(update {from: 'l s: 'c where: (== k 1)}) +(at l 's) -- [c b] + +;; ── hash-indexed key column: fast lookup, never a stale answer ── +(set h (table [px sz] (list (til 1000) (til 1000)))) +(set h (update {from: h px: (.idx.hash px)})) +(update {from: 'h sz: -1 where: (== px 500)}) +(at (at h 'sz) 500) -- -1 +(at (at h 'sz) 499) -- 499 +(update {from: 'h sz: (+ sz 1) where: (== px 500)}) +(at (at h 'sz) 500) -- 0 +(select {from: h where: (== px 500)}) -- (table [px sz] (list [500] [0])) +(update {from: 'h sz: 7 where: (== px 5000)}) +(sum (at h 'sz)) -- 499000 +;; the indexed column itself rewritten: an equality on it must see new data +(update {from: 'h px: 5000 where: (== sz 1)}) +(select {from: h where: (== px 5000)}) -- (table [px sz] (list [5000] [1])) +(select {from: h where: (== px 1)}) -- (table [px sz] (list (as 'I64 []) (as 'I64 []))) +;; sym key with an index +(set q (table [sym bid] (list ['aa 'bb 'cc] [1.0 2.0 3.0]))) +(set q (update {from: q sym: (.idx.hash sym)})) +(update {from: 'q bid: 2.5 where: (== sym 'bb)}) +(at q 'bid) -- [1.0 2.5 3.0] +(set want 'cc) +(update {from: 'q bid: 3.5 where: (== sym want)}) +(at q 'bid) -- [1.0 2.5 3.5] +(update {from: 'q bid: 9.0 where: (== sym 'zz)}) +(at q 'bid) -- [1.0 2.5 3.5] + +;; ── value-semantic from: returns a new table, binding untouched ── +(set v (table [k x] (list [1 2] [1 2]))) +(update {from: v x: 9 where: (== k 2)}) -- (table [k x] (list [1 2] [1 9])) +(at v 'x) -- [1 2] + +;; ── larger: correctness at a size where the scan matters ── +(set big (table [px sz] (list (til 20000) (til 20000)))) +(update {from: 'big sz: (- 0 sz) where: (>= px 19000)}) +(at (at big 'sz) 18999) -- 18999 +(at (at big 'sz) 19000) -- -19000 +(sum (at big 'sz)) -- 160991000 diff --git a/test/rfl/table/upsert_inplace.rfl b/test/rfl/table/upsert_inplace.rfl new file mode 100644 index 000000000..af0da2a8f --- /dev/null +++ b/test/rfl/table/upsert_inplace.rfl @@ -0,0 +1,156 @@ +;; upsert_inplace.rfl — upsert into a named table writes matched rows in +;; place and appends new keys, in one pass per call (#475). +;; +;; Regression: ray_upsert found the target row with a linear key scan and +;; rebuilt the whole table to write one cell — per payload row, so a +;; 1000-row batch was 1000 scans and 1000 rebuilds. The rewrite keeps +;; every observable result below; these lines pin the semantics the fast +;; path must preserve (update-vs-append, last-wins inside a batch, partial +;; payloads, nulls, boxed cells, str/sym/f64/i32 keys, value-semantic +;; targets, indexed keys, and error atomicity). + +;; ── single-row: update in place, append on miss, returns the symbol ── +(set b (table [px sz] (list [10 20 30] [1 2 3]))) +(upsert 'b 'px (list 20 99)) -- 'b +(at b 'sz) -- [1 99 3] +(upsert 'b 'px (list 40 4)) -- 'b +(at b 'px) -- [10 20 30 40] +(at b 'sz) -- [1 99 3 4] +;; a shared owner sees the pre-upsert value (copy-on-write, not aliasing) +(set alias b) +(upsert 'b 'px (list 10 111)) +(at b 'sz) -- [111 99 3 4] +(at alias 'sz) -- [1 99 3 4] + +;; ── batch (vector row): one pass, existing keys update, new keys append, +;; a key repeated inside the batch resolves to its LAST value ── +(set b (table [px sz] (list [10 20 30] [1 2 3]))) +(upsert 'b 'px (list [20 40 20 50 40] [200 400 201 500 401])) -- 'b +(at b 'px) -- [10 20 30 40 50] +(at b 'sz) -- [1 201 3 401 500] +(count b) -- 5 + +;; ── batch (table payload): partial columns keep the old values ── +(set b (table [px sz side] (list [10 20 30] [1 2 3] ['bid 'ask 'bid]))) +(upsert 'b 'px (table [px sz] (list [30 40] [33 44]))) -- 'b +(at b 'sz) -- [1 2 33 44] +(at b 'side) -- [bid ask bid '] +(upsert 'b 'px (table [side px] (list ['ask 'ask] [10 50]))) -- 'b +(at b 'side) -- [ask ask bid ' ask] +(at b 'sz) -- [1 2 33 44 0Nl] + +;; ── composite key (first N columns) ── +(set k (table [sym side px sz] (list ['a 'a 'b] ['bid 'ask 'bid] [1.0 2.0 1.0] [10 20 30]))) +(upsert 'k 3 (list ['a 'b 'b] ['ask 'bid 'ask] [2.0 1.0 5.0] [21 31 51])) -- 'k +(at k 'sz) -- [10 21 31 51] +(at k 'sym) -- [a a b b] +(upsert 'k 3 (list 'a 'bid 1.0 11)) +(at k 'sz) -- [11 21 31 51] + +;; ── key column types: str, sym, f64, i32, date, timestamp, bool ── +(set ts (table [k v] (list (list "x" "y") [1 2]))) +(upsert 'ts 'k (list "y" 22)) +(upsert 'ts 'k (list "z" 33)) +(at ts 'v) -- [1 22 33] +(at ts 'k) -- (list "x""y""z") +(upsert 'ts 'k (list (list "z" "w" "x") [333 44 111])) +(at ts 'v) -- [111 22 333 44] +(upsert 'ts 'k (list 5 1)) !- type +(set tsym (table [k v] (list ['a 'b] [1 2]))) +(upsert 'tsym 'k (list 'b 22)) +(upsert 'tsym 'k (list ['c 'a] [33 11])) +(at tsym 'v) -- [11 22 33] +(upsert 'tsym 'k (list 5 1)) !- type +(set tf (table [k v] (list [1.5 2.5] [1 2]))) +(upsert 'tf 'k (list 2.5 22)) +(upsert 'tf 'k (list 3 33)) +(at tf 'k) -- [1.5 2.5 3.0] +(at tf 'v) -- [1 22 33] +(set ti (table [k v] (list [1i 2i] [1 2]))) +(upsert 'ti 'k (list 2i 22)) +(upsert 'ti 'k (list [3i 1i] [33 11])) +(at ti 'k) -- [1i 2i 3i] +(at ti 'v) -- [11 22 33] +(set td (table [d v] (list [2024.01.01 2024.01.02] [1 2]))) +(upsert 'td 'd (list 2024.01.02 22)) +(upsert 'td 'd (list 2024.01.03 33)) +(at td 'v) -- [1 22 33] +(set tt (table [t v] (list [2000.01.01D00:00:00.000000001 2000.01.01D00:00:00.000000002] [1 2]))) +(upsert 'tt 't (list 2000.01.01D00:00:00.000000002 22)) +(at tt 'v) -- [1 22] +(set tb (table [k v] (list [true false] [1 2]))) +(upsert 'tb 'k (list false 22)) +(at tb 'v) -- [1 22] + +;; ── nulls: payload nulls land, untouched nulls survive, key nulls match ── +(set tn (table [k p q] (list [1 2 3] [1.5 0Nf 4.1] [10 0Nl 40]))) +(upsert 'tn 'k (list 3 0Nf 0Nl)) +(nil? (at (at tn 'p) 2)) -- true +(nil? (at (at tn 'q) 2)) -- true +(nil? (at (at tn 'q) 1)) -- true +(sum (at tn 'q)) -- 10 +(upsert 'tn 'k (list [1 4] [11.0 44.0] [11 44])) +(sum (at tn 'q)) -- 55 +(sum (at tn 'p)) -- 55.0 +(set tnk (table [k v] (list [1 0Nl 3] [1 2 3]))) +(upsert 'tnk 'k (list 0Nl 22)) +(at tnk 'v) -- [1 22 3] +(count tnk) -- 3 + +;; ── boxed (LIST) column: cell replaced in place, appended on miss ── +(set tl (table [k v] (list [1 2] (list [1 2] "s")))) +(upsert 'tl 'k (list 2 [7 8 9])) +(at (at tl 'v) 1) -- [7 8 9] +(upsert 'tl 'k (list 3 "t")) +(at (at tl 'v) 2) -- "t" +(count tl) -- 3 +(upsert 'tl 'k (list [1 4] (list "a" [0]))) +(at (at tl 'v) 0) -- "a" +(at (at tl 'v) 3) -- [0] +(count tl) -- 4 + +;; ── value-semantic target: returns a fresh table, binding untouched ── +(set v (table [px sz] (list [10 20 30] [1 2 3]))) +(upsert v 'px (list 20 99)) -- (table [px sz] (list [10 20 30] [1 99 3])) +(upsert v 'px (list [20 40] [99 4])) -- (table [px sz] (list [10 20 30 40] [1 99 3 4])) +(upsert v 'px (table [px sz] (list [20 40] [99 4]))) -- (table [px sz] (list [10 20 30 40] [1 99 3 4])) +(at v 'sz) -- [1 2 3] +(count v) -- 3 + +;; ── hash-indexed key column: lookups stay correct, index never stale ── +(set hb (table [px sz] (list (til 1000) (til 1000)))) +(set hb (update {from: hb px: (.idx.hash px)})) +(upsert 'hb 'px (list 500 -1)) +(at (at hb 'sz) 500) -- -1 +(count hb) -- 1000 +(upsert 'hb 'px (list [1000 7] [1000 -7])) +(count hb) -- 1001 +(at (at hb 'sz) 7) -- -7 +(select {from: hb where: (== px 1000)}) -- (table [px sz] (list [1000] [1000])) +(select {from: hb where: (== px 7)}) -- (table [px sz] (list [7] [-7])) +;; index on a NON-key column that gets overwritten must not answer stale +(set hv (table [px sz] (list [1 2 3] [10 20 30]))) +(set hv (update {from: hv sz: (.idx.hash sz)})) +(upsert 'hv 'px (list 2 99)) +(select {from: hv where: (== sz 20)}) -- (table [px sz] (list (as 'I64 []) (as 'I64 []))) +(select {from: hv where: (== sz 99)}) -- (table [px sz] (list [2] [99])) + +;; ── errors: a bad cell anywhere in the batch leaves the table untouched ── +(set e (table [px sz] (list [10 20 30] [1 2 3]))) +(upsert 'e 'px (list [20 40 50] (list 200 400 'oops))) !- type +(at e 'sz) -- [1 2 3] +(count e) -- 3 +(upsert 'e 'px (list [20 40] [200])) !- length +(at e 'sz) -- [1 2 3] +(upsert 'e 'nope (list 1 2)) !- domain +(upsert 'e 'px (list 1 2 3)) !- domain + +;; ── larger batch: correctness at a size where the scan matters ── +(set big (table [px sz] (list (til 5000) (til 5000)))) +(set batch (table [px sz] (list (+ 2500 (til 5000)) (- 0 (+ 2500 (til 5000)))))) +(upsert 'big 'px batch) +(count big) -- 7500 +(at (at big 'sz) 2499) -- 2499 +(at (at big 'sz) 2500) -- -2500 +(at (at big 'sz) 7499) -- -7499 +(sum (at big 'px)) -- 28121250 diff --git a/test/scenarios/mcast_real_e2e.rfl b/test/scenarios/mcast_real_e2e.rfl new file mode 100644 index 000000000..a75e04abb --- /dev/null +++ b/test/scenarios/mcast_real_e2e.rfl @@ -0,0 +1,77 @@ +;; Real multicast IPC end-to-end scenario. +;; +;; Run against a separately-started `./rayforce -p PORT` server: +;; ./rayforce test/scenarios/mcast_real_e2e.rfl -- --addr 127.0.0.1:PORT +;; +;; The client process opens two real IPC handles, subscribes both to one +;; topic, publishes through the server, and verifies server-pushed `upd` +;; callbacks in this client process. + +(set _mc_user_args (at (.sys.args) 'user)) +(set _mc_addr (get _mc_user_args 'addr)) + +(set _mc_count 0) +(set _mc_sum 0) +(set _mc_last_topic "") +(set _mc_last_seq 0) +(set _mc_last_payload 0) + +(set _mc_fail (fn [msg] + (do + (println "REAL_MCAST_E2E_FAIL %" msg) + (exit 1)))) + +(set _mc_assert (fn [ok msg] + (if ok 1 (_mc_fail msg)))) + +(set upd (fn [topic seq payload] + (do + (set _mc_count (+ _mc_count 1)) + (set _mc_sum (+ _mc_sum payload)) + (set _mc_last_topic topic) + (set _mc_last_seq seq) + (set _mc_last_payload payload) + null))) + +(_mc_assert (!= _mc_addr "") "missing --addr") + +(set h1 (.ipc.open _mc_addr 2000)) +(set h2 (.ipc.open _mc_addr 2000)) +(_mc_assert (>= h1 0) "h1 open") +(_mc_assert (>= h2 0) "h2 open") + +(.ipc.send h1 "(.mc.sub \"ticks\" null)") +(.ipc.send h2 "(.mc.sub \"ticks\" null)") + +(set st1 (.ipc.send h1 "(.mc.stats)")) +(_mc_assert (== (at st1 'topics) 1) "stats topics after sub") +(_mc_assert (== (at st1 'subscriptions) 2) "stats subscriptions after sub") + +(.ipc.send h1 "(.mc.pub \"ticks\" 10)") +(.ipc.send h2 "(+ 0 0)") + +(_mc_assert (== _mc_count 2) "two subscribers received first publish") +(_mc_assert (== _mc_sum 20) "first publish payload sum") +(_mc_assert (== _mc_last_topic "ticks") "first publish topic") +(_mc_assert (== _mc_last_payload 10) "first publish payload") + +(.ipc.send h2 "(.mc.unsub \"ticks\")") +(.ipc.send h1 "(.mc.pub \"ticks\" 7)") +(.ipc.send h2 "(+ 0 0)") + +(_mc_assert (== _mc_count 3) "one subscriber received second publish") +(_mc_assert (== _mc_sum 27) "second publish payload sum") +(_mc_assert (== _mc_last_topic "ticks") "second publish topic") +(_mc_assert (== _mc_last_payload 7) "second publish payload") + +(set st2 (.ipc.send h1 "(.mc.stats)")) +(_mc_assert (== (at st2 'topics) 1) "stats topics after unsub") +(_mc_assert (== (at st2 'subscriptions) 1) "stats subscriptions after unsub") +(_mc_assert (== (at st2 'published) 2) "stats published") +(_mc_assert (== (at st2 'delivered) 3) "stats delivered") +(_mc_assert (== (at st2 'dropped) 0) "stats dropped") + +(.ipc.close h2) +(.ipc.close h1) + +(println "REAL_MCAST_E2E_OK count=% sum=% topic=% payload=%" _mc_count _mc_sum _mc_last_topic _mc_last_payload) diff --git a/test/scenarios/mcast_real_negative.rfl b/test/scenarios/mcast_real_negative.rfl new file mode 100644 index 000000000..33455e5f1 --- /dev/null +++ b/test/scenarios/mcast_real_negative.rfl @@ -0,0 +1,46 @@ +;; Real multicast negative/API scenario against a running `./rayforce -p PORT`. +;; +;; ./rayforce test/scenarios/mcast_real_negative.rfl -- --addr 127.0.0.1:PORT + +(set _mc_addr (get (at (.sys.args) 'user) 'addr)) + +(set _mc_fail (fn [msg] + (do + (println "REAL_MCAST_NEGATIVE_FAIL %" msg) + (exit 1)))) + +(set _mc_assert (fn [ok msg] + (if ok 1 (_mc_fail msg)))) + +(_mc_assert (!= _mc_addr "") "missing --addr") + +(set h (.ipc.open _mc_addr 2000)) +(_mc_assert (>= h 0) "open") + +(set st0 (.ipc.send h "(.mc.stats)")) +(_mc_assert (== (at st0 'topics) 0) "initial topics") +(_mc_assert (== (at st0 'subscriptions) 0) "initial subscriptions") + +(set orphan_seq (.ipc.send h "(.mc.pub \"orphan\" 99)")) +(_mc_assert (== orphan_seq 0) "orphan seq") +(set st1 (.ipc.send h "(.mc.stats)")) +(_mc_assert (== (at st1 'topics) 0) "orphan topic not created") +(_mc_assert (== (at st1 'subscriptions) 0) "orphan subscriptions") +(_mc_assert (== (at st1 'published) (at st0 'published)) "orphan published") +(_mc_assert (== (at st1 'delivered) (at st0 'delivered)) "orphan delivered") +(_mc_assert (== (at st1 'dropped) (at st0 'dropped)) "orphan dropped") + +(set bad_filter (try (.ipc.send h "(.mc.sub \"bad-filter\" 1)") (fn [e] "nyi"))) +(_mc_assert (== bad_filter "nyi") "bad filter error") + +(set bad_topic (try (.ipc.send h "(.mc.pub [1 2] 1)") (fn [e] "type"))) +(_mc_assert (== bad_topic "type") "bad topic error") + +(.ipc.send h "(.mc.unsub \"missing\")") +(set st2 (.ipc.send h "(.mc.stats)")) +(_mc_assert (== (at st2 'published) (at st0 'published)) "unsub missing does not publish") +(_mc_assert (== (at st2 'subscriptions) 0) "unsub missing leaves subscriptions") + +(.ipc.close h) + +(println "REAL_MCAST_NEGATIVE_OK topics=% published=% delivered=%" (at st2 'topics) (at st2 'published) (at st2 'delivered)) diff --git a/test/scenarios/mcast_real_payloads.rfl b/test/scenarios/mcast_real_payloads.rfl new file mode 100644 index 000000000..234f99eea --- /dev/null +++ b/test/scenarios/mcast_real_payloads.rfl @@ -0,0 +1,68 @@ +;; Real multicast payload coverage against a running `./rayforce -p PORT`. +;; +;; ./rayforce test/scenarios/mcast_real_payloads.rfl -- --addr 127.0.0.1:PORT + +(set _mc_addr (get (at (.sys.args) 'user) 'addr)) + +(set _mc_fail (fn [msg] + (do + (println "REAL_MCAST_PAYLOADS_FAIL %" msg) + (exit 1)))) + +(set _mc_assert (fn [ok msg] + (if ok 1 (_mc_fail msg)))) + +(set _mc_count 0) +(set _mc_last_topic "") +(set _mc_last_seq 0) +(set _mc_last_payload null) + +(set upd (fn [topic seq payload] + (do + (set _mc_count (+ _mc_count 1)) + (set _mc_last_topic topic) + (set _mc_last_seq seq) + (set _mc_last_payload payload) + null))) + +(_mc_assert (!= _mc_addr "") "missing --addr") + +(set h (.ipc.open _mc_addr 2000)) +(_mc_assert (>= h 0) "open") + +(.ipc.send h "(.mc.sub 'payloads null)") +(set st0 (.ipc.send h "(.mc.stats)")) + +(.ipc.send h "(.mc.pub \"payloads\" 42)") +(_mc_assert (== _mc_count 1) "i64 delivered") +(_mc_assert (== _mc_last_topic "payloads") "i64 topic") +(_mc_assert (== _mc_last_seq 1) "i64 seq") +(_mc_assert (== _mc_last_payload 42) "i64 payload") + +(.ipc.send h "(.mc.pub 'payloads [1 2 3])") +(_mc_assert (== _mc_count 2) "vector delivered") +(_mc_assert (== _mc_last_seq 2) "vector seq") +(_mc_assert (== (sum _mc_last_payload) 6) "vector payload") + +(.ipc.send h "(.mc.pub \"payloads\" 'IBM)") +(_mc_assert (== _mc_count 3) "symbol delivered") +(_mc_assert (== _mc_last_seq 3) "symbol seq") +(_mc_assert (== (type _mc_last_payload) 'sym) "symbol payload type") +(_mc_assert (== _mc_last_payload 'IBM) "symbol payload") + +(.ipc.send h "(.mc.pub 'payloads (dict ['a 'b] (list 7 \"seven\")))") +(_mc_assert (== _mc_count 4) "dict delivered") +(_mc_assert (== _mc_last_seq 4) "dict seq") +(_mc_assert (== (at _mc_last_payload 'a) 7) "dict numeric payload") +(_mc_assert (== (at _mc_last_payload 'b) "seven") "dict string payload") + +(set st (.ipc.send h "(.mc.stats)")) +(_mc_assert (== (at st 'topics) 1) "stats topics") +(_mc_assert (== (at st 'subscriptions) 1) "stats subscriptions") +(_mc_assert (== (at st 'published) (+ (at st0 'published) 4)) "stats published") +(_mc_assert (== (at st 'delivered) (+ (at st0 'delivered) 4)) "stats delivered") +(_mc_assert (== (at st 'dropped) (at st0 'dropped)) "stats dropped") + +(.ipc.close h) + +(println "REAL_MCAST_PAYLOADS_OK count=% last=%" _mc_count (format "%" _mc_last_payload)) diff --git a/test/test_lang.c b/test/test_lang.c index c5dc22c30..2723e3fb9 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -6522,6 +6522,50 @@ static test_result_t test_eval_restricted_lambda_bypass(void) { PASS(); } +/* #41/#44/#46-#49: mutating or destroying server-side state over restricted + * (-U) IPC is privilege escalation. These builtins were registered without + * RAY_FN_RESTRICTED, so a restricted client could free graph/HNSW/Datalog + * handles, mutate a Datalog program, register a global rule, or persist WAL + * work that replays unrestricted. Each must now be refused with an `access` + * error; dummy handles are deliberate — the restricted gate fires at the + * invocation boundary, before the body validates its arguments. */ +static test_result_t test_eval_restricted_server_state_ops(void) { + /* alter can bypass the restricted `set` path and mutate a global vector. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access("(alter 'x set 0 1)")); + /* #44: global Datalog rule registration (a restricted special form). */ + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "(rule (__rf_restr_probe ?x) (?x :tag 1))")); + /* #49: mutate a Datalog program with a new EDB relation. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access("(dl-add-edb 0 'rel 0 2)")); + /* Stratification and evaluation rewrite a Datalog program in place. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access("(dl-stratify 0)")); + TEST_ASSERT_TRUE(restricted_expr_returns_access("(dl-eval 0)")); + /* #48: free a Datalog program handle. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access("(dl-free 0)")); + /* #46: free a server graph handle. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access("(.graph.free 0)")); + /* #47: free a server HNSW index handle. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access("(hnsw-free 0)")); + /* #41: persist WAL work that would replay outside restricted mode. */ + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "(.log.write (list 'set '__rf_restr_wal 1))")); + + /* The gate is scoped to restricted eval, not a blanket ban: in normal mode + * the same call reaches its body and fails for a non-access reason (a bogus + * handle), proving read-only mode is what changed, not the verb itself. */ + ray_t* normal = ray_eval_str("(dl-free 0)"); + TEST_ASSERT_NOT_NULL(normal); + if (RAY_IS_ERR(normal)) { + TEST_ASSERT(!ray_err_code(normal) || + strcmp(ray_err_code(normal), "access") != 0, + "dl-free must not be an access denial outside restricted mode"); + ray_error_free(normal); + } else { + ray_release(normal); + } + PASS(); +} + /* --- self-recursive lambda via recursion (tests op_calls path) --- */ static test_result_t test_eval_self_recursion_direct(void) { /* Direct recursion using named function — compiler may use op_calls */ @@ -9166,6 +9210,7 @@ const test_entry_t lang_entries[] = { { "lang/eval/cond_and_branches", test_eval_cond_and_branches, lang_setup, lang_teardown }, { "lang/eval/restricted_fn", test_eval_restricted_fn, lang_setup, lang_teardown }, { "lang/eval/restricted_lambda_bypass", test_eval_restricted_lambda_bypass, lang_setup, lang_teardown }, + { "lang/eval/restricted_server_state_ops", test_eval_restricted_server_state_ops, lang_setup, lang_teardown }, { "lang/eval/self_recursion_direct", test_eval_self_recursion_direct, lang_setup, lang_teardown }, { "lang/eval/nested_lambda_calls", test_eval_nested_lambda_calls, lang_setup, lang_teardown }, { "lang/eval/vm_empty_ret", test_eval_vm_empty_ret, lang_setup, lang_teardown }, diff --git a/test/test_mcast.c b/test/test_mcast.c new file mode 100644 index 000000000..0827b7b3b --- /dev/null +++ b/test/test_mcast.c @@ -0,0 +1,868 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + */ + +#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) +#define _POSIX_C_SOURCE 200809L +#endif +#define _GNU_SOURCE + +#include "test.h" +#include +#include "core/ipc.h" +#include "core/poll.h" +#include "core/runtime.h" +#include "core/sock.h" +#include "lang/env.h" +#include "table/dict.h" +#include "mem/sys.h" + +#include +#include +#include + +#ifndef RAY_OS_WINDOWS + #include + #include + #include +#endif + +extern ray_runtime_t* __RUNTIME; + +typedef struct { + ray_poll_t* poll; + ray_vm_t* vm; +} poll_thread_ctx_t; + +static poll_thread_ctx_t g_server_ctx; + +static void mcast_setup(void) { + ray_runtime_create(0, NULL); + ray_poll_t* p = ray_poll_create(); + if (p) ray_runtime_set_poll(p); +} + +static void mcast_teardown(void) { + ray_poll_t* p = (ray_poll_t*)ray_runtime_get_poll(); + if (p) { + ray_runtime_set_poll(NULL); + ray_poll_destroy(p); + } + ray_runtime_destroy(__RUNTIME); +} + +static void sleep_ms(long ms) { + struct timespec ts = { .tv_sec = ms / 1000, .tv_nsec = (ms % 1000) * 1000000L }; + nanosleep(&ts, NULL); +} + +static void pump_client(void) { + ray_poll_t* poll = (ray_poll_t*)ray_runtime_get_poll(); + if (!poll) return; + for (int i = 0; i < 20; i++) { + ray_poll_run_for(poll, 10); + sleep_ms(1); + } +} + +static bool pump_until_env_i64_at_least(const char* name, size_t len, + int64_t want, int rounds) { + ray_poll_t* poll = (ray_poll_t*)ray_runtime_get_poll(); + if (!poll) return false; + int64_t sym = ray_sym_intern(name, len); + for (int i = 0; i < rounds; i++) { + ray_t* v = ray_env_get(sym); + if (v && v->type == -RAY_I64 && v->i64 >= want) + return true; + ray_poll_run_for(poll, 10); + sleep_ms(1); + } + return false; +} + +static uint16_t get_listen_port(ray_sock_t fd) { + struct sockaddr_in addr; + socklen_t len = sizeof(addr); + if (getsockname(fd, (struct sockaddr*)&addr, &len) < 0) return 0; + return ntohs(addr.sin_port); +} + +static ray_vm_t* make_server_vm(void) { + ray_vm_t* vm = (ray_vm_t*)ray_sys_alloc(sizeof(ray_vm_t)); + if (!vm) return NULL; + ray_vm_init(vm, 77); + return vm; +} + +static void poll_server_thread_fn(void* arg) { + poll_thread_ctx_t* ctx = (poll_thread_ctx_t*)arg; + __VM = ctx->vm; + ray_poll_run(ctx->poll); +} + +static void poll_stop(ray_poll_t* poll, uint16_t port) { + ray_poll_exit(poll, 0); + ray_sock_t k = ray_sock_connect("127.0.0.1", port, 200); + if (k != RAY_INVALID_SOCK) ray_sock_close(k); +} + +static int64_t dict_i64(ray_t* d, const char* key) { + ray_t* k = ray_sym(ray_sym_intern(key, strlen(key))); + if (!k || RAY_IS_ERR(k)) return -1; + ray_t* v = ray_dict_get(d, k); + ray_release(k); + if (!v) return -1; + int64_t out = (v->type == -RAY_I64) ? v->i64 : -1; + ray_release(v); + return out; +} + +static test_result_t assert_ok(ray_t* x, const char* label) { + TEST_ASSERT_NOT_NULL(x); + if (RAY_IS_ERR(x)) { + const char* code = ray_err_code(x); + TEST_ASSERT_FMT(false, "%s returned error: %s", label, code ? code : "error"); + } + PASS(); +} + +static test_result_t start_server(ray_poll_t** poll_out, uint16_t* port_out, + ray_vm_t** vm_out, ray_thread_t* tid_out) { + ray_poll_t* poll = ray_poll_create(); + TEST_ASSERT_NOT_NULL(poll); + int64_t listener_id = ray_ipc_listen(poll, 0); + TEST_ASSERT((listener_id) >= (0), "listener_id >= 0"); + ray_selector_t* listener_sel = ray_poll_get(poll, listener_id); + TEST_ASSERT_NOT_NULL(listener_sel); + uint16_t port = get_listen_port((ray_sock_t)listener_sel->fd); + TEST_ASSERT((port) > (0), "port > 0"); + + ray_vm_t* vm = make_server_vm(); + TEST_ASSERT_NOT_NULL(vm); + g_server_ctx.poll = poll; + g_server_ctx.vm = vm; + ray_thread_create(tid_out, poll_server_thread_fn, &g_server_ctx); + sleep_ms(20); + + *poll_out = poll; + *port_out = port; + *vm_out = vm; + PASS(); +} + +static void stop_server(ray_poll_t* poll, uint16_t port, ray_vm_t* vm, ray_thread_t tid) { + poll_stop(poll, port); + ray_thread_join(tid); + ray_poll_destroy(poll); + ray_sys_free(vm); +} + +static test_result_t test_mcast_single_client_pub(void) { + ray_t* r = ray_eval_str( + "(set _mc_count 0)" + "(set _mc_last_seq 0)" + "(set _mc_last_topic \"\")" + "(set _mc_last_payload 0)" + "(set upd (fn [topic seq payload] " + " (set _mc_count (+ _mc_count 1))" + " (set _mc_last_seq seq)" + " (set _mc_last_topic topic)" + " (set _mc_last_payload payload)))"); + 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 h = ray_ipc_connect("127.0.0.1", port, NULL, NULL, 0); + TEST_ASSERT((h) >= (0), "client connected"); + + ray_t* sub_msg = ray_str("(.mc.sub \"ticks\" null)", strlen("(.mc.sub \"ticks\" null)")); + ray_t* sub = ray_ipc_send(h, sub_msg); + ray_release(sub_msg); + test_result_t ok = assert_ok(sub, "sub"); + if (ok.status != TEST_PASS) return ok; + TEST_ASSERT_EQ_I(sub->i64, 1); + ray_release(sub); + + ray_t* pub_msg = ray_str("(.mc.pub \"ticks\" 42)", strlen("(.mc.pub \"ticks\" 42)")); + ray_t* pub = ray_ipc_send(h, pub_msg); + ray_release(pub_msg); + ok = assert_ok(pub, "pub"); + if (ok.status != TEST_PASS) return ok; + TEST_ASSERT_EQ_I(pub->i64, 1); + ray_release(pub); + pump_client(); + + ray_t* c = ray_env_get(ray_sym_intern("_mc_count", 9)); + ray_t* s = ray_env_get(ray_sym_intern("_mc_last_seq", 12)); + ray_t* t = ray_env_get(ray_sym_intern("_mc_last_topic", 14)); + ray_t* p = ray_env_get(ray_sym_intern("_mc_last_payload", 16)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_NOT_NULL(s); + TEST_ASSERT_NOT_NULL(t); + TEST_ASSERT_NOT_NULL(p); + TEST_ASSERT_EQ_I(c->i64, 1); + TEST_ASSERT_EQ_I(s->i64, 1); + TEST_ASSERT_EQ_I(t->type, -RAY_STR); + TEST_ASSERT_STR_EQ(ray_str_ptr(t), "ticks"); + TEST_ASSERT_EQ_I(p->i64, 42); + + pub_msg = ray_str("(.mc.pub \"ticks\" 'IBM)", strlen("(.mc.pub \"ticks\" 'IBM)")); + pub = ray_ipc_send(h, pub_msg); + ray_release(pub_msg); + ok = assert_ok(pub, "pub symbol"); + if (ok.status != TEST_PASS) return ok; + TEST_ASSERT_EQ_I(pub->i64, 2); + ray_release(pub); + pump_client(); + + c = ray_env_get(ray_sym_intern("_mc_count", 9)); + s = ray_env_get(ray_sym_intern("_mc_last_seq", 12)); + p = ray_env_get(ray_sym_intern("_mc_last_payload", 16)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_NOT_NULL(s); + TEST_ASSERT_NOT_NULL(p); + TEST_ASSERT_EQ_I(c->i64, 2); + TEST_ASSERT_EQ_I(s->i64, 2); + TEST_ASSERT_EQ_I(p->type, -RAY_SYM); + ray_t* ps = ray_sym_str(p->i64); + TEST_ASSERT_NOT_NULL(ps); + TEST_ASSERT_STR_EQ(ray_str_ptr(ps), "IBM"); + + pub_msg = ray_str("(.mc.pub \"ticks\" (list (first ['+]) 20 22))", + strlen("(.mc.pub \"ticks\" (list (first ['+]) 20 22))")); + pub = ray_ipc_send(h, pub_msg); + ray_release(pub_msg); + ok = assert_ok(pub, "pub list payload"); + if (ok.status != TEST_PASS) return ok; + TEST_ASSERT_EQ_I(pub->i64, 3); + ray_release(pub); + pump_client(); + + c = ray_env_get(ray_sym_intern("_mc_count", 9)); + s = ray_env_get(ray_sym_intern("_mc_last_seq", 12)); + p = ray_env_get(ray_sym_intern("_mc_last_payload", 16)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_NOT_NULL(s); + TEST_ASSERT_NOT_NULL(p); + TEST_ASSERT_EQ_I(c->i64, 3); + TEST_ASSERT_EQ_I(s->i64, 3); + TEST_ASSERT_EQ_I(p->type, RAY_LIST); + TEST_ASSERT_EQ_I(ray_len(p), 3); + + ray_ipc_close(h); + stop_server(poll, port, vm, tid); + PASS(); +} + +static test_result_t test_mcast_two_clients_unsub_close_stats(void) { + ray_t* r = ray_eval_str( + "(set _mc_count 0)" + "(set upd (fn [topic seq payload] (set _mc_count (+ _mc_count payload))))"); + 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); + TEST_ASSERT((h1) >= (0), "h1 connected"); + TEST_ASSERT((h2) >= (0), "h2 connected"); + + ray_t* msg = ray_str("(.mc.sub \"ticks\" null)", strlen("(.mc.sub \"ticks\" null)")); + ray_t* r1 = ray_ipc_send(h1, msg); + ray_t* r2 = ray_ipc_send(h2, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(r1); TEST_ASSERT_FALSE(RAY_IS_ERR(r1)); ray_release(r1); + TEST_ASSERT_NOT_NULL(r2); TEST_ASSERT_FALSE(RAY_IS_ERR(r2)); ray_release(r2); + + ray_t* st_msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + ray_t* st = ray_ipc_send(h1, st_msg); + ray_release(st_msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "topics"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "subscriptions"), 2); + ray_release(st); + + ray_t* unsub_msg = ray_str("(.mc.unsub \"ticks\")", strlen("(.mc.unsub \"ticks\")")); + ray_t* ur = ray_ipc_send(h2, unsub_msg); + ray_release(unsub_msg); + TEST_ASSERT_NOT_NULL(ur); + TEST_ASSERT_FALSE(RAY_IS_ERR(ur)); + ray_release(ur); + + ray_t* pub_msg = ray_str("(.mc.pub \"ticks\" 5)", strlen("(.mc.pub \"ticks\" 5)")); + ray_t* pub = ray_ipc_send(h1, pub_msg); + ray_release(pub_msg); + TEST_ASSERT_NOT_NULL(pub); + TEST_ASSERT_FALSE(RAY_IS_ERR(pub)); + ray_release(pub); + pump_client(); + + ray_t* barrier_msg = ray_str("(+ 0 0)", strlen("(+ 0 0)")); + ray_t* barrier = ray_ipc_send(h2, barrier_msg); + ray_release(barrier_msg); + TEST_ASSERT_NOT_NULL(barrier); + TEST_ASSERT_FALSE(RAY_IS_ERR(barrier)); + ray_release(barrier); + + ray_t* c = ray_env_get(ray_sym_intern("_mc_count", 9)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_EQ_I(c->i64, 5); + + msg = ray_str("(.mc.sub \"ticks\" null)", strlen("(.mc.sub \"ticks\" null)")); + r2 = ray_ipc_send(h2, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(r2); TEST_ASSERT_FALSE(RAY_IS_ERR(r2)); ray_release(r2); + ray_ipc_close(h2); + sleep_ms(50); + + st_msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + st = ray_ipc_send(h1, st_msg); + ray_release(st_msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "subscriptions"), 1); + ray_release(st); + + ray_ipc_close(h1); + stop_server(poll, port, vm, tid); + PASS(); +} + +static test_result_t test_mcast_duplicate_sub_is_idempotent(void) { + ray_t* r = ray_eval_str( + "(set _mc_count 0)" + "(set upd (fn [topic seq payload] (set _mc_count (+ _mc_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 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 \"dup\" null)", strlen("(.mc.sub \"dup\" null)")); + ray_t* sub1 = ray_ipc_send(h, msg); + ray_t* sub2 = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub1); TEST_ASSERT_FALSE(RAY_IS_ERR(sub1)); ray_release(sub1); + TEST_ASSERT_NOT_NULL(sub2); TEST_ASSERT_FALSE(RAY_IS_ERR(sub2)); ray_release(sub2); + + msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + ray_t* st = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "topics"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "subscriptions"), 1); + ray_release(st); + + msg = ray_str("(.mc.pub \"dup\" 1)", strlen("(.mc.pub \"dup\" 1)")); + ray_t* pub = ray_ipc_send(h, 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); + pump_client(); + + ray_t* c = ray_env_get(ray_sym_intern("_mc_count", 9)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_EQ_I(c->i64, 1); + + ray_ipc_close(h); + stop_server(poll, port, vm, tid); + PASS(); +} + +static test_result_t test_mcast_multi_topic_routing(void) { + ray_t* r = ray_eval_str( + "(set _mc_count 0)" + "(set _mc_sum 0)" + "(set _mc_last_topic \"\")" + "(set upd (fn [topic seq payload] " + " (set _mc_count (+ _mc_count 1))" + " (set _mc_sum (+ _mc_sum payload))" + " (set _mc_last_topic topic)))"); + 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 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 'alpha null)", strlen("(.mc.sub 'alpha null)")); + ray_t* sub = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); ray_release(sub); + + msg = ray_str("(.mc.sub \"beta\" null)", strlen("(.mc.sub \"beta\" null)")); + sub = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); ray_release(sub); + + msg = ray_str("(.mc.pub \"alpha\" 11)", strlen("(.mc.pub \"alpha\" 11)")); + ray_t* pub = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(pub); TEST_ASSERT_FALSE(RAY_IS_ERR(pub)); ray_release(pub); + pump_client(); + + msg = ray_str("(.mc.pub 'beta 13)", strlen("(.mc.pub 'beta 13)")); + pub = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(pub); TEST_ASSERT_FALSE(RAY_IS_ERR(pub)); ray_release(pub); + pump_client(); + + ray_t* c = ray_env_get(ray_sym_intern("_mc_count", 9)); + ray_t* sum = ray_env_get(ray_sym_intern("_mc_sum", 7)); + ray_t* topic = ray_env_get(ray_sym_intern("_mc_last_topic", 14)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_NOT_NULL(sum); + TEST_ASSERT_NOT_NULL(topic); + TEST_ASSERT_EQ_I(c->i64, 2); + TEST_ASSERT_EQ_I(sum->i64, 24); + TEST_ASSERT_EQ_I(topic->type, -RAY_STR); + TEST_ASSERT_STR_EQ(ray_str_ptr(topic), "beta"); + + msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + ray_t* st = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "topics"), 2); + TEST_ASSERT_EQ_I(dict_i64(st, "subscriptions"), 2); + TEST_ASSERT_EQ_I(dict_i64(st, "published"), 2); + TEST_ASSERT_EQ_I(dict_i64(st, "delivered"), 2); + ray_release(st); + + ray_ipc_close(h); + stop_server(poll, port, vm, tid); + PASS(); +} + +static test_result_t test_mcast_no_subscribers_and_api_errors(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.pub \"orphan\" 99)", strlen("(.mc.pub \"orphan\" 99)")); + ray_t* pub = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(pub); + TEST_ASSERT_FALSE(RAY_IS_ERR(pub)); + TEST_ASSERT_EQ_I(pub->i64, 0); + ray_release(pub); + + msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + ray_t* st = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "topics"), 0); + TEST_ASSERT_EQ_I(dict_i64(st, "subscriptions"), 0); + TEST_ASSERT_EQ_I(dict_i64(st, "published"), 0); + TEST_ASSERT_EQ_I(dict_i64(st, "delivered"), 0); + TEST_ASSERT_EQ_I(dict_i64(st, "dropped"), 0); + ray_release(st); + + msg = ray_str("(.mc.sub \"bad-filter\" 1)", strlen("(.mc.sub \"bad-filter\" 1)")); + 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), "nyi"); + ray_error_free(err); + + msg = ray_str("(.mc.pub [1 2] 1)", strlen("(.mc.pub [1 2] 1)")); + 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), "type"); + 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; + uint16_t port; + ray_thread_t tid; + test_result_t sr = start_server(&poll, &port, &vm, &tid); + if (sr.status != TEST_PASS) return sr; + strcpy(poll->auth_secret, "secret"); + ray_poll_set_restricted(poll, true); + + int64_t h = ray_ipc_connect("127.0.0.1", port, "u", "secret", 0); + TEST_ASSERT((h) >= (0), "restricted client connected"); + + ray_t* msg = ray_str("(.mc.sub \"ticks\" null)", strlen("(.mc.sub \"ticks\" null)")); + ray_t* sub = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); + ray_release(sub); + + msg = ray_str("(.mc.pub \"ticks\" 1)", strlen("(.mc.pub \"ticks\" 1)")); + ray_t* pub = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(pub); + TEST_ASSERT_TRUE(RAY_IS_ERR(pub)); + TEST_ASSERT_STR_EQ(ray_err_code(pub), "access"); + ray_error_free(pub); + + ray_ipc_close(h); + stop_server(poll, port, vm, tid); + PASS(); +} + +static test_result_t test_mcast_requires_ipc_context_for_sub(void) { + ray_t* sub = ray_eval_str("(.mc.sub \"ticks\" null)"); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_TRUE(RAY_IS_ERR(sub)); + TEST_ASSERT_STR_EQ(ray_err_code(sub), "domain"); + ray_error_free(sub); + PASS(); +} + +static test_result_t test_mcast_large_payload_queues_until_writable(void) { + ray_t* r = ray_eval_str( + "(set _mc_count 0)" + "(set _mc_last_len 0)" + "(set _mc_open_count 0)" + "(set _mc_sub_handle -1)" + "(set upd (fn [topic seq payload] " + " (do " + " (set _mc_count (+ _mc_count 1))" + " (set _mc_last_len (count payload)))))" + "(set .ipc.on.open (fn [h] " + " (do " + " (set _mc_open_count (+ _mc_open_count 1))" + " (if (== _mc_open_count 1) (set _mc_sub_handle h) 0))))"); + 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); + TEST_ASSERT((h1) >= (0), "h1 connected"); + TEST_ASSERT((h2) >= (0), "h2 connected"); + + ray_t* msg = ray_str("(.mc.sub \"big\" null)", strlen("(.mc.sub \"big\" null)")); + ray_t* sub = ray_ipc_send(h1, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); + ray_release(sub); + +#ifndef RAY_OS_WINDOWS + ray_t* server_h = ray_env_get(ray_sym_intern("_mc_sub_handle", 14)); + TEST_ASSERT_NOT_NULL(server_h); + TEST_ASSERT_EQ_I(server_h->type, -RAY_I64); + ray_selector_t* server_sel = ray_poll_get(poll, server_h->i64); + TEST_ASSERT_NOT_NULL(server_sel); + int sndbuf = 4096; + setsockopt((ray_sock_t)server_sel->fd, SOL_SOCKET, SO_SNDBUF, + &sndbuf, sizeof(sndbuf)); +#endif + + const char* pub_src = + "(.mc.pub \"big\" (+ (* (til 100000) 1103515245) 12345))"; + msg = ray_str(pub_src, strlen(pub_src)); + ray_t* pub = ray_ipc_send(h2, 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); + + TEST_ASSERT_TRUE(pump_until_env_i64_at_least("_mc_count", 9, 1, 1000)); + ray_t* c = ray_env_get(ray_sym_intern("_mc_count", 9)); + ray_t* len = ray_env_get(ray_sym_intern("_mc_last_len", 12)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_NOT_NULL(len); + TEST_ASSERT_EQ_I(c->i64, 1); + TEST_ASSERT_EQ_I(len->i64, 100000); + + msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + ray_t* st = ray_ipc_send(h2, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "topics"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "subscriptions"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "published"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "delivered"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "dropped"), 0); + ray_release(st); + + msg = ray_str("(+ 0 0)", strlen("(+ 0 0)")); + ray_t* ping = ray_ipc_send(h1, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(ping); + TEST_ASSERT_FALSE(RAY_IS_ERR(ping)); + TEST_ASSERT_EQ_I(ping->i64, 0); + ray_release(ping); + + ray_ipc_close(h1); + ray_ipc_close(h2); + 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)" + "(set _mc_sum 0)" + "(set _mc_open_count 0)" + "(set _mc_dead_handle -1)" + "(set upd (fn [topic seq payload] " + " (set _mc_count (+ _mc_count 1))" + " (set _mc_sum (+ _mc_sum payload))))" + "(set .ipc.on.open (fn [h] " + " (do " + " (set _mc_open_count (+ _mc_open_count 1))" + " (if (== _mc_open_count 1) (set _mc_dead_handle h) 0))))" + "(set .ipc.on.close (fn [h] " + " (do " + " (.mc.sub \"hook-grow\" null)" + " (.mc.unsub \"hook-grow\")" + " null)))"); + 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); + TEST_ASSERT((h1) >= (0), "h1 connected"); + TEST_ASSERT((h2) >= (0), "h2 connected"); + + for (int i = 0; i < 7; i++) { + char src[64]; + int n = snprintf(src, sizeof(src), "(.mc.sub \"fill%d\" null)", i); + TEST_ASSERT((n) > (0), "format filler sub"); + TEST_ASSERT((size_t)n < sizeof(src), "filler sub fits buffer"); + ray_t* msg = ray_str(src, (size_t)n); + ray_t* sub = ray_ipc_send(h2, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); + ray_release(sub); + } + + ray_t* msg = ray_str("(.mc.sub \"target\" null)", strlen("(.mc.sub \"target\" null)")); + ray_t* sub = ray_ipc_send(h1, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); + ray_release(sub); + + msg = ray_str("(.mc.sub \"target\" null)", strlen("(.mc.sub \"target\" null)")); + sub = ray_ipc_send(h2, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); + ray_release(sub); + + ray_t* dead_v = ray_env_get(ray_sym_intern("_mc_dead_handle", 15)); + TEST_ASSERT_NOT_NULL(dead_v); + TEST_ASSERT_EQ_I(dead_v->type, -RAY_I64); + ray_selector_t* dead_sel = ray_poll_get(poll, dead_v->i64); + TEST_ASSERT_NOT_NULL(dead_sel); + ray_sock_t old_dead_fd = (ray_sock_t)dead_sel->fd; + TEST_ASSERT(old_dead_fd != RAY_INVALID_SOCK, "dead selector has fd"); + dead_sel->fd = RAY_INVALID_SOCK; + + msg = ray_str("(.mc.pub \"target\" 7)", strlen("(.mc.pub \"target\" 7)")); + ray_t* pub = ray_ipc_send(h2, 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); + pump_client(); + + ray_t* c = ray_env_get(ray_sym_intern("_mc_count", 9)); + ray_t* sum = ray_env_get(ray_sym_intern("_mc_sum", 7)); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT_NOT_NULL(sum); + TEST_ASSERT_EQ_I(c->i64, 1); + TEST_ASSERT_EQ_I(sum->i64, 7); + + msg = ray_str("(.mc.stats)", strlen("(.mc.stats)")); + ray_t* st = ray_ipc_send(h2, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(st); + TEST_ASSERT_FALSE(RAY_IS_ERR(st)); + TEST_ASSERT_EQ_I(dict_i64(st, "topics"), 8); + TEST_ASSERT_EQ_I(dict_i64(st, "subscriptions"), 8); + TEST_ASSERT_EQ_I(dict_i64(st, "published"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "delivered"), 1); + TEST_ASSERT_EQ_I(dict_i64(st, "dropped"), 1); + ray_release(st); + + ray_sock_close(old_dead_fd); + ray_ipc_close(h1); + ray_ipc_close(h2); + stop_server(poll, port, vm, tid); + PASS(); +} + +/* Regression: a sync request from a subscriber whose multicast frame is still + * queued must not corrupt the stream. test_mcast_large_payload_queues drains + * the queue before pinging; here the ping races the still-pending frame. Before + * the tx-drain fix, send_response spliced the RESP into the half-sent `upd` + * frame, so h1's reply came back garbled (or never framed) and the payload was + * truncated. With the fix the server drains the queued frame first, then + * replies on a frame boundary. */ +static test_result_t test_mcast_sync_reply_after_queued_frame(void) { + ray_t* r = ray_eval_str( + "(set _mc_count 0)" + "(set _mc_last_len 0)" + "(set _mc_open_count 0)" + "(set _mc_sub_handle -1)" + "(set upd (fn [topic seq payload] " + " (do " + " (set _mc_count (+ _mc_count 1))" + " (set _mc_last_len (count payload)))))" + "(set .ipc.on.open (fn [h] " + " (do " + " (set _mc_open_count (+ _mc_open_count 1))" + " (if (== _mc_open_count 1) (set _mc_sub_handle h) 0))))"); + 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); + TEST_ASSERT((h1) >= (0), "h1 connected"); + TEST_ASSERT((h2) >= (0), "h2 connected"); + + ray_t* msg = ray_str("(.mc.sub \"big\" null)", strlen("(.mc.sub \"big\" null)")); + ray_t* sub = ray_ipc_send(h1, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(sub); + TEST_ASSERT_FALSE(RAY_IS_ERR(sub)); + ray_release(sub); + +#ifndef RAY_OS_WINDOWS + /* Shrink the server->h1 send buffer so a big frame parks on sel->tx.buf + * instead of leaving in a single write. */ + ray_t* server_h = ray_env_get(ray_sym_intern("_mc_sub_handle", 14)); + TEST_ASSERT_NOT_NULL(server_h); + TEST_ASSERT_EQ_I(server_h->type, -RAY_I64); + ray_selector_t* server_sel = ray_poll_get(poll, server_h->i64); + TEST_ASSERT_NOT_NULL(server_sel); + int sndbuf = 4096; + setsockopt((ray_sock_t)server_sel->fd, SOL_SOCKET, SO_SNDBUF, + &sndbuf, sizeof(sndbuf)); +#endif + + const char* pub_src = + "(.mc.pub \"big\" (+ (* (til 100000) 1103515245) 12345))"; + msg = ray_str(pub_src, strlen(pub_src)); + ray_t* pub = ray_ipc_send(h2, 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); + + /* Do NOT drain h1 first: the ~800 KB frame is still queued on the server's + * tx.buf for h1. Issue a sync ping from h1 now — as h1 reads for its RESP + * it consumes the queued frame (firing `upd`), and with the fix the RESP + * only follows once that frame is fully flushed. */ + msg = ray_str("(+ 21 21)", strlen("(+ 21 21)")); + ray_t* ping = ray_ipc_send(h1, msg); + ray_release(msg); + TEST_ASSERT_NOT_NULL(ping); + TEST_ASSERT_FALSE(RAY_IS_ERR(ping)); + TEST_ASSERT_EQ_I(ping->type, -RAY_I64); + TEST_ASSERT_EQ_I(ping->i64, 42); /* clean reply, not bytes from the frame */ + ray_release(ping); + + /* The queued `upd` was delivered whole, not truncated by the interleave. */ + ray_t* cnt = ray_env_get(ray_sym_intern("_mc_count", 9)); + ray_t* len = ray_env_get(ray_sym_intern("_mc_last_len", 12)); + TEST_ASSERT_NOT_NULL(cnt); + TEST_ASSERT_NOT_NULL(len); + TEST_ASSERT_EQ_I(cnt->i64, 1); + TEST_ASSERT_EQ_I(len->i64, 100000); + + ray_ipc_close(h1); + ray_ipc_close(h2); + stop_server(poll, port, vm, tid); + PASS(); +} + +const test_entry_t mcast_entries[] = { + { "mcast/single_client_pub", test_mcast_single_client_pub, mcast_setup, mcast_teardown }, + { "mcast/two_clients_unsub_close", test_mcast_two_clients_unsub_close_stats, mcast_setup, mcast_teardown }, + { "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/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 }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_pool.c b/test/test_pool.c index 1dfeb0b39..1b757d0a9 100644 --- a/test/test_pool.c +++ b/test/test_pool.c @@ -634,10 +634,13 @@ static test_result_t test_pool_zero_workers(void) { TEST_ASSERT_EQ_I(atomic_load(&ctx.calls), 3); TEST_ASSERT_EQ_I(atomic_load(&ctx.elem_sum), 8192LL * 3); - /* Worker 0 (main) must have participated; worker 1 may or may not have - * picked up tasks depending on scheduling — at least worker 0 is set. */ - uint32_t mask = atomic_load(&ctx.saw_worker); - TEST_ASSERT_TRUE((mask & 0x1u) != 0); /* main thread always = worker 0 */ + /* No per-id participation assert, for the reason workers_participate + * gives: which claimant wins is pure scheduling. With one worker and + * three tasks the worker can drain all three before main enters its + * claim loop, leaving bit 0 unset — observed on macOS CI. Completion + * is asserted exactly above; some bit is necessarily set once + * calls == 3. */ + TEST_ASSERT_TRUE(atomic_load(&ctx.saw_worker) != 0); ray_pool_free(&pool); ray_heap_destroy(); diff --git a/test/test_store.c b/test/test_store.c index 2e13f2f68..bc4e99c6f 100644 --- a/test/test_store.c +++ b/test/test_store.c @@ -2709,6 +2709,54 @@ static test_result_t test_serde_function_types(void) { PASS(); } +/* ---- test_serde_builtin_name_roundtrip ---------------------------------- */ + +static test_result_t test_serde_builtin_name_roundtrip(void) { + /* Regression: builtins serialize by name, but the encoder capped the name + * at 15 bytes. A builtin whose registered name is longer was written + * truncated and could not be resolved on decode, so (de (ser fn)) raised a + * name error instead of round-tripping. test_serde_function_types only + * exercises short names (neg, +, list), so it never caught this. */ + ray_runtime_t* rt = ray_runtime_create(0, NULL); + TEST_ASSERT_NOT_NULL(rt); + + static const char* const long_names[] = { + ".db.parted.tables", /* 17 bytes, RAY_VARY */ + ".sys.querylog.enable", /* 20 bytes */ + }; + + for (size_t i = 0; i < sizeof(long_names) / sizeof(long_names[0]); i++) { + const char* name = long_names[i]; + TEST_ASSERT(strlen(name) > 15, "test name must exceed the old 15-byte cap"); + + /* Borrowed: ray_env_get returns the env-owned object, do not release. */ + ray_t* orig = ray_env_get(ray_sym_intern(name, strlen(name))); + TEST_ASSERT_NOT_NULL(orig); + TEST_ASSERT_FALSE(RAY_IS_ERR(orig)); + + ray_t* wire = ray_ser(orig); + TEST_ASSERT_NOT_NULL(wire); + TEST_ASSERT_FALSE(RAY_IS_ERR(wire)); + + ray_t* back = ray_de(wire); + TEST_ASSERT_NOT_NULL(back); + TEST_ASSERT_FALSE(RAY_IS_ERR(back)); + + /* The decoder resolves the full name in the global env, so it returns + * the very same builtin — identity is the strongest proof and implies + * the name survived intact. A truncated name would either miss or + * resolve to a different entry. */ + TEST_ASSERT_EQ_PTR(back, orig); + TEST_ASSERT_EQ_I(back->type, orig->type); + + ray_release(back); + ray_release(wire); + } + + ray_runtime_destroy(rt); + PASS(); +} + /* ---- serde coverage: ERROR object roundtrip ------------------------------ */ static test_result_t test_serde_error_roundtrip(void) { @@ -5509,6 +5557,7 @@ const test_entry_t store_entries[] = { { "store/serde_de_error_paths", test_serde_de_error_paths, store_setup, store_teardown }, { "store/serde_list_null_elem", test_serde_list_with_null_elem, store_setup, store_teardown }, { "store/serde_function_types", test_serde_function_types, NULL, NULL }, + { "store/serde_builtin_name_roundtrip", test_serde_builtin_name_roundtrip, NULL, NULL }, { "store/serde_error_roundtrip", test_serde_error_roundtrip, store_setup, store_teardown }, { "store/serde_large_null_vec", test_serde_large_null_vec, store_setup, store_teardown }, { "store/serde_f32_atom", test_serde_f32_atom_and_edge_cases, store_setup, store_teardown },