diff --git a/CLAUDE.md b/CLAUDE.md
index 387ef5e..9992e48 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -115,7 +115,7 @@ console.log(table.toRows());
```html
*
* @module rayforce
- * @version 0.2.1
+ * @version 0.3.0
*/
import { createRayforceSDK, Types, Expr } from './rayforce.sdk.js';
// SDK version
-export const version = '0.2.1';
+export const version = '0.3.0';
// Re-export types and utilities
export { Types, Expr };
@@ -191,6 +191,10 @@ export const create = {
if (!_sdkInstance) throw new Error('RayforceDB not initialized');
return (v) => _sdkInstance.time(v);
},
+ get timespan() {
+ if (!_sdkInstance) throw new Error('RayforceDB not initialized');
+ return (v) => _sdkInstance.timespan(v);
+ },
get timestamp() {
if (!_sdkInstance) throw new Error('RayforceDB not initialized');
return (v) => _sdkInstance.timestamp(v);
diff --git a/src/main.c b/src/main.c
index 7759773..01485fb 100644
--- a/src/main.c
+++ b/src/main.c
@@ -1,5 +1,5 @@
/*
- * RayforceDB WASM Entry Point — v2 engine
+ * RayforceDB WASM Entry Point — v3 engine
*
* This file provides the main entry point and exported functions
* for the WebAssembly build of RayforceDB.
@@ -16,6 +16,12 @@
#include
#include "mem/sys.h"
#include "table/sym.h"
+#include "ops/idxop.h"
+_Static_assert(sizeof(ray_t) == 32, "WASM value header must remain 32 bytes");
+_Static_assert(offsetof(ray_t, _idx_pad) == 8, "index padding must preserve aux high slot");
+_Static_assert(offsetof(ray_index_t, u) == 32, "index union offset changed");
+_Static_assert(sizeof(ray_index_t) == 96, "WASM index payload must reserve 96 bytes");
+
/* Internal-engine functions we reach for WASM glue. We declare them as
* externs (rather than including the headers) because core/runtime.h and
@@ -46,7 +52,7 @@ extern ray_t* ray_read_csv(const char* path);
* IPC stubs
*
* src/core/ipc.c is excluded from the WASM build (uses select()/sockets).
- * src/ops/system.c still references these symbols, so provide weak stubs
+ * src/ops/system.c still references these symbols, so provide explicit stubs
* that return "nyi" errors at runtime. Browsers can't open raw TCP sockets
* from WASM anyway — these would be unsuitable even if the engine code
* compiled.
@@ -240,6 +246,7 @@ EMSCRIPTEN_KEEPALIVE int32_t TYPE_CODE_F64(void) { return RAY_F64; }
EMSCRIPTEN_KEEPALIVE int32_t TYPE_CODE_DATE(void) { return RAY_DATE; }
EMSCRIPTEN_KEEPALIVE int32_t TYPE_CODE_TIME(void) { return RAY_TIME; }
EMSCRIPTEN_KEEPALIVE int32_t TYPE_CODE_TIMESTAMP(void) { return RAY_TIMESTAMP; }
+EMSCRIPTEN_KEEPALIVE int32_t TYPE_CODE_TIMESPAN(void) { return RAY_TIMESPAN; }
EMSCRIPTEN_KEEPALIVE int32_t TYPE_CODE_GUID(void) { return RAY_GUID; }
EMSCRIPTEN_KEEPALIVE int32_t TYPE_CODE_SYM(void) { return RAY_SYM; }
EMSCRIPTEN_KEEPALIVE int32_t TYPE_CODE_STR(void) { return RAY_STR; }
@@ -379,6 +386,50 @@ EMSCRIPTEN_KEEPALIVE ray_t* init_date(int64_t days) { return ray_date(days
EMSCRIPTEN_KEEPALIVE ray_t* init_time(int64_t ms) { return ray_time(ms); }
EMSCRIPTEN_KEEPALIVE ray_t* init_timestamp(int64_t ns) { return ray_timestamp(ns); }
+/* Keep signed nanoseconds exact across Emscripten's legalized i64 ABI. */
+EMSCRIPTEN_KEEPALIVE ray_t* init_timespan_parts(uint32_t lo, int32_t hi) {
+ uint64_t bits = ((uint64_t)(uint32_t)hi << 32) | lo;
+ int64_t ns;
+ memcpy(&ns, &bits, sizeof(ns));
+ /* The released core's atom constructor dereferences a NULL allocation.
+ * Keep allocation failure at this new bridge boundary, not in JS payload. */
+ ray_t* out = ray_alloc(0);
+ if (!out) return NULL;
+ if (RAY_IS_ERR(out)) { ray_error_free(out); return NULL; }
+ out->type = -RAY_TIMESPAN;
+ out->i64 = ns;
+ return out;
+}
+/* Fresh constructor vectors have no aliases or indexes yet. JS observed the
+ * sentinel during its fill loop; publish the hint once, without a second scan. */
+EMSCRIPTEN_KEEPALIVE void timespan_vec_mark_nulls(ray_t* vec) {
+ if (vec && vec->type == RAY_TIMESPAN) vec->attrs |= RAY_ATTR_HAS_NULLS;
+}
+/* ray_vec_set preserves the old owned reference on allocation failure, and
+ * consumes it on a successful COW. Use int32 index/parts to avoid legalized
+ * i64 parameter shifting. Numeric vec_set needs explicit sentinel publication. */
+EMSCRIPTEN_KEEPALIVE ray_t* timespan_vec_set_parts(ray_t* vec, int32_t idx,
+ uint32_t lo, int32_t hi) {
+ if (!vec || vec->type != RAY_TIMESPAN || idx < 0 || idx >= vec->len) return NULL;
+ uint64_t bits = ((uint64_t)(uint32_t)hi << 32) | lo;
+ int64_t ns;
+ memcpy(&ns, &bits, sizeof(ns));
+ ray_t* out = ray_vec_set(vec, idx, &ns);
+ if (RAY_IS_ERR(out)) { ray_error_free(out); return NULL; }
+ if (out && ns == NULL_I64) out->attrs |= RAY_ATTR_HAS_NULLS;
+ return out;
+}
+EMSCRIPTEN_KEEPALIVE uint32_t read_timespan_lo(ray_t* obj) {
+ return obj ? (uint32_t)(uint64_t)obj->i64 : 0;
+}
+EMSCRIPTEN_KEEPALIVE int32_t read_timespan_hi(ray_t* obj) {
+ uint32_t bits = obj ? (uint32_t)((uint64_t)obj->i64 >> 32) : 0;
+ int32_t hi;
+ memcpy(&hi, &bits, sizeof(hi));
+ return hi;
+}
+
+
EMSCRIPTEN_KEEPALIVE ray_t* init_symbol_str(const char* s, int64_t len) {
return ray_sym(ray_sym_intern(s, (size_t)len));
}
@@ -531,7 +582,7 @@ static const void* scalar_addr(ray_t* atom, int8_t target_type) {
case RAY_I16: return &atom->i16;
case RAY_I32: return &atom->i32;
case RAY_I64: case RAY_DATE:
- case RAY_TIME: case RAY_TIMESTAMP:
+ case RAY_TIME: case RAY_TIMESTAMP: case RAY_TIMESPAN:
case RAY_SYM: return &atom->i64;
case RAY_F32: {
static _Thread_local float f; /* narrow once into a stable slot */
@@ -558,6 +609,7 @@ static ray_t* box_vec_element(int8_t vec_type, const void* p) {
case RAY_DATE: return ray_date(*(const int32_t*)p);
case RAY_TIME: return ray_time(*(const int32_t*)p);
case RAY_TIMESTAMP: return ray_timestamp(*(const int64_t*)p);
+ case RAY_TIMESPAN: return ray_timespan(*(const int64_t*)p);
case RAY_SYM: return ray_sym(*(const int64_t*)p);
case RAY_GUID: return ray_guid((const uint8_t*)p);
default: return RAY_NULL_OBJ;
diff --git a/src/platform-stubs.c b/src/platform-stubs.c
new file mode 100644
index 0000000..4773f5b
--- /dev/null
+++ b/src/platform-stubs.c
@@ -0,0 +1,60 @@
+/* Browser builds have no native TCP listener or transmit queue. Keep these
+ * signatures checked against the core headers, and refuse operations explicitly.
+ */
+#include "core/ipc.h"
+#include "app/repl.h"
+
+static ray_t* no_ipc(void) { return ray_error("nyi", "native IPC is unavailable in WASM"); }
+ray_t* ray_ipc_parse_open_opts_full(ray_t* arg, ray_ipc_open_opts_t* out) {
+ (void)arg; (void)out; return no_ipc();
+}
+int64_t ray_ipc_connect_with(const char* h, uint16_t p, const char* u,
+ const char* pw, const ray_ipc_open_opts_t* opts) {
+ (void)h; (void)p; (void)u; (void)pw; (void)opts; return -1;
+}
+int64_t ray_ipc_listen_at(ray_poll_t* poll, const char* host, uint16_t port) {
+ (void)poll; (void)host; (void)port; return -1;
+}
+ray_t* ray_ipc_send_timeout(int64_t h, ray_t* msg, int64_t timeout) {
+ (void)h; (void)msg; (void)timeout; return no_ipc();
+}
+int ray_ipc_xport_policy_get(void) { return RAY_IPC_XPORT_TCP; }
+const char* ray_ipc_xport_policy_name(int p) { return p == RAY_IPC_XPORT_TCP ? "tcp" : NULL; }
+const char* ray_ipc_xport_kind_name(int kind) { (void)kind; return NULL; }
+/* No browser handle resolves; match the native invalid-handle contract. */
+size_t ray_ipc_handle_threshold(int64_t h) { (void)h; return RAY_IPC_COMPRESS_AUTO; }
+ray_err_t ray_ipc_frame_async_at(ray_t* msg, size_t threshold, ray_poll_frame_t** out) {
+ (void)msg; (void)threshold; *out = NULL; return RAY_ERR_NYI;
+}
+ray_err_t ray_ipc_try_send_frame(int64_t h, ray_poll_frame_t* f) {
+ (void)h; (void)f; return RAY_ERR_NYI;
+}
+void ray_poll_frame_release(ray_poll_frame_t* f) {
+ if (f && --f->rc == 0) ray_free_raw(f);
+}
+void ray_ipc_tx_limit_get(int64_t* bytes, int64_t* frames) {
+ if (bytes) *bytes = 0;
+ if (frames) *frames = 0;
+}
+ray_err_t ray_ipc_tx_info(int64_t h, ray_ipc_tx_info_t* out) {
+ (void)h; (void)out; return RAY_ERR_IO;
+}
+int64_t ray_ipc_tx_hwm_bytes(ray_poll_t* poll) { (void)poll; return 0; }
+static _Thread_local bool auto_journal;
+bool ray_ipc_auto_journal_eval(void) { return auto_journal; }
+bool ray_ipc_set_auto_journal_eval(bool enabled) {
+ bool previous = auto_journal; auto_journal = enabled; return previous;
+}
+ray_t* ray_repl_complete_fn(ray_t* prefix) {
+ (void)prefix; return ray_error("nyi", "native REPL completion is unavailable in WASM");
+}
+ray_err_t ray_ipc_tx_limit_set(int64_t bytes, int64_t frames) {
+ (void)bytes; (void)frames; return RAY_ERR_NYI;
+}
+ray_err_t ray_ipc_tx_limit_set_handle(int64_t h, int64_t bytes, int64_t frames) {
+ (void)h; (void)bytes; (void)frames; return RAY_ERR_NYI;
+}
+int ray_ipc_xport_policy_parse(const char* s, size_t n) { (void)s; (void)n; return -1; }
+bool ray_ipc_xport_policy_set(int policy) { (void)policy; return false; }
+ray_poll_t* ray_ipc_context_poll(void) { return NULL; }
+ray_poll_t* ray_ipc_active_poll(void) { return NULL; }
diff --git a/src/rayforce.sdk.d.ts b/src/rayforce.sdk.d.ts
index e5ccec0..a1c3909 100644
--- a/src/rayforce.sdk.d.ts
+++ b/src/rayforce.sdk.d.ts
@@ -22,6 +22,7 @@ export declare const Types: {
readonly GUID: 11;
readonly SYM: 12;
readonly STR: 13;
+ readonly TIMESPAN: 16;
readonly TABLE: 98;
readonly DICT: 99;
readonly LAMBDA: 100;
@@ -143,6 +144,13 @@ export declare class RayTimestamp extends RayObject {
toJS(): Date;
}
+export declare class RayTimespan extends RayObject {
+ /** Exact signed nanoseconds; INT64_MIN is the raw NULL sentinel. */
+ readonly value: bigint;
+ readonly isNull: boolean;
+ toJS(): bigint | null;
+}
+
export declare class Sym extends RayObject {
/** Interned symbol ID */
readonly id: number;
@@ -188,15 +196,15 @@ export declare class Vector extends RayObject
readonly typedArray: T;
/** Get element at index */
- at(idx: number): T extends BigInt64Array ? bigint : number;
+ at(idx: number, raw?: boolean): T extends BigInt64Array ? number | bigint | null : number;
/** Set element at index */
- set(idx: number, value: T extends BigInt64Array ? bigint : number): void;
+ set(idx: number, value: T extends BigInt64Array ? number | bigint | null : number): void;
/** Convert to JS array (copies data) */
- toJS(): Array;
+ toJS(): Array;
- [Symbol.iterator](): Iterator;
+ [Symbol.iterator](): Iterator;
}
/**
@@ -436,6 +444,7 @@ export declare class RayforceSDK {
/** Create a timestamp */
timestamp(value: number | bigint | Date): RayTimestamp;
+ timespan(value: number | bigint | null): RayTimespan;
/** Create a symbol (interned string) */
symbol(value: string): Sym;
@@ -448,6 +457,7 @@ export declare class RayforceSDK {
* @param type - Type code from Types
* @param lengthOrData - Length or array of values
*/
+ vector(type: 16, lengthOrData: number | Array): Vector;
vector(type: T, lengthOrData: number | any[]): Vector;
/**
diff --git a/src/rayforce.sdk.js b/src/rayforce.sdk.js
index fa250eb..0e42c7c 100644
--- a/src/rayforce.sdk.js
+++ b/src/rayforce.sdk.js
@@ -5,7 +5,7 @@
* Provides TypedArray views over native Rayforce vectors for efficient data access.
*
* @module rayforce
- * @version 0.2.1
+ * @version 0.3.0
*/
// ============================================================================
@@ -43,6 +43,7 @@ export const Types = Object.freeze({
GUID: 11,
SYM: 12,
STR: 13,
+ TIMESPAN: 16,
TABLE: 98,
DICT: 99,
LAMBDA: 100,
@@ -66,6 +67,7 @@ const ELEMENT_SIZES = {
[Types.DATE]: 4,
[Types.TIME]: 4,
[Types.TIMESTAMP]: 8,
+ [Types.TIMESPAN]: 8,
[Types.SYM]: 8,
[Types.GUID]: 16,
[Types.LIST]: 4, // pointer size in WASM32
@@ -83,6 +85,7 @@ const TYPED_ARRAY_MAP = {
[Types.DATE]: Int32Array,
[Types.TIME]: Int32Array,
[Types.TIMESTAMP]: BigInt64Array,
+ [Types.TIMESPAN]: BigInt64Array,
[Types.SYM]: BigInt64Array,
};
@@ -90,6 +93,17 @@ const TYPED_ARRAY_MAP = {
// Main SDK Class
// ============================================================================
+const TIMESPAN_NULL = -(1n << 63n);
+function timespanBits(value) {
+ if (value === null) return TIMESPAN_NULL;
+ if (typeof value !== 'bigint' && (typeof value !== 'number' || !Number.isSafeInteger(value))) {
+ throw new TypeError('TIMESPAN requires bigint or a safe integer nanosecond count');
+ }
+ const ns = BigInt(value);
+ if (ns < TIMESPAN_NULL || ns > (1n << 63n) - 1n) throw new RangeError('TIMESPAN outside signed 64-bit range');
+ return ns;
+}
+
class RayforceSDK {
constructor(wasm) {
this._wasm = wasm;
@@ -139,6 +153,11 @@ class RayforceSDK {
this._initDate = w.cwrap('init_date', 'number', ['number']);
this._initTime = w.cwrap('init_time', 'number', ['number']);
this._initTimestamp = w.cwrap('init_timestamp', 'number', ['number']);
+ this._initTimespanParts = w.cwrap('init_timespan_parts', 'number', ['number', 'number']);
+ this._readTimespanLo = w.cwrap('read_timespan_lo', 'number', ['number']);
+ this._readTimespanHi = w.cwrap('read_timespan_hi', 'number', ['number']);
+ this._timespanVecMarkNulls = w.cwrap('timespan_vec_mark_nulls', null, ['number']);
+ this._timespanVecSetParts = w.cwrap('timespan_vec_set_parts', 'number', ['number', 'number', 'number', 'number']);
this._initSymbolStr = w.cwrap('init_symbol_str', 'number', ['string', 'number']);
this._initStringStr = w.cwrap('init_string_str', 'number', ['string', 'number']);
@@ -280,6 +299,7 @@ class RayforceSDK {
case Types.DATE: return new RayDate(this, ptr);
case Types.TIME: return new RayTime(this, ptr);
case Types.TIMESTAMP: return new RayTimestamp(this, ptr);
+ case Types.TIMESPAN: return new RayTimespan(this, ptr);
case Types.SYM: return new Sym(this, ptr);
case Types.STR: return new RayString(this, ptr);
case Types.GUID: return new GUID(this, ptr);
@@ -403,9 +423,17 @@ class RayforceSDK {
return new RayTime(this, this._initTime(ms));
}
+ /** Signed nanoseconds, with INT64_MIN reserved for NULL. */
+ timespan(value) {
+ const ns = timespanBits(value);
+ const ptr = this._initTimespanParts(Number(ns & 0xffffffffn), Number(BigInt.asIntN(32, ns >> 32n)));
+ if (!ptr) throw new Error('Failed to allocate TIMESPAN atom');
+ return new RayTimespan(this, ptr);
+ }
+
/**
- * Create a timestamp (nanoseconds since 2000-01-01)
- * @param {number|bigint|Date} value - Nanoseconds or JS Date
+ * Create a timestamp (nanoseconds since 2000-01-01).
+ * @param {number|bigint|Date} value
* @returns {RayTimestamp}
*/
timestamp(value) {
@@ -445,19 +473,24 @@ class RayforceSDK {
*/
vector(type, lengthOrData) {
if (Array.isArray(lengthOrData)) {
- const arr = lengthOrData;
+ const arr = type === Types.TIMESPAN ? lengthOrData.map(timespanBits) : lengthOrData;
// v2 vectors are growable; init_vector takes a capacity hint, then
// each push appends. For typed numeric vectors we still allocate
// up-front and write through the typed-array view for speed.
const vec = new Vector(this, this._initVector(type, arr.length), type);
const view = vec.typedArray;
+ let hasTimespanNull = false;
for (let i = 0; i < arr.length; i++) {
- if (type === Types.I64 || type === Types.TIMESTAMP || type === Types.SYM) {
+ if (type === Types.TIMESPAN) {
+ view[i] = arr[i];
+ hasTimespanNull ||= arr[i] === TIMESPAN_NULL;
+ } else if (type === Types.I64 || type === Types.TIMESTAMP || type === Types.SYM) {
view[i] = BigInt(type === Types.SYM ? this._internSymbol(arr[i], arr[i].length) : arr[i]);
} else {
view[i] = arr[i];
}
}
+ if (hasTimespanNull) this._timespanVecMarkNulls(vec.ptr);
return vec;
}
return new Vector(this, this._initVector(type, lengthOrData), type);
@@ -930,6 +963,16 @@ class RayTimestamp extends RayObject {
}
}
+class RayTimespan extends RayObject {
+ static typeCode = -Types.TIMESPAN;
+ get value() {
+ return (BigInt(this._sdk._readTimespanHi(this._ptr)) << 32n) |
+ BigInt(this._sdk._readTimespanLo(this._ptr) >>> 0);
+ }
+ get isNull() { return this.value === TIMESPAN_NULL; }
+ toJS() { const ns = this.value; return ns === TIMESPAN_NULL ? null : ns; }
+}
+
class Sym extends RayObject {
static typeCode = -Types.SYM;
@@ -1063,6 +1106,7 @@ class Vector extends RayObject {
throw new RangeError(`Index ${idx} out of bounds [0, ${this.length})`);
}
const val = this.typedArray[idx];
+ if (!raw && this._elementType === Types.TIMESPAN) return val === TIMESPAN_NULL ? null : val;
// Convert symbol IDs to strings
if (!raw && this._elementType === Types.SYM) {
@@ -1088,6 +1132,16 @@ class Vector extends RayObject {
if (idx < 0 || idx >= this.length) {
throw new RangeError(`Index ${idx} out of bounds [0, ${this.length})`);
}
+ if (this._elementType === Types.TIMESPAN) {
+ if (!Number.isInteger(idx)) throw new RangeError('Vector index must be an integer');
+ const ns = timespanBits(value);
+ const next = this._sdk._timespanVecSetParts(this._ptr, idx,
+ Number(ns & 0xffffffffn), Number(BigInt.asIntN(32, ns >> 32n)));
+ if (!next) throw new Error('TIMESPAN vector update allocation failed');
+ this._ptr = next;
+ this._typedArray = null;
+ return;
+ }
this.typedArray[idx] = value;
}
@@ -1097,6 +1151,7 @@ class Vector extends RayObject {
*/
toJS() {
const arr = Array.from(this.typedArray);
+ if (this._elementType === Types.TIMESPAN) return arr.map(v => v === TIMESPAN_NULL ? null : v);
// Convert BigInt to Number for I64 types if safe
if (this._elementType === Types.I64 ||
@@ -1427,8 +1482,9 @@ class Table extends RayObject {
for (let i = 0; i < count; i++) {
const row = {};
for (const name of names) {
- row[name] = this.col(name).at(i);
- if (typeof row[name] === 'bigint') {
+ const column = this.col(name);
+ row[name] = column.at(i);
+ if (typeof row[name] === 'bigint' && column.elementType !== Types.TIMESPAN) {
const n = Number(row[name]);
row[name] = Number.isSafeInteger(n) ? n : row[name];
}
@@ -1679,7 +1735,7 @@ export {
RayNull,
RayError,
B8, U8, I16, I32, I64, F32, F64,
- RayDate, RayTime, RayTimestamp,
+ RayDate, RayTime, RayTimestamp, RayTimespan,
Sym, GUID,
Vector, RayString, StrVector, List, Dict, Table, Lambda,
Expr, SelectQuery,
diff --git a/test-current-core.mjs b/test-current-core.mjs
new file mode 100644
index 0000000..85854fa
--- /dev/null
+++ b/test-current-core.mjs
@@ -0,0 +1,120 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { init, Types, RayTimespan } from './dist/index.js';
+const rf = await init({ singleton: false });
+assert.equal(rf.version, '3.0.2');
+assert.equal(Types.TIMESPAN, 16);
+const minimum = -(1n << 63n);
+for (const n of [0n, 1n, -1n, 9007199254740993n, -9007199254740993n, (1n << 63n) - 1n, minimum]) {
+ const a = rf.timespan(n);
+ assert.ok(a instanceof RayTimespan);
+ assert.equal(a.type, -16);
+ assert.equal(a.value, n);
+ assert.equal(a.isNull, n === minimum);
+ assert.equal(a.toJS(), n === minimum ? null : n);
+ a.drop();
+}
+assert.throws(() => rf.timespan(9007199254740992), TypeError);
+assert.throws(() => rf.timespan(1n << 63n), RangeError);
+assert.throws(() => rf.timespan(-1.5), TypeError);
+const values = [1n, -1n, 9007199254740993n, null];
+const v = rf.vector(Types.TIMESPAN, values);
+assert.deepEqual(v.toJS(), values);
+assert.equal(v.at(2), values[2]);
+assert.equal(v.at(3), null);
+assert.equal(v.at(3, true), minimum);
+assert.deepEqual([...v.typedArray], [1n, -1n, 9007199254740993n, minimum]);
+rf.set('W6Input', v);
+assert.equal(rf.eval('(sum (nil? W6Input))').toJS(), 1);
+const oldView = v.typedArray;
+v.set(0, null);
+assert.equal(v.at(0), null);
+assert.equal(oldView[0], 1n); // the bound original keeps its backing alive
+assert.equal(rf.eval('(sum (nil? W6Input))').toJS(), 1);
+rf.set('W6Changed', v);
+assert.equal(rf.eval('(sum (nil? W6Changed))').toJS(), 2);
+v.set(0, 2n);
+assert.equal(v.at(0), 2n);
+v.drop();
+const indexedSpan = rf.eval("(.idx.hash (as 'TIMESPAN [1 2 1]))");
+assert.equal(indexedSpan.isError, false);
+rf.set('W6IndexedOriginal', indexedSpan);
+indexedSpan.set(0, 3n);
+rf.set('W6IndexedChanged', indexedSpan);
+assert.equal(rf.eval("(nil? (find W6IndexedOriginal (as 'TIMESPAN 3)))").toJS(), true);
+assert.equal(rf.eval("(find W6IndexedChanged (as 'TIMESPAN 3))").toJS(), 0);
+indexedSpan.drop();
+const empty = rf.vector(Types.TIMESPAN, []);
+assert.deepEqual(empty.toJS(), []);
+empty.drop();
+for (const [expr, expected] of [
+ ['0D00:00:00.000000001', 1n],
+ ['(- 2026.01.01D00:00:00.000000002 2026.01.01D00:00:00.000000001)', 1n],
+ ["(as 'TIMESPAN 9007199254740993)", 9007199254740993n],
+]) {
+ const a = rf.eval(expr);
+ assert.equal(a.isError, false, expr);
+ assert.equal(a.type, -16, expr);
+ assert.equal(a.toJS(), expected, expr);
+ a.drop();
+}
+// Duration null survives the engine/wrapper boundary without changing type.
+const durationNull = rf.eval("(as 'TIMESPAN 0Nl)");
+assert.equal(durationNull.type, -16);
+assert.equal(durationNull.toJS(), null);
+durationNull.drop();
+// These are real native x86_64 frames generated with ray_ser from the pinned
+// tag, not self-roundtrips or altered version bytes.
+const fixture = JSON.parse(readFileSync(new URL('./test/fixtures/core-v3.0.2-wire.json', import.meta.url)));
+assert.equal(fixture.wire, 3);
+const expected = [1, 1n, 9007199254740993n, null,
+ [1n, -1n, 9007199254740993n, null],
+ [{ duration: 1n }, { duration: -1n }, { duration: 9007199254740993n }, { duration: null }]];
+for (const [i, entry] of fixture.cases.entries()) {
+ const decoded = rf.eval(`(de (as 'U8 [${[...Buffer.from(entry.hex, 'hex')].join(' ')}]))`);
+ assert.equal(decoded.isError, false, entry.expr);
+ assert.deepEqual(i === 5 ? decoded.toRows() : decoded.toJS(), expected[i], entry.expr);
+ decoded.drop();
+}
+// The stable tag must reject wire v4 explicitly. This is rejection coverage,
+// NOT evidence that v3.0.2 can decode current dev's format.
+const v4 = Buffer.from(fixture.cases[0].hex, 'hex');
+v4[4] = 4;
+const incompatible = rf.eval(`(de (as 'U8 [${[...v4].join(' ')}]))`);
+assert.equal(incompatible.isError, true);
+assert.equal(incompatible.code, 'version');
+incompatible.drop();
+for (const [expr, expectedRows] of [
+ ['(find (.idx.hash [1 2 1]) [2 1])', [1, 0]],
+ ["(find (.idx.hash ['a 'b 'a]) ['b 'a])", [1, 0]],
+]) {
+ const indexed = rf.eval(expr);
+ assert.equal(indexed.isError, false, expr);
+ assert.deepEqual(indexed.toJS(), expectedRows, expr);
+ indexed.drop();
+}
+// An x86_64 inline index is not a wasm32 pointer layout. Its column remains
+// readable but its accelerator must be ignored before examining child offsets.
+const nativeIndex = JSON.parse(readFileSync(new URL('./test/fixtures/native-v3.0.2-index.json', import.meta.url)));
+rf._wasm.FS.mkdirTree('/tmp/w6-native-index');
+for (const [name, base64] of Object.entries(nativeIndex.files)) {
+ rf._wasm.FS.writeFile(`/tmp/w6-native-index/${name}`, Buffer.from(base64, 'base64'));
+}
+const imported = rf.eval('(set W6NativeIndex (.db.splayed.get "/tmp/w6-native-index"))');
+assert.equal(imported.isError, false);
+imported.drop();
+assert.deepEqual(rf.eval("(at W6NativeIndex 'v)").toJS(), [10, 20, 10]);
+assert.equal(rf.eval("(.idx.has? (at W6NativeIndex 'v))").toJS(), false);
+assert.equal(rf.eval("(find (at W6NativeIndex 'v) 20)").toJS(), 1);
+const savedIndex = rf.eval('(.db.splayed.set "/tmp/w6-own-index" (table [v] (list (.idx.hash [10 20 10]))))');
+assert.equal(savedIndex.isError, false);
+savedIndex.drop();
+const ownColumn = rf._wasm.FS.readFile('/tmp/w6-own-index/v');
+// 32-byte column header + 24-byte values, aligned to 64, then index order at +17.
+assert.ok([129, 130, 131].includes(ownColumn[81]));
+const loadedIndex = rf.eval('(set W6OwnIndex (.db.splayed.get "/tmp/w6-own-index"))');
+assert.equal(loadedIndex.isError, false);
+loadedIndex.drop();
+assert.equal(rf.eval("(.idx.has? (at W6OwnIndex 'v))").toJS(), true);
+assert.equal(rf.eval("(find (at W6OwnIndex 'v) 20)").toJS(), 1);
+console.log('current-core TIMESPAN and native wire-v3 checks passed');
diff --git a/test-examples.mjs b/test-examples.mjs
index 75f8f83..c710fcf 100644
--- a/test-examples.mjs
+++ b/test-examples.mjs
@@ -34,7 +34,7 @@ await new Promise((resolve, reject) => {
const { port } = server.address();
const origin = `http://127.0.0.1:${port}`;
-const browser = await chromium.launch({ channel: 'chrome', headless: true });
+const browser = await chromium.launch({ channel: process.env.BROWSER_CHANNEL ?? 'chrome', headless: true });
async function openPage(pathname, { cdnPackage = false } = {}) {
const page = await browser.newPage();
@@ -48,7 +48,7 @@ async function openPage(pathname, { cdnPackage = false } = {}) {
);
if (cdnPackage) {
- await page.route('https://unpkg.com/rayforce-wasm@0.2.1/dist/**', async (route) => {
+ await page.route('https://unpkg.com/rayforce-wasm@0.3.0/dist/**', async (route) => {
const filename = new URL(route.request().url()).pathname.split('/').at(-1);
const filePath = join(root, 'dist', filename);
await route.fulfill({
@@ -66,6 +66,18 @@ try {
const main = await openPage('/examples/index.html');
await main.page.waitForFunction(() => globalThis.rf?.version);
+ const nativeFrames = JSON.parse(await readFile(join(root, 'test/fixtures/core-v3.0.2-wire.json'), 'utf8'));
+ assert.deepEqual(await main.page.evaluate((frames) => {
+ const rf = globalThis.rf;
+ const duration = rf.timespan(9007199254740993n);
+ const v = rf.vector(16, [1n, -1n, null, 9007199254740993n]);
+ const bytes = frames.cases[2].hex.match(/../g).map(x => parseInt(x, 16));
+ const wire = rf.eval(`(de (as 'U8 [${bytes.join(' ')}]))`);
+ const observed = [duration.value.toString(), v.toJS().map(x => x === null ? null : x.toString()), wire.toJS().toString()];
+ duration.drop(); v.drop(); wire.drop();
+ return observed;
+ }, nativeFrames), ['9007199254740993', ['1', '-1', null, '9007199254740993'], '9007199254740993']);
+
const exampleButtons = main.page.locator('.example-btn');
for (let index = 0; index < (await exampleButtons.count()); index += 1) {
const before = await main.page.locator('.output-line').count();
diff --git a/test-timespan-allocation-unit.mjs b/test-timespan-allocation-unit.mjs
new file mode 100644
index 0000000..7a28343
--- /dev/null
+++ b/test-timespan-allocation-unit.mjs
@@ -0,0 +1,9 @@
+import assert from 'node:assert/strict';
+import {createRayforceSDK} from './src/rayforce.sdk.js';
+const rf=createRayforceSDK({cwrap:()=>()=>0});
+let called=0;
+rf._initTimespanParts=()=>{called++; return 0;};
+assert.throws(()=>rf.timespan(1n), /Failed to allocate TIMESPAN atom/);assert.equal(called,1);
+rf._initTimespanParts=(lo,hi)=>{assert.equal(lo,1);assert.equal(hi,2097152);return 64;};
+assert.equal(rf.timespan(9007199254740993n).ptr,64);
+console.log('TIMESPAN_JS_ALLOCATION_BOUNDARY_AND_EXACT_PARTS_UNIT_PASS');
diff --git a/test-wire4-examples.mjs b/test-wire4-examples.mjs
new file mode 100644
index 0000000..98dcd15
--- /dev/null
+++ b/test-wire4-examples.mjs
@@ -0,0 +1,143 @@
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { readFile } from 'node:fs/promises';
+import { extname, join, normalize } from 'node:path';
+import { chromium } from 'playwright';
+
+const root = new URL('.', import.meta.url).pathname;
+const mimeTypes = {
+ '.css': 'text/css',
+ '.html': 'text/html',
+ '.js': 'text/javascript',
+ '.wasm': 'application/wasm',
+};
+
+const server = createServer(async (request, response) => {
+ try {
+ const pathname = new URL(request.url, 'http://localhost').pathname;
+ const relativePath = pathname === '/' ? 'examples/index.html' : pathname.slice(1);
+ const filePath = normalize(join(root, relativePath));
+ assert.ok(filePath.startsWith(root), 'request escaped repository root');
+ const body = await readFile(filePath);
+ response.writeHead(200, { 'content-type': mimeTypes[extname(filePath)] ?? 'application/octet-stream' });
+ response.end(body);
+ } catch (error) {
+ response.writeHead(error?.code === 'ENOENT' ? 404 : 500);
+ response.end(String(error));
+ }
+});
+
+await new Promise((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', resolve);
+});
+
+const { port } = server.address();
+const origin = `http://127.0.0.1:${port}`;
+const browser = await chromium.launch({ channel: process.env.BROWSER_CHANNEL ?? 'chrome', headless: true });
+
+async function openPage(pathname, { cdnPackage = false } = {}) {
+ const page = await browser.newPage();
+ const runtimeErrors = [];
+ page.on('pageerror', (error) => runtimeErrors.push(error));
+
+ await page.route('https://fonts.googleapis.com/**', (route) => route.abort());
+ await page.route('https://fonts.gstatic.com/**', (route) => route.abort());
+ await page.route('https://unpkg.com/lucide@latest/dist/umd/lucide.min.js', (route) =>
+ route.fulfill({ contentType: 'text/javascript', body: 'globalThis.lucide = { createIcons() {} };' }),
+ );
+
+ if (cdnPackage) {
+ await page.route('https://unpkg.com/rayforce-wasm@0.3.0/dist/**', async (route) => {
+ const filename = new URL(route.request().url()).pathname.split('/').at(-1);
+ const filePath = join(root, 'dist', filename);
+ await route.fulfill({
+ contentType: mimeTypes[extname(filePath)] ?? 'application/octet-stream',
+ body: await readFile(filePath),
+ });
+ });
+ }
+
+ await page.goto(`${origin}${pathname}`);
+ return { page, runtimeErrors };
+}
+
+try {
+ const main = await openPage('/examples/index.html');
+ await main.page.waitForFunction(() => globalThis.rf?.version);
+
+ const nativeFrames = JSON.parse(await readFile(join(root, 'test/fixtures/core-fa9bccfd-wire.json'), 'utf8'));
+ assert.deepEqual(await main.page.evaluate((frames) => {
+ const rf = globalThis.rf;
+ const duration = rf.timespan(9007199254740993n);
+ const v = rf.vector(16, [1n, -1n, null, 9007199254740993n]);
+ const bytes = frames.cases[2].hex.match(/../g).map(x => parseInt(x, 16));
+ const wire = rf.eval(`(de (as 'U8 [${bytes.join(' ')}]))`);
+ const observed = [duration.value.toString(), v.toJS().map(x => x === null ? null : x.toString()), wire.toJS().toString()];
+ duration.drop(); v.drop(); wire.drop();
+ return observed;
+ }, nativeFrames), ['9007199254740993', ['1', '-1', null, '9007199254740993'], '9007199254740993']);
+
+ assert.deepEqual(await main.page.evaluate((frame) => {
+ const rf = globalThis.rf;
+ const bytes = frame.hex.match(/../g).map(x => parseInt(x, 16));
+ const error = rf.eval(`(de (as 'U8 [${bytes.join(' ')}]))`);
+ const result = [error.isError, error.code, error.message]; error.drop();
+ const own = rf.eval('(ser 1)'); result.push(own.typedArray[4]); own.drop();
+ return result;
+ }, nativeFrames.cases[6]), [true, 'domain', 'wire4 exact diagnostic', 4]);
+
+ const exampleButtons = main.page.locator('.example-btn');
+ for (let index = 0; index < (await exampleButtons.count()); index += 1) {
+ const before = await main.page.locator('.output-line').count();
+ await exampleButtons.nth(index).click();
+ const output = main.page.locator('.output-line').nth(before + 1);
+ await output.waitFor();
+ const classes = (await output.getAttribute('class'))?.split(/\s+/) ?? [];
+ assert.ok(!classes.includes('error'), `expression example ${index + 1} failed: ${await output.textContent()}`);
+ }
+
+ const demos = [
+ ['demoZeroCopy', '#demo-zerocopy-result', 'Zero-copy mutation successful'],
+ ['demoTable', '#demo-table-result', 'Table created'],
+ ['demoQuery', '#demo-query-result', 'Filtered (score > 90): 2 rows'],
+ ['demoPerfTest', '#demo-perf-result', 'Benchmark complete'],
+ ['demoTypeConversion', '#demo-typeconv-result', 'Type conversion successful'],
+ ['demoAggregations', '#demo-aggr-result', 'sum:'],
+ ];
+ for (const [functionName, selector, expected] of demos) {
+ await main.page.evaluate((name) => globalThis[name](), functionName);
+ assert.match(await main.page.locator(selector).textContent(), new RegExp(expected.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
+ }
+
+ await main.page.evaluate(() => globalThis.createSampleTable());
+ assert.equal(await main.page.locator('#table-display tbody tr').count(), 5);
+ await main.page.evaluate(() => globalThis.filterTable());
+ assert.match(await main.page.locator('#table-display').textContent(), /Filtered: 4 of 5 rows/);
+ await main.page.evaluate(() => globalThis.createSampleTable());
+ await main.page.evaluate(() => globalThis.addTableRow());
+ assert.equal(await main.page.locator('#table-display tbody tr').count(), 6);
+ await main.page.evaluate(() => globalThis.groupByTable());
+ assert.match(await main.page.locator('#table-display').textContent(), /Grouped by department: 3 groups/);
+ await main.page.evaluate(() => globalThis.aggregateTable());
+ assert.match(await main.page.locator('#table-display').textContent(), /Row count:\s*6/);
+
+ assert.deepEqual(main.runtimeErrors, [], `main example page errors: ${main.runtimeErrors.join('\n')}`);
+ await main.page.close();
+
+ const minimal = await openPage('/examples/minimal.html', { cdnPackage: true });
+ await minimal.page.evaluate(() => globalThis.runDemo());
+ const output = minimal.page.locator('#output');
+ await minimal.page.waitForFunction(() => document.querySelector('#output')?.textContent.includes('= 49'));
+ const minimalText = await output.textContent();
+ assert.match(minimalText, /\(sum \[1 2 3 4 5\]\) = 15/);
+ assert.match(minimalText, /\(\(fn \[x\] \(\* x x\)\) 7\) = 49/);
+ assert.ok(!minimalText.includes('Error:'), minimalText);
+ assert.deepEqual(minimal.runtimeErrors, [], `minimal example page errors: ${minimal.runtimeErrors.join('\n')}`);
+ await minimal.page.close();
+
+ console.log('PRIVATE_FA9_WIRE4_BROWSER_PASS: duration/native4 diagnostic/writer4 plus 15 expressions, 11 demos and local-intercepted CDN');
+} finally {
+ await browser.close();
+ await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
+}
diff --git a/test-wire4.mjs b/test-wire4.mjs
new file mode 100644
index 0000000..92a00e0
--- /dev/null
+++ b/test-wire4.mjs
@@ -0,0 +1,147 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { init, Types, RayTimespan } from './dist/index.js';
+const rf = await init({ singleton: false });
+assert.equal(rf.version, '0.0.0');
+assert.equal(Types.TIMESPAN, 16);
+const minimum = -(1n << 63n);
+for (const n of [0n, 1n, -1n, 9007199254740993n, -9007199254740993n, (1n << 63n) - 1n, minimum]) {
+ const a = rf.timespan(n);
+ assert.ok(a instanceof RayTimespan);
+ assert.equal(a.type, -16);
+ assert.equal(a.value, n);
+ assert.equal(a.isNull, n === minimum);
+ assert.equal(a.toJS(), n === minimum ? null : n);
+ a.drop();
+}
+assert.throws(() => rf.timespan(9007199254740992), TypeError);
+assert.throws(() => rf.timespan(1n << 63n), RangeError);
+assert.throws(() => rf.timespan(-1.5), TypeError);
+const values = [1n, -1n, 9007199254740993n, null];
+const v = rf.vector(Types.TIMESPAN, values);
+assert.deepEqual(v.toJS(), values);
+assert.equal(v.at(2), values[2]);
+assert.equal(v.at(3), null);
+assert.equal(v.at(3, true), minimum);
+assert.deepEqual([...v.typedArray], [1n, -1n, 9007199254740993n, minimum]);
+rf.set('W6Input', v);
+assert.equal(rf.eval('(sum (nil? W6Input))').toJS(), 1);
+const oldView = v.typedArray;
+v.set(0, null);
+assert.equal(v.at(0), null);
+assert.equal(oldView[0], 1n); // the bound original keeps its backing alive
+assert.equal(rf.eval('(sum (nil? W6Input))').toJS(), 1);
+rf.set('W6Changed', v);
+assert.equal(rf.eval('(sum (nil? W6Changed))').toJS(), 2);
+v.set(0, 2n);
+assert.equal(v.at(0), 2n);
+v.drop();
+const indexedSpan = rf.eval("(.idx.hash (as 'TIMESPAN [1 2 1]))");
+assert.equal(indexedSpan.isError, false);
+rf.set('W6IndexedOriginal', indexedSpan);
+indexedSpan.set(0, 3n);
+rf.set('W6IndexedChanged', indexedSpan);
+assert.equal(rf.eval("(nil? (find W6IndexedOriginal (as 'TIMESPAN 3)))").toJS(), true);
+assert.equal(rf.eval("(find W6IndexedChanged (as 'TIMESPAN 3))").toJS(), 0);
+indexedSpan.drop();
+const empty = rf.vector(Types.TIMESPAN, []);
+assert.deepEqual(empty.toJS(), []);
+empty.drop();
+for (const [expr, expected] of [
+ ['0D00:00:00.000000001', 1n],
+ ['(- 2026.01.01D00:00:00.000000002 2026.01.01D00:00:00.000000001)', 1n],
+ ["(as 'TIMESPAN 9007199254740993)", 9007199254740993n],
+]) {
+ const a = rf.eval(expr);
+ assert.equal(a.isError, false, expr);
+ assert.equal(a.type, -16, expr);
+ assert.equal(a.toJS(), expected, expr);
+ a.drop();
+}
+// Duration null survives the engine/wrapper boundary without changing type.
+const durationNull = rf.eval("(as 'TIMESPAN 0Nl)");
+assert.equal(durationNull.type, -16);
+assert.equal(durationNull.toJS(), null);
+durationNull.drop();
+// These are real native x86_64 frames generated with ray_ser from the pinned
+// tag, not self-roundtrips or altered version bytes.
+const fixture = JSON.parse(readFileSync(new URL('./test/fixtures/core-v3.0.2-wire.json', import.meta.url)));
+assert.equal(fixture.wire, 3);
+const expected = [1, 1n, 9007199254740993n, null,
+ [1n, -1n, 9007199254740993n, null],
+ [{ duration: 1n }, { duration: -1n }, { duration: 9007199254740993n }, { duration: null }]];
+for (const [i, entry] of fixture.cases.entries()) {
+ const decoded = rf.eval(`(de (as 'U8 [${[...Buffer.from(entry.hex, 'hex')].join(' ')}]))`);
+ assert.equal(decoded.isError, false, entry.expr);
+ assert.deepEqual(i === 5 ? decoded.toRows() : decoded.toJS(), expected[i], entry.expr);
+ decoded.drop();
+}
+// Real native exact-fa9 frames, not a mutated version byte.
+const dev = JSON.parse(readFileSync(new URL('./test/fixtures/core-fa9bccfd-wire.json', import.meta.url)));
+assert.equal(dev.core, 'dev/fa9bccfd7f96b9248a39b23994f39a15d001b42c');
+assert.equal(dev.wire, 4);
+for (const [i, entry] of dev.cases.entries()) {
+ const bytes = Buffer.from(entry.hex, 'hex');
+ assert.equal(bytes[4], 4);
+ const decoded = rf.eval(`(de (as 'U8 [${[...bytes].join(' ')}]))`);
+ if (i === 6) {
+ assert.equal(decoded.isError, true);
+ assert.equal(decoded.code, 'domain');
+ assert.equal(decoded.message, 'wire4 exact diagnostic');
+ } else {
+ assert.equal(decoded.isError, false, entry.expr);
+ assert.deepEqual(i === 5 ? decoded.toRows() : decoded.toJS(), expected[i], entry.expr);
+ }
+ decoded.drop();
+}
+const oldWithError = JSON.parse(readFileSync(new URL('./test/fixtures/core-v3.0.2-wire-with-error.json', import.meta.url)));
+assert.equal(oldWithError.wire, 3);
+const oldErrorBytes = Buffer.from(oldWithError.cases[6].hex, 'hex');
+assert.equal(oldErrorBytes[4], 3); assert.equal(oldErrorBytes.length, 25);
+const previous = rf.eval('(+ 1)'); assert.equal(previous.code, 'arity');
+const oldError = rf.eval(`(de (as 'U8 [${[...oldErrorBytes].join(' ')}]))`);
+assert.equal(oldError.isError, true); assert.equal(oldError.code, 'domain');
+assert.equal(oldError.message, ''); oldError.drop(); previous.drop();
+
+const own = rf.eval('(ser 1)');
+assert.equal(own.isError, false);
+assert.equal(own.typedArray[4], 4);
+own.drop();
+// Reader range refusal is distinct from actual native v4 interoperability.
+const unsupported = Buffer.from(dev.cases[0].hex, 'hex'); unsupported[4] = 5;
+const refused = rf.eval(`(de (as 'U8 [${[...unsupported].join(' ')}]))`);
+assert.equal(refused.isError, true); assert.equal(refused.code, 'version'); refused.drop();
+for (const [expr, expectedRows] of [
+ ['(find (.idx.hash [1 2 1]) [2 1])', [1, 0]],
+ ["(find (.idx.hash ['a 'b 'a]) ['b 'a])", [1, 0]],
+]) {
+ const indexed = rf.eval(expr);
+ assert.equal(indexed.isError, false, expr);
+ assert.deepEqual(indexed.toJS(), expectedRows, expr);
+ indexed.drop();
+}
+// An x86_64 inline index is not a wasm32 pointer layout. Its column remains
+// readable but its accelerator must be ignored before examining child offsets.
+const nativeIndex = JSON.parse(readFileSync(new URL('./test/fixtures/native-v3.0.2-index.json', import.meta.url)));
+rf._wasm.FS.mkdirTree('/tmp/w6-native-index');
+for (const [name, base64] of Object.entries(nativeIndex.files)) {
+ rf._wasm.FS.writeFile(`/tmp/w6-native-index/${name}`, Buffer.from(base64, 'base64'));
+}
+const imported = rf.eval('(set W6NativeIndex (.db.splayed.get "/tmp/w6-native-index"))');
+assert.equal(imported.isError, false);
+imported.drop();
+assert.deepEqual(rf.eval("(at W6NativeIndex 'v)").toJS(), [10, 20, 10]);
+assert.equal(rf.eval("(.idx.has? (at W6NativeIndex 'v))").toJS(), false);
+assert.equal(rf.eval("(find (at W6NativeIndex 'v) 20)").toJS(), 1);
+const savedIndex = rf.eval('(.db.splayed.set "/tmp/w6-own-index" (table [v] (list (.idx.hash [10 20 10]))))');
+assert.equal(savedIndex.isError, false);
+savedIndex.drop();
+const ownColumn = rf._wasm.FS.readFile('/tmp/w6-own-index/v');
+// 32-byte column header + 24-byte values, aligned to 64, then index order at +17.
+assert.ok([129, 130, 131].includes(ownColumn[81]));
+const loadedIndex = rf.eval('(set W6OwnIndex (.db.splayed.get "/tmp/w6-own-index"))');
+assert.equal(loadedIndex.isError, false);
+loadedIndex.drop();
+assert.equal(rf.eval("(.idx.has? (at W6OwnIndex 'v))").toJS(), true);
+assert.equal(rf.eval("(find (at W6OwnIndex 'v) 20)").toJS(), 1);
+console.log('private exact-fa9 TIMESPAN, native v3/v4 frames and writer-v4 checks passed');
diff --git a/test.mjs b/test.mjs
index f7994a1..d79cc74 100644
--- a/test.mjs
+++ b/test.mjs
@@ -1,10 +1,10 @@
import assert from 'node:assert/strict';
import { init, version, Types } from './dist/index.js';
-assert.equal(version, '0.2.1');
+assert.equal(version, '0.3.0');
const rf = await init({ singleton: false });
-assert.equal(rf.version, '2.5.13');
+assert.equal(rf.version, '3.0.2');
assert.equal(rf.eval('(+ (+ 1 2) 3)').toJS(), 6);
assert.deepEqual(rf.eval('(til 5)').toJS(), [0, 1, 2, 3, 4]);
@@ -110,8 +110,9 @@ assert.deepEqual(
.execute()
.toRows()
.map(({ name }) => name),
- ['Bob', 'Carol'],
+ ['Bob'],
);
+assert.deepEqual(rf.eval('(or [false true false] (not [true false true]))').toJS(), [0, 1, 0]);
assert.throws(() => rf.col('score) injected'), /column name/);
const error = rf.eval('(+ 1)');
diff --git a/test/fixtures/README.md b/test/fixtures/README.md
new file mode 100644
index 0000000..a63839e
--- /dev/null
+++ b/test/fixtures/README.md
@@ -0,0 +1,22 @@
+# Native core compatibility fixtures
+
+Generated from unmodified released core v3.0.2, commit
+`d5a44cdb4ec33772104f466a2ca177a74b528041`, on little-endian x86_64.
+Verify that SHA before regenerating; build `make lib CC=clang` there.
+
+Compile `generate-core-frames.c` with that checkout's `include` and `src`
+include paths, linking `librayforce.a -lm -lpthread`. Run with
+`RAYFORCE_CORES=0`; stdout is `core-v3.0.2-wire.json`. These are actual
+native wire-v3 bytes, including typed NULLs and exact large durations,
+not relabelled v4 frames.
+
+Compile `generate-native-index.c` the same way and run in an empty writable
+directory. It writes `native-index-table/{.d,v}` and a transient write lock.
+Base64-encode `.d` and `v` into the `files` object of
+`native-v3.0.2-index.json`, excluding the lock. This native-layout HASH
+accelerator is deliberately ignored by wasm32 while its column values
+remain readable. Tests separately save/reload a wasm32 index with its
+own generation.
+
+Tiny synthetic fixtures, no customer data. Not general cross-version or
+filesystem-format certification.
diff --git a/test/fixtures/core-fa9bccfd-wire.json b/test/fixtures/core-fa9bccfd-wire.json
new file mode 100644
index 0000000..89545bb
--- /dev/null
+++ b/test/fixtures/core-fa9bccfd-wire.json
@@ -0,0 +1 @@
+{"core":"dev/fa9bccfd7f96b9248a39b23994f39a15d001b42c","wire":4,"cases":[{"expr":"1","hex":"fadeface040000000a00000000000000fb000100000000000000"},{"expr":"0D00:00:00.000000001","hex":"fadeface040000000a00000000000000f0000100000000000000"},{"expr":"(as 'TIMESPAN 9007199254740993)","hex":"fadeface040000000a00000000000000f0000100000000002000"},{"expr":"(as 'TIMESPAN 0Nl)","hex":"fadeface040000000a00000000000000f0010000000000000080"},{"expr":"(as 'TIMESPAN [1 -1 9007199254740993 0Nl])","hex":"fadeface040000002a00000000000000104004000000000000000100000000000000ffffffffffffffff01000000000020000000000000000080"},{"expr":"(table [duration] (list (as 'TIMESPAN [1 -1 9007199254740993 0Nl])))","hex":"fadeface04000000490000000000000062000c0301000000000000006475726174696f6e0000000100000000000000104004000000000000000100000000000000ffffffffffffffff01000000000020000000000000000080"},{"expr":"domain-error","hex":"fadeface0400000020000000000000007f646f6d61696e000016776972653420657861637420646961676e6f73746963"}]}
diff --git a/test/fixtures/core-v3.0.2-wire-with-error.json b/test/fixtures/core-v3.0.2-wire-with-error.json
new file mode 100644
index 0000000..f283f1c
--- /dev/null
+++ b/test/fixtures/core-v3.0.2-wire-with-error.json
@@ -0,0 +1 @@
+{"core":"v3.0.2/d5a44cdb4ec33772104f466a2ca177a74b528041","wire":3,"cases":[{"expr":"1","hex":"fadeface030000000a00000000000000fb000100000000000000"},{"expr":"0D00:00:00.000000001","hex":"fadeface030000000a00000000000000f0000100000000000000"},{"expr":"(as 'TIMESPAN 9007199254740993)","hex":"fadeface030000000a00000000000000f0000100000000002000"},{"expr":"(as 'TIMESPAN 0Nl)","hex":"fadeface030000000a00000000000000f0010000000000000080"},{"expr":"(as 'TIMESPAN [1 -1 9007199254740993 0Nl])","hex":"fadeface030000002a00000000000000104004000000000000000100000000000000ffffffffffffffff01000000000020000000000000000080"},{"expr":"(table [duration] (list (as 'TIMESPAN [1 -1 9007199254740993 0Nl])))","hex":"fadeface03000000490000000000000062000c0301000000000000006475726174696f6e0000000100000000000000104004000000000000000100000000000000ffffffffffffffff01000000000020000000000000000080"},{"expr":"domain-error","hex":"fadeface0300000009000000000000007f646f6d61696e0000"}]}
diff --git a/test/fixtures/core-v3.0.2-wire.json b/test/fixtures/core-v3.0.2-wire.json
new file mode 100644
index 0000000..15d54a0
--- /dev/null
+++ b/test/fixtures/core-v3.0.2-wire.json
@@ -0,0 +1 @@
+{"core":"v3.0.2/d5a44cdb4ec33772104f466a2ca177a74b528041","wire":3,"cases":[{"expr":"1","hex":"fadeface030000000a00000000000000fb000100000000000000"},{"expr":"0D00:00:00.000000001","hex":"fadeface030000000a00000000000000f0000100000000000000"},{"expr":"(as 'TIMESPAN 9007199254740993)","hex":"fadeface030000000a00000000000000f0000100000000002000"},{"expr":"(as 'TIMESPAN 0Nl)","hex":"fadeface030000000a00000000000000f0010000000000000080"},{"expr":"(as 'TIMESPAN [1 -1 9007199254740993 0Nl])","hex":"fadeface030000002a00000000000000104004000000000000000100000000000000ffffffffffffffff01000000000020000000000000000080"},{"expr":"(table [duration] (list (as 'TIMESPAN [1 -1 9007199254740993 0Nl])))","hex":"fadeface03000000490000000000000062000c0301000000000000006475726174696f6e0000000100000000000000104004000000000000000100000000000000ffffffffffffffff01000000000020000000000000000080"}]}
diff --git a/test/fixtures/generate-core-frames.c b/test/fixtures/generate-core-frames.c
new file mode 100644
index 0000000..7dfd34e
--- /dev/null
+++ b/test/fixtures/generate-core-frames.c
@@ -0,0 +1,31 @@
+#include
+#include
+#include "lang/eval.h"
+#include "store/serde.h"
+static const char* exprs[] = {
+ "1",
+ "0D00:00:00.000000001",
+ "(as 'TIMESPAN 9007199254740993)",
+ "(as 'TIMESPAN 0Nl)",
+ "(as 'TIMESPAN [1 -1 9007199254740993 0Nl])",
+ "(table [duration] (list (as 'TIMESPAN [1 -1 9007199254740993 0Nl])))"
+};
+int main(void) {
+ ray_runtime_t* rt = ray_runtime_create(0, NULL);
+ if (!rt) return 1;
+ printf("{\"core\":\"v3.0.2/d5a44cdb4ec33772104f466a2ca177a74b528041\",\"wire\":%d,\"cases\":[", RAY_SERDE_WIRE_VERSION);
+ for (size_t i = 0; i < sizeof(exprs)/sizeof(exprs[0]); i++) {
+ ray_t* obj = ray_eval_str(exprs[i]);
+ if (!obj || RAY_IS_ERR(obj)) return 2;
+ ray_t* bytes = ray_ser(obj);
+ if (!bytes || RAY_IS_ERR(bytes)) return 3;
+ printf("%s{\"expr\":\"%s\",\"hex\":\"", i ? "," : "", exprs[i]);
+ const unsigned char* data = ray_data(bytes);
+ for (int64_t j = 0; j < bytes->len; j++) printf("%02x", data[j]);
+ printf("\"}");
+ ray_release(bytes); ray_release(obj);
+ }
+ printf("]}\n");
+ ray_runtime_destroy(rt);
+ return 0;
+}
diff --git a/test/fixtures/generate-native-fa9-frames.c b/test/fixtures/generate-native-fa9-frames.c
new file mode 100644
index 0000000..7c4a75d
--- /dev/null
+++ b/test/fixtures/generate-native-fa9-frames.c
@@ -0,0 +1,34 @@
+#include
+#include
+#include "lang/eval.h"
+#include "store/serde.h"
+static const char* exprs[] = {
+ "1",
+ "0D00:00:00.000000001",
+ "(as 'TIMESPAN 9007199254740993)",
+ "(as 'TIMESPAN 0Nl)",
+ "(as 'TIMESPAN [1 -1 9007199254740993 0Nl])",
+ "(table [duration] (list (as 'TIMESPAN [1 -1 9007199254740993 0Nl])))",
+ "domain-error"
+};
+int main(void) {
+ ray_runtime_t* rt = ray_runtime_create(0, NULL);
+ if (!rt) return 1;
+ printf("{\"core\":\"dev/fa9bccfd7f96b9248a39b23994f39a15d001b42c\",\"wire\":%d,\"cases\":[", RAY_SERDE_WIRE_VERSION);
+ for (size_t i = 0; i < sizeof(exprs)/sizeof(exprs[0]); i++) {
+ bool is_error = i == sizeof(exprs)/sizeof(exprs[0]) - 1;
+ ray_t* obj = is_error ? ray_error("domain", "wire4 exact diagnostic") : ray_eval_str(exprs[i]);
+ if (!obj || (!is_error && RAY_IS_ERR(obj))) return 2;
+ ray_t* bytes = ray_ser(obj);
+ if (!bytes || RAY_IS_ERR(bytes)) return 3;
+ printf("%s{\"expr\":\"%s\",\"hex\":\"", i ? "," : "", exprs[i]);
+ const unsigned char* data = ray_data(bytes);
+ for (int64_t j = 0; j < bytes->len; j++) printf("%02x", data[j]);
+ printf("\"}");
+ ray_release(bytes);
+ if (is_error) ray_error_free(obj); else ray_release(obj);
+ }
+ printf("]}\n");
+ ray_runtime_destroy(rt);
+ return 0;
+}
diff --git a/test/fixtures/generate-native-index.c b/test/fixtures/generate-native-index.c
new file mode 100644
index 0000000..24c69c1
--- /dev/null
+++ b/test/fixtures/generate-native-index.c
@@ -0,0 +1,11 @@
+#include
+#include "lang/eval.h"
+int main(void) {
+ ray_runtime_t* rt = ray_runtime_create(0, 0);
+ if (!rt) return 1;
+ ray_t* saved = ray_eval_str("(.db.splayed.set \"native-index-table\" (table [v] (list (.idx.hash [10 20 10]))))");
+ if (!saved || RAY_IS_ERR(saved)) return 2;
+ ray_release(saved);
+ ray_runtime_destroy(rt);
+ return 0;
+}
diff --git a/test/fixtures/generate-native-v3-error-frames.c b/test/fixtures/generate-native-v3-error-frames.c
new file mode 100644
index 0000000..014d446
--- /dev/null
+++ b/test/fixtures/generate-native-v3-error-frames.c
@@ -0,0 +1,34 @@
+#include
+#include
+#include "lang/eval.h"
+#include "store/serde.h"
+static const char* exprs[] = {
+ "1",
+ "0D00:00:00.000000001",
+ "(as 'TIMESPAN 9007199254740993)",
+ "(as 'TIMESPAN 0Nl)",
+ "(as 'TIMESPAN [1 -1 9007199254740993 0Nl])",
+ "(table [duration] (list (as 'TIMESPAN [1 -1 9007199254740993 0Nl])))",
+ "domain-error"
+};
+int main(void) {
+ ray_runtime_t* rt = ray_runtime_create(0, NULL);
+ if (!rt) return 1;
+ printf("{\"core\":\"v3.0.2/d5a44cdb4ec33772104f466a2ca177a74b528041\",\"wire\":%d,\"cases\":[", RAY_SERDE_WIRE_VERSION);
+ for (size_t i = 0; i < sizeof(exprs)/sizeof(exprs[0]); i++) {
+ bool is_error = i == sizeof(exprs)/sizeof(exprs[0]) - 1;
+ ray_t* obj = is_error ? ray_error("domain", "wire4 exact diagnostic") : ray_eval_str(exprs[i]);
+ if (!obj || (!is_error && RAY_IS_ERR(obj))) return 2;
+ ray_t* bytes = ray_ser(obj);
+ if (!bytes || RAY_IS_ERR(bytes)) return 3;
+ printf("%s{\"expr\":\"%s\",\"hex\":\"", i ? "," : "", exprs[i]);
+ const unsigned char* data = ray_data(bytes);
+ for (int64_t j = 0; j < bytes->len; j++) printf("%02x", data[j]);
+ printf("\"}");
+ ray_release(bytes);
+ if (is_error) ray_error_free(obj); else ray_release(obj);
+ }
+ printf("]}\n");
+ ray_runtime_destroy(rt);
+ return 0;
+}
diff --git a/test/fixtures/native-v3.0.2-index.json b/test/fixtures/native-v3.0.2-index.json
new file mode 100644
index 0000000..42b7b99
--- /dev/null
+++ b/test/fixtures/native-v3.0.2-index.json
@@ -0,0 +1,7 @@
+{
+ "core": "v3.0.2/d5a44cdb4ec33772104f466a2ca177a74b528041",
+ "files": {
+ ".d": "AAAAAAAAAAAAAAAAAAAAAAAADQBIQVNIAQAAAAAAAAABAAAAdgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAA=",
+ "v": "WElEWAAAAAAAAAAAAAAAAAAABQAAAAAAAwAAAAAAAAAKAAAAAAAAABQAAAAAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA2EAAQAAAGAAAAAAAAAAAQAFBgAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAMAAAAAAAAAAAAEAAAAAAABAAQAAAAAAAAcAAAAAAAAAAwAAAAAAAAACAAAAAAAAAP//////////AAAAAAAAAAAAAAAAAAAAAAEGBAABAAAACAAAAAAAAAABAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBgUAAQAAAAIAAAAAAAAACgAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQYEAAEAAAADAAAAAAAAAAAAAAACAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEGBAABAAAAAwAAAAAAAAAAAAAAAgAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
+ }
+}
diff --git a/test/typed-timespan.ts b/test/typed-timespan.ts
new file mode 100644
index 0000000..85fe3a9
--- /dev/null
+++ b/test/typed-timespan.ts
@@ -0,0 +1,18 @@
+import { init, Types, RayTimespan } from '../src/index.js';
+async function check() {
+ const rf = await init();
+ const span: RayTimespan = rf.timespan(9007199254740993n);
+ const raw: bigint = span.value;
+ const result: bigint | null = span.toJS();
+ const vector = rf.vector(Types.TIMESPAN, [raw, result, null]);
+ const view: BigInt64Array = vector.typedArray;
+ const cells: Array = vector.toJS();
+ vector.set(0, null);
+ for (const cell of vector) {
+ const value: number | bigint | null = cell;
+ void value;
+ }
+ span.drop(); vector.drop();
+ return { view, cells };
+}
+void check;