diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8bd0470..7b2818d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,7 +102,7 @@ jobs: # so the server checks its own side of every exchange. (main.c itself is # compiled at the Makefile's default RELEASE_CFLAGS either way. `-DDEBUG` # reaches no struct in the public header — only the RAY_ASSERT_VALUE macro - # at rayforce.h:242 — so the two agree on layout.) + # at rayforce.h:246 — so the two agree on layout.) # # The three make variables are read back out of build.rs rather than # restated, the way scripts/check-vendored-pin.sh already reads them: the @@ -111,12 +111,20 @@ jobs: # binary instead of the core's. - name: Build the core server binary run: | - cargo build --workspace --tests - # Absolute: cargo runs each test binary with the cwd set to its own - # crate root, so a workspace-relative RAYFORCE_BINARY would not resolve. - CORE=$(ls -dt "$PWD"/target/debug/build/rayforce-sys-*/out/core 2>/dev/null | head -1) - if [ ! -f "$CORE/librayforce.a" ]; then - echo "::error::no staged core under target/debug/build — did build.rs run?"; exit 1 + # The staged core is rayforce-sys's OUT_DIR/core. Cargo names that + # OUT_DIR in its build-script-executed message, fresh build or not; + # globbing target/ for it instead broke when cargo 1.100 moved + # build/-/out to build///out, a layout cargo + # documents as its own implementation detail. The JSON goes to a + # file, not a pipe, so a failed build still fails this step. + cargo build --workspace --tests --message-format=json-render-diagnostics > "$RUNNER_TEMP/build.jsonl" + OUT=$(jq -r 'select(.reason == "build-script-executed" and (.package_id | contains("rayforce-sys"))) | .out_dir' "$RUNNER_TEMP/build.jsonl" | tail -1) + # Absolute, as cargo reports it: cargo runs each test binary with the + # cwd set to its own crate root, so a workspace-relative + # RAYFORCE_BINARY would not resolve. + CORE="$OUT/core" + if [ -z "$OUT" ] || [ ! -f "$CORE/librayforce.a" ]; then + echo "::error::cargo reported no rayforce-sys OUT_DIR holding core/librayforce.a"; exit 1 fi field() { sed -n "s/^const $1: &str = \"\(.*\)\";\$/\1/p" rayforce-sys/build.rs; } make -C "$CORE" release \ diff --git a/Cargo.toml b/Cargo.toml index de79475..d0e971d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = ["rayforce-sys", "rayforce"] [workspace.package] -version = "1.4.0" +version = "1.5.0" edition = "2021" license = "MIT" authors = ["RayforceDB"] @@ -16,4 +16,4 @@ categories = ["database", "api-bindings"] rust-version = "1.74" [workspace.dependencies] -rayforce-sys = { path = "rayforce-sys", version = "1.4.0" } +rayforce-sys = { path = "rayforce-sys", version = "1.5.0" } diff --git a/README.md b/README.md index 1b27cba..f0630c3 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ To move the pin, move both: ```sh git -C rayforce-sys/vendor/rayforce fetch --tags -git -C rayforce-sys/vendor/rayforce checkout v3.0.1 +git -C rayforce-sys/vendor/rayforce checkout v3.0.2 git add rayforce-sys/vendor/rayforce git -C rayforce-sys/vendor/rayforce rev-parse --short=7 HEAD # CORE_COMMIT @@ -137,6 +137,11 @@ $EDITOR rayforce-sys/build.rs # CORE_VERSION, C cargo test --workspace ``` +The pin may also be a commit of the core's `dev` branch, between releases. Then +`CORE_VERSION` is the newest release that commit contains, what the core's own Makefile +stamps on it (release tags sit on `master`, so `git describe` would name an older one), and +the check asserts that it is. + `rayforce-sys/vendor/rayforce-q` works the same way, minus the constants — nothing is stamped from it. The build script needs rayforce-q 2.5.0 or later, the first with `q_decode_cols`, and names the version when a checkout is older. diff --git a/docs/docs/content/CHANGELOG.md b/docs/docs/content/CHANGELOG.md index 6d2aed3..ee3bebc 100644 --- a/docs/docs/content/CHANGELOG.md +++ b/docs/docs/content/CHANGELOG.md @@ -3,7 +3,7 @@ All notable changes to `rayforce` are documented here. This project adheres to [Semantic Versioning](https://semver.org). -## Unreleased +## 1.5.0 ### Added @@ -15,6 +15,101 @@ All notable changes to `rayforce` are documented here. This project adheres to C side reads 0 as no timeout or as the default keepalive, and so is either past `i32::MAX` milliseconds. `rayforce-sys` binds `q_connect_opts` and the `Q_KEEPALIVE_*` constants. +- **Timespan values.** The core's `TIMESPAN` (type 16), a signed duration in + nanoseconds, is what subtracting two timestamps yields. `Value::timespan_nanos` + builds an atom and `as_timespan_nanos` reads one; `timespan_nanos_slice` + views a vector's `&[i64]`. With the `chrono` feature, `chrono::Duration` + converts both ways; past the ±~292 years an i64 of nanoseconds holds, it + saturates to that limit, never to `i64::MIN`, which is the null. A null + timespan atom is `None` as `Option`. + +### Changed + +- **Native IPC speaks wire version 4 and refuses 3: upgrade both ends + together.** The core now sends a remote error's message across the wire + with its code (core #1107), so a `TcpClient` error reads as the server's + (`type: cannot add i64 and sym`, where it carried the code alone). The + handshake requires the same version on both sides, so a `TcpClient` built on + this release cannot connect to a v3.0.x or older server, failing with + `wire version mismatch`, and a client on an older core cannot connect to + `Poll::serve_ipc`. The Q wire is unaffected. + +- **The vendored core is dev `e6deb32`, from v3.0.1 (`0aa2d6a`).** The core + has released nothing since v3.0.2, so this pins a commit of its `dev` branch: + v3.0.2 plus 248 commits, 32 features, 54 performance changes and 176 fixes + past v3.0.1's sources. `CORE_VERSION` is `3.0.2`, the newest release the + commit contains, which is what the core's own Makefile stamps on it, so + `.sys.build` reports version 3.0.2. + `scripts/check-vendored-pin.sh` and CI accept such a pin, and still refuse a + `CORE_VERSION` the commit does not contain or one older than a release it + does. What reaches this crate besides the wire version: + - A native connection to a server on the same host moves from TCP to + shared-memory rings once the handshake agrees (core #1046), and across + hosts to RDMA where both sides have it. `TcpClient` connections do this by + default, as the suite now exercises; `rt.eval("(.ipc.transport 'tcp)")` + keeps this process on TCP. The RDMA transport is compiled in when `make + lib` finds the verbs headers (`libibverbs-dev`) and then `dlopen`s the + library, so `rayforce-sys` now links `-ldl` on Linux, as the core's own + Makefile does (glibc 2.34 and later have it in libc). + - `include/rayforce.h` grows: `RAY_ERR_ACCESS`, an evaluation refused in + restricted mode (`ErrorCode::Other`, code string `access`); the heap's + anon watermark (`ray_heap_set_anon_watermark`, `ray_heap_anon_watermark`, + `ray_heap_anon_peak`); one password for every listener on a poll + (`ray_poll_auth_set`, `ray_poll_auth_check`, `ray_poll_auth_restricted`, + `RAY_POLL_AUTH_API`); and `ray_error_msg_set`, `ray_error_usage` and + `ray_error_usage_set`. `rayforce-sys` binds them all; the safe crate wraps + none yet. Of the private layouts the bindings carry, `ray_selector` gains + three trailing transport fields and `ray_ipc_tx_info_t` a `transport` byte. + The nineteen `INTERNAL_FNS` signatures are unchanged. + - Rayfall changes a caller can see: `TIME - TIME` is a timespan; a builtin + called with the wrong arguments names the ones it expects; a `try` handler + gets `{code msg}` for an engine error, not 0; an explicit cast to I16, + I32, DATE or TIME that lands on the minimum is null. + - Engine highlights: `.json.parse`/`.json.get`/`.json.format`; `mmu`, + `inv`, `lsq` and `gram` on lists of numeric rows; parquet LZ4, UINT64 and + DECIMAL columns and multi-file `.parquet.parted`; `union-all` over parted + tables; timestamp partition keys and partition pruning by column + statistics; a GUID hash index; `.sys.profile` and `.sys.trust`; and + faster grouping, joins, finds and parquet imports. + +- **rayforce-q is 2.7.0 (`8bab7ec`), from 2.6.0 (`69b4210`).** What reaches + this crate: + - A q timespan decodes to a timespan, and a timespan encodes as q's. Before, + `q::decode_response` and `QConnection::execute` refused a message holding + one (`q: unsupported wire type`), and `q::encode` could not send one. + - **A table's text column decodes as a string vector** (`RAY_STR`, type 13) + where it was a list of string atoms (type 0). `get(i)` still yields string + atoms, but `is_list()` is now false, so **code that read a q text column as + a list needs updating**. A text column whose every cell is one character, + which q sends as one char vector, now decodes instead of failing. + - `q::decode_response_cols` returns text columns as `decode_response` does. + rayforce-q 2.7.0's `q_decode_cols` skips that conversion, so this crate + applies it to the projected table: plain, or a keyed table's value side. + One shape it cannot repair: a kept one-character text column still fails + inside rayforce-q (`domain: table add_col: column must be + list/vector-like`), though `decode_response` decodes it. A fix is on + rayforce-q branch `fix/decode-cols-text-columns`. + - A `Poll::serve_q` listener sends an error's text to the q client + (`'type: cannot add i64 and str`, and a raised value as raised), where only + the category went. An empty request is answered with `(::)` rather than a + parse error. A sync request is evaluated as data, with every list argument + quoted, so a list argument whose head names a function reaches the handler + as the list, where it used to be called. Replies are written directly, with + `TCP_NODELAY`, and a hard send failure closes the connection. + - `QConnection::connect_with` with an empty user and a password sends + `:password`, where it sent the anonymous handshake. + - rayforce-q's hooks, `.q.post`, `.q.readonly` and `q_serve_at` are not + exposed here. + +### Fixed + +- **A timespan vector is a vector.** `Value::is_vec` stopped at type 13 while + the core's `ray_is_vector_type` also counts 16, so a timespan vector reported + `len() == 0`, `get` refused it as "not a vector or list", and + `is_null_at` was always false. All three now treat it as the core does, and + an `i64::MIN` timespan atom is `is_atom_null`. Rayfall could already produce + one since core v3.0.1 (1.4.0); with rayforce-q 2.7.0 a q timespan decodes to + one too. ## 1.4.0 diff --git a/docs/docs/content/documentation/data-types/overview.md b/docs/docs/content/documentation/data-types/overview.md index 72f52cf..2b7d094 100644 --- a/docs/docs/content/documentation/data-types/overview.md +++ b/docs/docs/content/documentation/data-types/overview.md @@ -54,6 +54,7 @@ The atom code and its vector code are mirror images: an `I64` atom is `-5`, an | [GUID](guid.md) | 11 | `Value::guid(&[u8;16])` | — | `as_guid` | | [Symbol](symbol.md) | 12 | `Value::sym(&str)` | `Value::sym_vec(&[..])` | `as_sym` | | [String](string.md) | 13 | `Value::string(&str)` | `Value::str_vec(&[..])` | `as_string` | +| [Timespan](temporal.md) | 16 | `Value::timespan_nanos(i64)` | — | `as_timespan_nanos` / `timespan_nanos_slice` | | [List](list.md) | 0 | `Value::list(&[..])` | — | `get` | | [Dict](dict.md) | 99 | `Value::dict(keys, values)` | — | `dict_get` | | [Table](../table/overview.md) | 98 | `Table::new(..)` | — | `column(..)` | diff --git a/docs/docs/content/documentation/data-types/temporal.md b/docs/docs/content/documentation/data-types/temporal.md index e54d97b..d25e726 100644 --- a/docs/docs/content/documentation/data-types/temporal.md +++ b/docs/docs/content/documentation/data-types/temporal.md @@ -1,12 +1,14 @@ # :material-clock-outline: Temporal -Rayforce has three temporal types, all measured against a **2000-01-01** epoch: +Rayforce has three temporal types measured against a **2000-01-01** epoch, and +a timespan, a signed duration: | Type | Unit | Atom constructor | Reader | Slice reader | |------|------|------------------|--------|--------------| | `Date` | days since 2000-01-01 | `Value::date_days(i32)` | `as_date_days` | `date_days_slice` | | `Time` | milliseconds since midnight | `Value::time_millis(i32)` | `as_time_millis` | `time_millis_slice` | | `Timestamp` | nanoseconds since 2000-01-01 UTC | `Value::timestamp_nanos(i64)` | `as_timestamp_nanos` | `timestamp_nanos_slice` | +| `Timespan` | nanoseconds, signed | `Value::timespan_nanos(i64)` | `as_timespan_nanos` | `timespan_nanos_slice` | !!! note "Assume a live runtime" ```rust @@ -27,10 +29,14 @@ assert_eq!( Value::timestamp_nanos(1_000_000_000).as_timestamp_nanos()?, 1_000_000_000, ); +assert_eq!(Value::timespan_nanos(-1_500).as_timespan_nanos()?, -1_500); ``` Note the widths: `Date` and `Time` carry an `i32` offset, while `Timestamp` -carries an `i64` (nanoseconds need the extra range). +and `Timespan` carry an `i64` (nanoseconds need the extra range). + +A timespan is what subtracting two timestamps yields, and what a q timespan +decodes to. Its null is `i64::MIN`, as for a timestamp. ## Chrono conversions @@ -49,10 +55,15 @@ assert_eq!(t.to_value().extract::()?, t); let ts = Utc.with_ymd_and_hms(2021, 6, 15, 13, 30, 45).unwrap(); assert_eq!(ts.to_value().extract::>()?, ts); + +let span = chrono::Duration::milliseconds(-250); +assert_eq!(span.to_value().extract::()?, span); ``` -The mapping is `NaiveDate` ↔ `Date`, `NaiveTime` ↔ `Time`, and -`DateTime` ↔ `Timestamp`. +The mapping is `NaiveDate` ↔ `Date`, `NaiveTime` ↔ `Time`, +`DateTime` ↔ `Timestamp`, and `chrono::Duration` ↔ `Timespan`. A +`chrono::Duration` past the ±~292 years an i64 of nanoseconds holds +saturates to that limit. ## Slice readers @@ -66,7 +77,7 @@ assert!(v.timestamp_nanos_slice().is_err()); ``` - `date_days_slice()` and `time_millis_slice()` return `&[i32]`. -- `timestamp_nanos_slice()` returns `&[i64]`. +- `timestamp_nanos_slice()` and `timespan_nanos_slice()` return `&[i64]`. !!! tip "Everything is relative to 2000-01-01" Unlike Unix time (epoch 1970), Rayforce dates and timestamps count from diff --git a/docs/docs/content/get-started/installation.md b/docs/docs/content/get-started/installation.md index 94f4b42..d169e93 100644 --- a/docs/docs/content/get-started/installation.md +++ b/docs/docs/content/get-started/installation.md @@ -34,10 +34,10 @@ places that must agree: | The core sources | the `rayforce-sys/vendor/rayforce` submodule | | The version stamped into the library | `CORE_VERSION` / `CORE_COMMIT` in `rayforce-sys/build.rs` | -The constants exist because the core's `Makefile` normally resolves its version -from `git describe`, and a crate unpacked from crates.io has no git history to -read. `scripts/check-vendored-pin.sh` asserts the two agree, and CI runs it on -every push. +The constants exist because the core's `Makefile` normally takes its version +from the newest `vX.Y.Z` tag of its repository, and a crate unpacked from +crates.io has no git history to read. `scripts/check-vendored-pin.sh` asserts +the two agree, and CI runs it on every push. As a consumer you get the core that matches the `rayforce` version you depend on — pick a different core by picking a different `rayforce` release. The two @@ -77,11 +77,11 @@ Moving the pin means moving the submodule and the constants together: ```sh # 1. Move the submodule to the new tag. git -C rayforce-sys/vendor/rayforce fetch --tags -git -C rayforce-sys/vendor/rayforce checkout v3.0.1 +git -C rayforce-sys/vendor/rayforce checkout v3.0.2 git add rayforce-sys/vendor/rayforce # 2. Read back the values build.rs must stamp. -git -C rayforce-sys/vendor/rayforce describe --tags --exact-match # -> v3.0.1 +git -C rayforce-sys/vendor/rayforce describe --tags --exact-match # -> v3.0.2 git -C rayforce-sys/vendor/rayforce rev-parse --short=7 HEAD # -> e.g. 1a2b3c4 ``` @@ -89,7 +89,7 @@ Then edit `rayforce-sys/build.rs` to match — `CORE_VERSION` is the tag without its leading `v`: ```rust -const CORE_VERSION: &str = "3.0.1"; +const CORE_VERSION: &str = "3.0.2"; const CORE_COMMIT: &str = "1a2b3c4"; ``` @@ -100,6 +100,14 @@ And check the result: cargo test --workspace ``` +Between releases the pin can be a commit of the core's `dev` branch instead of +a tag. `CORE_COMMIT` is that commit, and `CORE_VERSION` the newest release it +contains, which is what the core's own `Makefile` stamps on it. Release tags +sit on `master`, so a release counts as contained when its commit is an +ancestor of the pin, or when the release commit's parent with the same tree is: +a `dev` → `master` merge before the core merges it back. The check fails when +the pin contains no release under `CORE_VERSION`, or contains a newer one. + The same applies to `rayforce-sys/vendor/rayforce-q`, minus the constants — nothing is stamped from it, so moving the submodule is the whole change. diff --git a/docs/docs/content/get-started/technical-details.md b/docs/docs/content/get-started/technical-details.md index be747c2..9cf5531 100644 --- a/docs/docs/content/get-started/technical-details.md +++ b/docs/docs/content/get-started/technical-details.md @@ -136,7 +136,8 @@ Runtime::scope(|_rt| { ``` The same applies to the typed slice readers for temporal and boolean columns -(`date_days_slice`, `time_millis_slice`, `timestamp_nanos_slice`, `bool_slice`). +(`date_days_slice`, `time_millis_slice`, `timestamp_nanos_slice`, +`timespan_nanos_slice`, `bool_slice`). ## :material-arrow-right: Next steps diff --git a/rayforce-sys/build.rs b/rayforce-sys/build.rs index be7daea..c8920c5 100644 --- a/rayforce-sys/build.rs +++ b/rayforce-sys/build.rs @@ -18,30 +18,38 @@ use std::path::{Path, PathBuf}; use std::process::Command; /// Version stamped into the vendored core at compile time. The core's Makefile -/// normally resolves this from `git describe` (`Makefile:19`), but a crate -/// unpacked from crates.io has no git history — without this the core would -/// report itself as `0.0.0`. +/// normally takes the newest `vX.Y.Z` tag of its repository (`Makefile:26`), +/// but a crate unpacked from crates.io has no git history — without this the +/// core would report itself as `0.0.0`. /// -/// Must match the tag `vendor/rayforce` is pinned to. CI asserts the two agree; -/// see the "Check vendored core pin" step in `.github/workflows/ci.yml`. -const CORE_VERSION: &str = "3.0.1"; +/// When `vendor/rayforce` is pinned to a release, this is that release's tag. +/// When it is pinned to a `dev` commit, as now, it is the newest release that +/// commit contains, which is what the core's own Makefile stamps on it. +/// Release tags sit on `master`: a dev commit contains one when the release +/// commit is in its history, or the release commit's parent with the same +/// tree, the release PR's head, is. CI asserts either form, see +/// `scripts/check-vendored-pin.sh` and the "Check vendored core pin" step in +/// `.github/workflows/ci.yml`. +const CORE_VERSION: &str = "3.0.2"; /// Commit the `vendor/rayforce` submodule is pinned to, stamped alongside /// [`CORE_VERSION`]. Also checked by CI's "Check vendored core pin" step. /// /// This must be passed explicitly for the same reason as the version, and for -/// one more: `Makefile:27` resolves it with `git rev-parse --short HEAD`, and +/// one more: `Makefile:34` resolves it with `git rev-parse --short HEAD`, and /// git searches *upward* from the working directory. Since the core is built /// under OUT_DIR, an unset value does not fall back to "unknown" — it silently /// reports the HEAD of whatever unrelated repository happens to enclose the /// build directory. -const CORE_COMMIT: &str = "0aa2d6a"; +const CORE_COMMIT: &str = "e6deb32"; -/// Warning flags for the vendored core build — the core's own `WARNS` -/// (`Makefile:35`) minus `-Werror`. Consumers compile this with whatever +/// Warning flags for the vendored core build — the core's own `WARNS_BASE` +/// (`Makefile:44`) minus `-Werror`. Consumers compile this with whatever /// toolchain they happen to have, and a new diagnostic from a future compiler /// should not be a hard failure inside someone else's dependency tree. The -/// core's own CI is where `-Werror` belongs. +/// core's own CI is where `-Werror` belongs. (Its `WARNS`, `Makefile:59`, adds +/// a demotion of clang's AVX10 feature-promotion warning that only matters +/// under `-Werror`.) const CORE_WARNS: &str = "-Wall -Wextra -Wstrict-prototypes -Wno-unused-parameter"; /// Core headers outside `include/` that declare [`INTERNAL_FNS`]. Private to @@ -191,8 +199,13 @@ fn main() { println!("cargo:rustc-link-search=native={}", core.display()); println!("cargo:rustc-link-lib=static=rayforce"); println!("cargo:rustc-link-lib=dylib=m"); - if cfg!(target_os = "linux") { + // The target's OS, not the host's that `cfg!` in a build script reads. + if env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "linux") { println!("cargo:rustc-link-lib=dylib=pthread"); + // The core's RDMA transport (src/core/rdma.c) dlopens the verbs library + // at run time when `make lib` found its headers, and glibc before 2.34 + // keeps dlopen in libdl. The core's own Linux LIBS carry -ldl for it. + println!("cargo:rustc-link-lib=dylib=dl"); } // Expose the staged core dir to downstream crates (e.g. for symfile // fixtures) — this is where librayforce.a and the headers actually live. @@ -204,19 +217,19 @@ fn main() { .clang_arg(format!("-I{}", include.display())) .clang_arg(format!("-I{}", core.join("src").display())) // Everything the public header declares. This bound is load-bearing: - // the private headers added below declare ~700 functions and ~100 RAY_* + // the private headers added below declare ~800 functions and ~120 RAY_* // constants between them, so a blanket `ray_.*` would drag in the whole // internal surface. Anchored loosely because the staged path lives under // OUT_DIR, which may itself contain regex metacharacters. .allowlist_file(".*/include/rayforce\\.h") - // The public header leaves ray_runtime_s incomplete (`rayforce.h:771`) - // and `core/runtime.h:156` completes it. Left alone, bindgen would + // The public header leaves ray_runtime_s incomplete (`rayforce.h:843`) + // and `core/runtime.h:172` completes it. Left alone, bindgen would // publish the runtime internals — ray_vm_t and friends, ~67 KB of // private layout that would then churn on every core bump. Opaque // keeps it a handle, which is all the public API ever passes around. .opaque_type("ray_runtime_s") - // The same for the poll: `rayforce.h:800` leaves `struct ray_poll` - // incomplete and `core/poll.h:108` completes it, and left alone it + // The same for the poll: `rayforce.h:872` leaves `struct ray_poll` + // incomplete and `core/poll.h:171` completes it, and left alone it // would publish the selector table and every type it reaches. .opaque_type("ray_poll") // ray_t is a union with a flexible array member + nested anon structs; @@ -285,8 +298,8 @@ fn out_dir() -> PathBuf { /// Mirror the parts of the vendored core that `make lib` needs into /// `OUT_DIR/core`, and return that path. /// -/// The core's Makefile builds strictly in-tree — `Makefile:168` names objects -/// `src//.rel.o` and `Makefile:238` drops `librayforce.a` at the +/// The core's Makefile builds strictly in-tree — `Makefile:271` names objects +/// `src//.lib.o` and `Makefile:324` drops `librayforce.a` at the /// root — so running it where the sources sit would write into the crate's own /// directory. For a crates.io consumer that is the shared registry cache, and /// it is what makes `cargo package`'s verify step fail with "files added". @@ -350,7 +363,7 @@ fn is_current(from: &Path, to: &Path) -> bool { /// Delete staged sources that no longer exist upstream. Without this, a file /// dropped by a core version bump would linger in OUT_DIR and still be compiled -/// in via the Makefile's `$(wildcard src/*/*.c)` (`Makefile:159`). Only `.c` / +/// in via the Makefile's `$(wildcard src/*/*.c)` (`Makefile:221`). Only `.c` / /// `.h` are considered, so the objects and archive built here survive. fn prune_stale(dst: &Path, staged: &HashSet) { for root in [dst.join("src"), dst.join("include")] { @@ -381,7 +394,7 @@ fn walk(root: &Path, visit: &mut dyn FnMut(&Path)) { } /// Drop the compiled objects when the flags stamped into them change. The -/// Makefile tracks header dependencies (`Makefile:44`) but not flag changes, +/// Makefile tracks header dependencies (`Makefile:69`) but not flag changes, /// so editing [`CORE_VERSION`] on its own would otherwise leave the previous /// string baked into objects that `make` still considers up to date. /// @@ -442,7 +455,7 @@ fn sanitize_libclang_path() { /// /// `Release` is the default and what every published build uses. `Debug` adds /// `-DDEBUG`, which compiles in the core's invariant checks and its stale -/// retain/release detector (`ray_dfd_check_live` in `src/mem/cow.c`) — the only +/// retain/release detector (`ray_dfd_check_live` in `src/mem/heap.c`) — the only /// tool that can see a use-after-free inside the engine's `mmap`-backed pool /// allocator, which ASan and Valgrind are structurally blind to. Opt in with /// `RAYFORCE_CORE_DEBUG=1`, then run with `RAY_DFD=1` to arm the detector. diff --git a/rayforce-sys/src/lib.rs b/rayforce-sys/src/lib.rs index 0ec456a..a666506 100644 --- a/rayforce-sys/src/lib.rs +++ b/rayforce-sys/src/lib.rs @@ -66,12 +66,17 @@ extern "C" { /// As [`q_decode`], but a table comes back with only the `ncols` columns /// named in `cols`, in the order named (q's `cols#t`). The other columns /// are skipped by their serialized length: nothing is allocated or - /// interned for them, and a column `q_decode` rejects (a timespan) can be - /// skipped. For a keyed table the key comes back whole and the names pick - /// among the value columns. A name the table lacks is a `RAY_ERROR` naming - /// it; a null or repeated name returns null with `err` set. With - /// `ncols == 0`, or a message that is not a table, this is `q_decode`. - /// Since rayforce-q 2.5.0. Engine thread only. + /// interned for them, and nothing is checked beyond that length. For a + /// keyed table the key comes back whole and the names pick among the value + /// columns. A name the table lacks is a `RAY_ERROR` naming it; a null or + /// repeated name returns null with `err` set. With `ncols == 0`, or a + /// message that is not a table, this is `q_decode`. Since rayforce-q 2.5.0. + /// Engine thread only. + /// + /// In rayforce-q 2.7.0 the projected table's text columns are not turned + /// into `RAY_STR` vectors as `q_decode` turns them: a general list of char + /// vectors stays a `RAY_LIST` of string atoms, and a single char vector + /// (every cell one character) fails the table build. pub fn q_decode_cols( resp: *mut u8, resp_len: i64, diff --git a/rayforce-sys/vendor/rayforce b/rayforce-sys/vendor/rayforce index 0aa2d6a..e6deb32 160000 --- a/rayforce-sys/vendor/rayforce +++ b/rayforce-sys/vendor/rayforce @@ -1 +1 @@ -Subproject commit 0aa2d6afae56e8bb32e76d2739eb090f2a7e933e +Subproject commit e6deb326f91299a7f3e983a2ce582892dc9f4200 diff --git a/rayforce-sys/vendor/rayforce-q b/rayforce-sys/vendor/rayforce-q index 69b4210..8bab7ec 160000 --- a/rayforce-sys/vendor/rayforce-q +++ b/rayforce-sys/vendor/rayforce-q @@ -1 +1 @@ -Subproject commit 69b4210572c14669e49d261560900e83754278ec +Subproject commit 8bab7ec7fe31d9ea51a78d6eb9a4ca355683d37c diff --git a/rayforce/src/convert.rs b/rayforce/src/convert.rs index 3f6c8b9..aec0429 100644 --- a/rayforce/src/convert.rs +++ b/rayforce/src/convert.rs @@ -4,7 +4,8 @@ //! [`ToValue`] builds a `Value` from a Rust value; [`FromValue`] extracts one. //! Bare `&str`/`String` map to **symbols** (matching the Python bindings); wrap //! in [`Str`] for a string atom. [`Guid`] carries 16 raw bytes. With the -//! `chrono` feature, date/time/timestamp types convert directly. +//! `chrono` feature, date/time/timestamp types convert directly, and a +//! timespan converts to and from `chrono::Duration`. // `RayError` is only constructed by the chrono conversions below. #[cfg(feature = "chrono")] @@ -233,6 +234,22 @@ mod chrono_impls { } } + /// A timespan atom. The engine's timespan is i64 nanoseconds (±~292 + /// years), which a `chrono::Duration` can exceed; such a duration + /// saturates toward the limit, never reaching `i64::MIN`, the null. + impl ToValue for chrono::Duration { + fn to_value(&self) -> Value { + let ns = self + .num_nanoseconds() + .unwrap_or(if *self < chrono::Duration::zero() { + i64::MIN + 1 + } else { + i64::MAX + }); + Value::timespan_nanos(ns) + } + } + impl FromValue for NaiveDate { fn from_value(v: &Value) -> Result { let days = v.as_date_days()?; @@ -257,6 +274,14 @@ mod chrono_impls { .ok_or_else(|| RayError::binding("timestamp out of range")) } } + /// Every i64 nanosecond count fits a `chrono::Duration`. Extract a column + /// that may hold nulls as `Option`: a null element boxes + /// as the untyped null, which is `None` there and an `Err` here. + impl FromValue for chrono::Duration { + fn from_value(v: &Value) -> Result { + Ok(chrono::Duration::nanoseconds(v.as_timespan_nanos()?)) + } + } // Silence unused-import warnings when only some traits are exercised. #[allow(unused_imports)] diff --git a/rayforce/src/q.rs b/rayforce/src/q.rs index eaf4610..fca57ee 100644 --- a/rayforce/src/q.rs +++ b/rayforce/src/q.rs @@ -1,8 +1,8 @@ //! Q IPC client — connect to a Q server, send a query, get the response decoded //! into a rayforce [`Value`]. //! -//! Wraps the `rayforce-q` client (`q.c`/`q.h`), built by `rayforce-sys` from a -//! local checkout (env `RAYFORCE_Q_SRC`, default `~/rayforce-q`). Requires a +//! Wraps the `rayforce-q` client (`q.c`/`q.h`), built by `rayforce-sys` from +//! the copy it vendors, or from a checkout `RAYFORCE_Q_SRC` names. Requires a //! live [`crate::Runtime`]. //! //! [`QConnection`] is sync request/reply. To *receive* — a tickerplant or a @@ -666,8 +666,8 @@ pub fn decode_response(msg: &[u8]) -> Result { /// q's `` cols#t `` does. The others are skipped by their serialized length: /// no string is built for a cell of a string column and no symbol of a symbol /// column is interned, so a caller that lands a few columns of a wide table no -/// longer pays for all of them. Skipping reads only lengths, so a column -/// [`decode_response`] rejects, a timespan, can be skipped. +/// longer pays for all of them. Skipping reads only lengths, so a skipped +/// column is never checked beyond its length. /// /// ```no_run /// # use rayforce::{q, Runtime, Table}; @@ -694,6 +694,13 @@ pub fn decode_response(msg: &[u8]) -> Result { /// an `Err` either way. /// - A compressed message is still decompressed whole: q's compression does /// not let a reader skip, so the saving starts after it. +/// - A text column, q's general list of char vectors, comes back as a string +/// vector (`RAY_STR`), as [`decode_response`] returns it. rayforce-q 2.7.0 +/// leaves it a list of string atoms here, and this converts it. One shape +/// that rayforce-q 2.7.0 cannot project: a text column whose every cell is +/// one character, which q sends as a single char vector, is an `Err` +/// (`` domain: table add_col: column must be list/vector-like ``), though +/// [`decode_response`] decodes it. /// /// Needs `rayforce-q` 2.5.0 or later. Like [`decode_response`], it must run on /// the thread that owns the [`crate::Runtime`]. @@ -725,7 +732,113 @@ pub fn decode_response_cols>(msg: &[u8], cols: &[S]) -> Result Result { + if v.type_code() == sys::RAY_TABLE as i8 { + return Ok(str_columns(&v)?.unwrap_or(v)); + } + if v.is_list() && v.len() == 2 { + let key = v.get(0)?; + let val = v.get(1)?; + if key.type_code() == sys::RAY_TABLE as i8 && val.type_code() == sys::RAY_TABLE as i8 { + if let Some(val) = str_columns(&val)? { + return Ok(Value::list(&[key, val])); + } + } + } + Ok(v) +} + +/// The table `tbl` with each column [`str_vector`] converts replaced by its +/// conversion, or `None` when no column converts. The other columns are shared +/// with `tbl`, not copied. +fn str_columns(tbl: &Value) -> Result> { + let t = tbl.as_ptr(); + let ncols = unsafe { sys::ray_table_ncols(t) }; + let mut cols = Vec::with_capacity(ncols.max(0) as usize); + let mut converted = false; + for i in 0..ncols { + let col = unsafe { sys::ray_table_get_col_idx(t, i) }; + // As `Table::column_at`: a column that does not resolve leaves the + // table as it was decoded. + if col.is_null() || unsafe { crate::raw::is_err(col) } { + return Ok(None); + } + let col = unsafe { Value::from_borrowed(col) }; + match str_vector(&col)? { + Some(s) => { + converted = true; + cols.push(s); + } + None => cols.push(col), + } + } + if !converted { + return Ok(None); + } + unsafe { + let mut out = check(sys::ray_table_new(ncols))?; + for (i, col) in cols.iter().enumerate() { + // ray_table_add_col retains `col`, and on error releases `out`. + out = check(sys::ray_table_add_col( + out, + sys::ray_table_col_name(t, i as i64), + col.as_ptr(), + ))?; + } + Ok(Some(Value::from_owned(out))) + } +} + +/// `col` as a `RAY_STR` vector when it is a non-empty list of string atoms, +/// else `None`. +fn str_vector(col: &Value) -> Result> { + if !col.is_list() || col.is_empty() { + return Ok(None); + } + let n = col.len(); + let mut items = Vec::with_capacity(n); + for i in 0..n { + let item = unsafe { sys::ray_list_get(col.as_ptr(), i as i64) }; + if item.is_null() || unsafe { crate::raw::type_code(item) } != -(sys::RAY_STR as i8) { + return Ok(None); + } + items.push(item); + } + unsafe { + let mut out = Value::from_owned(check(sys::ray_vec_new(sys::RAY_STR as i8, n as i64))?); + for item in items { + // `col` holds `item` alive. ray_str_vec_append consumes the + // vector it is given and returns the one to keep. On an error it + // leaves the vector it was given alive; as at the crate's other + // consuming calls (`install_mutation`), that one is let go rather + // than risk a double release. + let next = sys::ray_str_vec_append( + out.into_raw(), + sys::ray_str_ptr(item), + sys::ray_str_len(item), + ); + out = Value::from_owned(check(next)?); + } + Ok(Some(out)) + } } /// Check the 8-byte wire header of a complete Q response message and return diff --git a/rayforce/src/raw.rs b/rayforce/src/raw.rs index a3d38b9..12f5f3e 100644 --- a/rayforce/src/raw.rs +++ b/rayforce/src/raw.rs @@ -87,10 +87,12 @@ pub(crate) unsafe fn is_atom(v: Raw) -> bool { t < 0 || t >= sys::RAY_LAMBDA as i8 } +/// Mirrors the header's inline `ray_is_vector_type`: the contiguous run of +/// vector types, plus `RAY_TIMESPAN` (16), which sits past the run. #[inline] pub(crate) unsafe fn is_vec(v: Raw) -> bool { let t = type_code(v); - t >= sys::RAY_BOOL as i8 && t <= sys::RAY_STR as i8 + (t >= sys::RAY_BOOL as i8 && t <= sys::RAY_STR as i8) || t == sys::RAY_TIMESPAN as i8 } /// Vector / list element count (reads the `len` arm of the value union). @@ -190,7 +192,7 @@ pub(crate) unsafe fn atom_is_null(v: Raw) -> bool { match (-t) as u32 { sys::RAY_F64 => as_f64(v).is_nan(), sys::RAY_F32 => (as_f64(v) as f32).is_nan(), - sys::RAY_I64 | sys::RAY_TIMESTAMP => as_i64(v) == i64::MIN, + sys::RAY_I64 | sys::RAY_TIMESTAMP | sys::RAY_TIMESPAN => as_i64(v) == i64::MIN, sys::RAY_I32 | sys::RAY_DATE | sys::RAY_TIME => as_i32(v) == i32::MIN, sys::RAY_I16 => as_i16(v) == i16::MIN, sys::RAY_SYM => as_i64(v) == 0, diff --git a/rayforce/src/scalars.rs b/rayforce/src/scalars.rs index bca7bfd..df19d87 100644 --- a/rayforce/src/scalars.rs +++ b/rayforce/src/scalars.rs @@ -104,6 +104,13 @@ impl Value { assert_on_runtime_thread("Value::timestamp_nanos"); unsafe { own(sys::ray_timestamp(ns)) } } + /// A timespan atom: a signed duration in raw nanoseconds, what subtracting + /// two timestamps yields and how a q timespan decodes. `i64::MIN` is its + /// null. + pub fn timespan_nanos(ns: i64) -> Value { + assert_on_runtime_thread("Value::timespan_nanos"); + unsafe { own(sys::ray_timespan(ns)) } + } /// A GUID atom from 16 raw bytes. pub fn guid(bytes: &[u8; 16]) -> Value { @@ -196,6 +203,11 @@ impl Value { self.expect_atom(sys::RAY_TIMESTAMP)?; Ok(unsafe { raw::as_i64(self.as_ptr()) }) } + /// Read a timespan atom as raw nanoseconds. + pub fn as_timespan_nanos(&self) -> Result { + self.expect_atom(sys::RAY_TIMESPAN)?; + Ok(unsafe { raw::as_i64(self.as_ptr()) }) + } /// Read a GUID atom as 16 raw bytes. pub fn as_guid(&self) -> Result<[u8; 16]> { diff --git a/rayforce/src/value.rs b/rayforce/src/value.rs index db66a5b..f7e24a0 100644 --- a/rayforce/src/value.rs +++ b/rayforce/src/value.rs @@ -149,7 +149,7 @@ impl Value { unsafe { raw::is_atom(self.as_ptr()) } } - /// True for homogeneous vectors (bool…str). + /// True for homogeneous vectors (bool…str, and timespan). #[inline] pub fn is_vec(&self) -> bool { unsafe { raw::is_vec(self.as_ptr()) } diff --git a/rayforce/src/vector.rs b/rayforce/src/vector.rs index 6637736..4c3d94e 100644 --- a/rayforce/src/vector.rs +++ b/rayforce/src/vector.rs @@ -199,6 +199,11 @@ impl Value { self.raw_slice::(sys::RAY_TIMESTAMP as i8) } + /// Zero-copy view of a timespan vector as raw nanoseconds. + pub fn timespan_nanos_slice(&self) -> Result<&[i64]> { + self.raw_slice::(sys::RAY_TIMESPAN as i8) + } + /// Zero-copy slice of a vector whose element type tag equals `expected` and /// whose element width equals `size_of::()`. fn raw_slice(&self, expected: i8) -> Result<&[T]> { @@ -225,7 +230,7 @@ impl Value { /// True if element `idx` is null. /// /// Nulls are in-band. For the sentinel-encoded types (`i16`/`i32`/`i64`, - /// `f32`/`f64`, date/time/timestamp, GUID) the core first consults the + /// `f32`/`f64`, date/time/timestamp/timespan, GUID) the core first consults the /// vector's `HAS_NULLS` attribute — raised by [`Value::vec`] when the raw /// payload already holds a sentinel, and by [`Value::set_null`] — and only /// then compares the element against its sentinel (`i64::MIN`, `NaN`, the @@ -295,6 +300,7 @@ impl Value { sys::RAY_DATE => Value::date_days(*(base.add(idx * 4) as *const i32)), sys::RAY_TIME => Value::time_millis(*(base.add(idx * 4) as *const i32)), sys::RAY_TIMESTAMP => Value::timestamp_nanos(*(base.add(idx * 8) as *const i64)), + sys::RAY_TIMESPAN => Value::timespan_nanos(*(base.add(idx * 8) as *const i64)), sys::RAY_GUID => Value::guid(&*(base.add(idx * 16) as *const [u8; 16])), sys::RAY_SYM => { // A cell is a *position* in the vector's symbol domain, not a diff --git a/rayforce/tests/ipc.rs b/rayforce/tests/ipc.rs index 42ab80b..c1d76e8 100644 --- a/rayforce/tests/ipc.rs +++ b/rayforce/tests/ipc.rs @@ -158,7 +158,7 @@ fn connect_failure_names_its_cause() { /// Bind a listener that completes the TCP accept, reads the client's two-byte /// handshake, and answers with a wire version the core cannot speak. Returns -/// the port. `RAY_SERDE_WIRE_VERSION` is 3, so 0xFF is reliably wrong. +/// the port. `RAY_SERDE_WIRE_VERSION` is 4, so 0xFF is reliably wrong. fn spawn_wrong_version_peer() -> u16 { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); @@ -215,16 +215,21 @@ fn a_client_is_closed_before_its_scope_ends() { } /// Bind a listener that completes the handshake as a server without -/// authentication does — `RAY_SERDE_WIRE_VERSION` (3), then no auth required — -/// and then swallows every request without answering, until the client hangs -/// up. Returns the port. +/// authentication does, and then swallows every request without answering, +/// until the client hangs up. Returns the port. +/// +/// The reply echoes the client's wire version, the one byte a server of that +/// version answers with (`RAY_SERDE_WIRE_VERSION`, 4 since core #1107, was 3), +/// so a later bump does not turn this into a version-mismatch peer. Its second +/// byte is 0x00: no auth required and no transport capability shared, so the +/// connection stays on TCP however the client's capabilities read. fn spawn_silent_peer() -> u16 { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); std::thread::spawn(move || { if let Ok((mut sock, _)) = listener.accept() { let mut hs = [0u8; 2]; - if sock.read_exact(&mut hs).is_ok() && sock.write_all(&[3u8, 0x00]).is_ok() { + if sock.read_exact(&mut hs).is_ok() && sock.write_all(&[hs[0], 0x00]).is_ok() { let _ = std::io::copy(&mut sock, &mut std::io::sink()); } } diff --git a/rayforce/tests/ipc_serve.rs b/rayforce/tests/ipc_serve.rs index a5a2b72..2bab56b 100644 --- a/rayforce/tests/ipc_serve.rs +++ b/rayforce/tests/ipc_serve.rs @@ -209,6 +209,11 @@ fn a_cancel_from_the_client_is_reported_as_the_clients() { fn a_push_is_answered_once_the_queries_ahead_of_it_end() { // Room for the push's own round trip after the queued query's answer. const SLACK: Duration = Duration::from_millis(250); + // Each time is taken by the thread that read the answer, so two answers + // the server wrote microseconds apart can be timed in either order: one + // run in a dozen or so timed the push 0.3 ms before the query ahead of + // it. A push that did not wait would be answered seconds early. + const WAKEUP: Duration = Duration::from_millis(20); Runtime::scope(|rt| { rt.eval(TABLE)?; let poll = Poll::install()?; @@ -237,7 +242,7 @@ fn a_push_is_answered_once_the_queries_ahead_of_it_end() { }); assert_eq!(reply, (RESPONSE, long_atom(2)), "answered, not cancelled"); assert!( - push >= first, + push + WAKEUP >= first, "the push waits for the query being evaluated: {push:?} against {first:?}" ); assert!( diff --git a/rayforce/tests/q.rs b/rayforce/tests/q.rs index 93e0b10..2891ca2 100644 --- a/rayforce/tests/q.rs +++ b/rayforce/tests/q.rs @@ -42,8 +42,8 @@ fn float_vec(vals: &[f64]) -> Vec { b } -/// Timespan vector: type 16, nanoseconds as i64. `q_decode` has no branch for -/// it, so a message carrying one decodes only when the column is skipped. +/// Timespan vector: type 16, nanoseconds as i64. Since rayforce-q 2.7.0 it +/// decodes to a `RAY_TIMESPAN` vector; before, `q_decode` refused it. fn timespan_vec(vals: &[i64]) -> Vec { let mut b = vec![16u8, 0u8]; b.extend_from_slice(&(vals.len() as i32).to_le_bytes()); @@ -53,6 +53,15 @@ fn timespan_vec(vals: &[i64]) -> Vec { b } +/// Char vector: type 10. As a table column it is how q sends a text column +/// whose every cell is one character. +fn char_vec(s: &str) -> Vec { + let mut b = vec![10u8, 0u8]; + b.extend_from_slice(&(s.len() as i32).to_le_bytes()); + b.extend_from_slice(s.as_bytes()); + b +} + /// String column: a general list (type 0) of char vectors (type 10). fn string_col(vals: &[&str]) -> Vec { let mut b = vec![0u8, 0u8]; @@ -226,8 +235,7 @@ fn decode_response_rejects_non_response_messages() { // --- projected decode (q::decode_response_cols) ---------------------------- /// A five-column table of every column shape the projected decode treats -/// differently: fixed width, symbol, string, a timespan `q_decode` refuses, and -/// a float. +/// differently: fixed width, symbol, string, timespan, and a float. fn wide_table() -> Vec { table( &["seq", "sym", "note", "span", "px"], @@ -250,9 +258,6 @@ fn wire(v: &Value) -> Vec { fn decode_response_cols_keeps_the_named_columns_in_order() { Runtime::scope(|_rt| { let full = msg(&wide_table()); - // The timespan column is why the whole message cannot be decoded. - assert!(q::decode_response(&full).is_err()); - let v = q::decode_response_cols(&full, &["px", "note", "seq", "sym"]).unwrap(); let t = Table::from_value(v).unwrap(); assert_eq!(t.shape(), (3, 4)); @@ -268,6 +273,8 @@ fn decode_response_cols_keeps_the_named_columns_in_order() { let sym = t.column("sym").unwrap(); assert_eq!(sym.get(1).unwrap().as_sym().unwrap(), "MSFT"); let note = t.column("note").unwrap(); + // A string vector, as `decode_response` gives it, not a list. + assert_eq!(note.type_code(), rayforce::sys::RAY_STR as i8); assert_eq!(note.get(0).unwrap().as_string().unwrap(), "a"); assert_eq!(note.get(1).unwrap().as_string().unwrap(), "bc"); assert_eq!(note.get(2).unwrap().as_string().unwrap(), ""); @@ -303,6 +310,100 @@ fn decode_response_cols_equals_decoding_the_projection() { .unwrap(); } +#[test] +fn decode_response_decodes_a_timespan_column() { + Runtime::scope(|_rt| { + let t = Table::from_value(q::decode_response(&msg(&table( + &["span"], + &[timespan_vec(&[1_500, i64::MIN, -7])], + )))?)?; + let span = t.column("span")?; + assert_eq!(span.type_code(), rayforce::sys::RAY_TIMESPAN as i8); + assert!(span.is_vec()); + assert_eq!(span.len(), 3); + assert_eq!(span.timespan_nanos_slice()?, &[1_500, i64::MIN, -7]); + assert_eq!(span.get(0)?.as_timespan_nanos()?, 1_500); + // 0Nn is the null timespan, and its cell boxes as the untyped null. + assert!(span.is_null_at(1)); + assert!(span.get(1)?.is_null()); + assert_eq!(span.get(2)?.as_timespan_nanos()?, -7); + #[cfg(feature = "chrono")] + assert_eq!( + span.to_vec::>()?, + [ + Some(chrono::Duration::nanoseconds(1_500)), + None, + Some(chrono::Duration::nanoseconds(-7)), + ] + ); + Ok(()) + }) + .unwrap(); +} + +/// Each column of `a` and `b` has the same name, type and wire form. +fn same_columns(a: &Table, b: &Table) { + assert_eq!(a.column_names(), b.column_names()); + for (x, y) in a.columns().unwrap().iter().zip(b.columns().unwrap()) { + assert_eq!(x.type_code(), y.type_code()); + assert_eq!(wire(x), wire(&y)); + } +} + +#[test] +fn decode_response_cols_gives_a_keyed_tables_text_columns_as_decode_response_does() { + Runtime::scope(|_rt| { + let kt = msg(&keyed( + table(&["k"], &[string_col(&["x", "yz"])]), + table( + &["note", "a"], + &[string_col(&["p", "qr"]), long_vec(&[1, 2])], + ), + )); + let whole = q::decode_response(&kt)?; + let kept = q::decode_response_cols(&kt, &["note", "a"])?; + for i in 0..2 { + let w = Table::from_value(whole.get(i)?)?; + let k = Table::from_value(kept.get(i)?)?; + same_columns(&k, &w); + } + let val = Table::from_value(kept.get(1)?)?; + assert_eq!( + val.column("note")?.type_code(), + rayforce::sys::RAY_STR as i8 + ); + Ok(()) + }) + .unwrap(); +} + +/// rayforce-q 2.7.0's `q_decode_cols` builds its table without the text-column +/// step `q_decode` takes, and the Rust side can only convert what it gets back. +/// A text column whose every cell is one character travels as one char vector, +/// which that table build refuses. When rayforce-q fixes it, this fails: update +/// the `decode_response_cols` docs and flip the assertion. +#[test] +fn decode_response_cols_cannot_project_a_one_character_text_column_on_rayforce_q_2_7_0() { + Runtime::scope(|_rt| { + let m = msg(&table( + &["seq", "c"], + &[long_vec(&[1, 2, 3]), char_vec("abc")], + )); + let whole = Table::from_value(q::decode_response(&m)?)?; + let c = whole.column("c")?; + assert_eq!(c.type_code(), rayforce::sys::RAY_STR as i8); + assert_eq!(c.get(2)?.as_string()?, "c"); + + let err = q::decode_response_cols(&m, &["c"]).unwrap_err(); + assert!( + err.to_string().contains("column must be list/vector-like"), + "unexpected error: {err}" + ); + Ok(()) + }) + .unwrap(); +} + #[test] fn decode_response_cols_names_a_column_the_table_lacks() { Runtime::scope(|_rt| { diff --git a/rayforce/tests/scalars.rs b/rayforce/tests/scalars.rs index a2698a2..96359f6 100644 --- a/rayforce/tests/scalars.rs +++ b/rayforce/tests/scalars.rs @@ -84,6 +84,40 @@ fn temporal_raw_roundtrips() { .unwrap(), 1_000_000_000 ); + assert_eq!( + Value::timespan_nanos(-1_500).as_timespan_nanos().unwrap(), + -1_500 + ); + // A timespan is its own type: neither a timestamp nor an i64. + assert!(Value::timespan_nanos(1).as_timestamp_nanos().is_err()); + assert!(Value::timespan_nanos(1).as_i64().is_err()); + assert!(Value::timespan_nanos(i64::MIN).is_atom_null()); + assert!(!Value::timespan_nanos(0).is_atom_null()); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn subtracting_timestamps_yields_a_timespan() { + Runtime::scope(|_rt| { + let one = eval("(- 2000.01.02D00:00:00.000000000 2000.01.01D00:00:00.000000000)").unwrap(); + assert_eq!(one.type_code(), -(rayforce::sys::RAY_TIMESPAN as i8)); + assert_eq!(one.as_timespan_nanos().unwrap(), 86_400_000_000_000); + assert_eq!( + Value::timespan_nanos(86_400_000_000_000).format(), + one.format() + ); + + let v = eval( + "(- [2000.01.01D00:00:00.000000002 2000.01.01D00:00:00.000000005] \ + 2000.01.01D00:00:00.000000001)", + ) + .unwrap(); + assert_eq!(v.type_code(), rayforce::sys::RAY_TIMESPAN as i8); + assert_eq!(v.len(), 2); + assert_eq!(v.timespan_nanos_slice().unwrap(), &[1, 4]); + assert_eq!(v.get(1).unwrap().as_timespan_nanos().unwrap(), 4); Ok(()) }) .unwrap(); @@ -161,6 +195,20 @@ fn chrono_roundtrips() { ts.to_value().extract::>().unwrap(), ts ); + + let span = chrono::Duration::milliseconds(-250); + assert_eq!(span.to_value().as_timespan_nanos().unwrap(), -250_000_000); + assert_eq!(span.to_value().extract::().unwrap(), span); + // Past what i64 nanoseconds hold, it saturates, and never to the null. + let far = chrono::Duration::days(300 * 365); + assert_eq!(far.to_value().as_timespan_nanos().unwrap(), i64::MAX); + assert_eq!((-far).to_value().as_timespan_nanos().unwrap(), i64::MIN + 1); + assert_eq!( + Value::timespan_nanos(i64::MIN) + .extract::>() + .unwrap(), + None + ); Ok(()) }) .unwrap(); diff --git a/rayforce/tests/support/ipc.rs b/rayforce/tests/support/ipc.rs index 0970de8..9839b27 100644 --- a/rayforce/tests/support/ipc.rs +++ b/rayforce/tests/support/ipc.rs @@ -8,7 +8,10 @@ use std::net::TcpStream; use std::os::fd::AsRawFd; const PREFIX: u32 = 0xCEFA_DEFA; -const VERSION: u8 = 3; +/// The core's `RAY_SERDE_WIRE_VERSION`: 4 since core #1107, which put an +/// error's message on the wire after its code. The server drops a peer whose +/// handshake names any other version, and checks it in every frame header. +const VERSION: u8 = 4; const SYNC: u8 = 1; const STR: i8 = -13; const I64: i8 = -5; diff --git a/scripts/check-vendored-pin.sh b/scripts/check-vendored-pin.sh index 1f57750..53d617c 100755 --- a/scripts/check-vendored-pin.sh +++ b/scripts/check-vendored-pin.sh @@ -4,9 +4,24 @@ # # The build script stamps CORE_VERSION / CORE_COMMIT into librayforce.a because # a crate unpacked from crates.io has no git history for the core's Makefile to -# read them from (it resolves them via `git describe` / `git rev-parse`, see -# Makefile:19 and Makefile:27 in the core). If the constants and the submodule +# read them from (it takes the newest vX.Y.Z tag and `git rev-parse`, see +# Makefile:26 and Makefile:34 in the core). If the constants and the submodule # disagree, published crates report a version they were not built from. +# +# Two pins pass: +# +# release pin The submodule is at tag vCORE_VERSION. +# +# dev pin The submodule is at a commit of the core's dev branch, past +# every release tag. CORE_VERSION is then the newest release +# that commit contains, which is what the core's Makefile stamps +# on it. A commit contains a release when the release commit is +# its ancestor, or when a parent of the release commit with the +# same tree is: a dev -> master release merge adds no change of +# its own, and until the core merges it back into dev, only that +# parent, the release PR's head, is in dev's history. These are +# the conditions the core's own merge-back checks +# (.github/release-merge-back.sh there). set -euo pipefail root="$(cd "$(dirname "$0")/.." && pwd)" @@ -28,45 +43,115 @@ if [ ! -e "$core/include/rayforce.h" ]; then exit 1 fi -head_commit="$(git -C "$core" rev-parse HEAD)" -got_commit="$(git -C "$core" rev-parse --short="${#want_commit}" HEAD)" +g() { git -C "$core" "$@"; } -# Resolve the tag we expect and compare it to HEAD, rather than asking -# `git describe` what HEAD happens to be named. actions/checkout clones -# submodules with `git submodule update --depth=1`, and a shallow clone carries -# no tags at all, so `describe` on CI always answers "not on a tag" even when -# the pin is correct. Fetching the single tag we care about takes ~1s and makes -# the check behave the same on CI as in a full local clone. -want_tag="v$want_version" -resolve_tag() { git -C "$core" rev-parse -q --verify "refs/tags/$want_tag^{commit}" || true; } +head_commit="$(g rev-parse HEAD)" +got_commit="$(g rev-parse --short="${#want_commit}" HEAD)" +short() { g rev-parse --short="${#want_commit}" "$1"; } -tag_commit="$(resolve_tag)" -if [ -z "$tag_commit" ]; then - # --depth=1 only where the clone is already shallow: on a full local checkout - # it would leave a .git/shallow behind and truncate history nobody asked to - # lose. Either way this fetches one ref, not the tag list. - if [ "$(git -C "$core" rev-parse --is-shallow-repository)" = true ]; then - git -C "$core" fetch --depth=1 --quiet origin "refs/tags/$want_tag:refs/tags/$want_tag" || true +status=0 +if [ "$got_commit" != "$want_commit" ]; then + echo "core submodule is at $got_commit, but build.rs CORE_COMMIT expects $want_commit" >&2 + status=1 +fi + +# actions/checkout clones submodules with `git submodule update --depth=1`: one +# commit, no tags, no history. So resolve tags by ref rather than asking `git +# describe`, and fetch what a check needs, one ref at a time. Never deepen a +# full local clone (it would leave a .git/shallow behind) or fetch where the +# objects are already here. +is_shallow() { [ "$(g rev-parse --is-shallow-repository)" = true ]; } +resolve_tag() { g rev-parse -q --verify "refs/tags/$1^{commit}" || true; } + +# Fetch tag $1 with its parents, which the dev-pin check compares trees with. +fetch_tag() { + if [ -n "$(resolve_tag "$1")" ] && ! is_shallow; then + return 0 + fi + if is_shallow; then + g fetch --depth=2 --quiet origin "+refs/tags/$1:refs/tags/$1" || true else - git -C "$core" fetch --quiet origin "refs/tags/$want_tag:refs/tags/$want_tag" || true + g fetch --quiet origin "refs/tags/$1:refs/tags/$1" || true fi - tag_commit="$(resolve_tag)" -fi +} + +# Print the commit through which HEAD contains release commit $1, or fail. +contained_via() { + local release="$1" tree c + tree="$(g rev-parse "$release^{tree}")" + for c in "$release" $(g rev-parse "$release^@" 2>/dev/null || true); do + [ "$(g rev-parse "$c^{tree}" 2>/dev/null || true)" = "$tree" ] || continue + if g merge-base --is-ancestor "$c" "$head_commit" 2>/dev/null; then + echo "$c" + return 0 + fi + done + return 1 +} + +# As contained_via, deepening a shallow clone's history first if that is all +# that stands between HEAD and the release: back to a day before the release +# commit, then, should that not reach it, all of HEAD's history. +contains() { + contained_via "$1" && return 0 + is_shallow || return 1 + local since + since="$(g log -1 --format=%ct "$1")" + g fetch --quiet --shallow-since="$((since - 86400)) +0000" origin "$head_commit" || true + contained_via "$1" && return 0 + is_shallow || return 1 + g fetch --quiet --unshallow origin "$head_commit" || true + contained_via "$1" +} + +want_tag="v$want_version" +fetch_tag "$want_tag" +tag_commit="$(resolve_tag "$want_tag")" -status=0 if [ -z "$tag_commit" ]; then echo "core has no tag $want_tag, locally or on origin, but build.rs CORE_VERSION expects $want_version" >&2 - status=1 -elif [ "$tag_commit" != "$head_commit" ]; then - echo "core submodule is at $got_commit, but tag $want_tag is at $(git -C "$core" rev-parse --short="${#want_commit}" "$tag_commit")" >&2 - status=1 + exit 1 fi -if [ "$got_commit" != "$want_commit" ]; then - echo "core submodule is at $got_commit, but build.rs CORE_COMMIT expects $want_commit" >&2 - status=1 + +if [ "$tag_commit" = "$head_commit" ]; then + if [ "$status" -eq 0 ]; then + echo "vendored core pin OK: release v$want_version ($want_commit)" + fi + exit "$status" fi +# Not the release itself, so a dev pin: it must contain v$want_version ... +if ! via="$(contains "$tag_commit")"; then + echo "core submodule is at $got_commit, which is neither tag $want_tag ($(short "$tag_commit")) nor a commit that contains it" >&2 + exit 1 +fi + +# ... and no newer release, or CORE_VERSION would understate what it carries. +# Only tags past CORE_VERSION are checked, and a release cut later from a +# newer dev is not contained, so a dev pin that passes keeps passing. +if ! remote_tags="$(g ls-remote --tags --refs origin 'v*')"; then + echo "could not list the core's tags on origin, so the dev pin's newest release is unchecked" >&2 + exit 1 +fi +newer="$(printf '%s\n' "$remote_tags" | + sed -n 's|.*refs/tags/\(v[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)$|\1|p' | + { cat; echo "$want_tag"; } | sort -V -u | + awk -v want="$want_tag" 'past { print } $0 == want { past = 1 }')" +for t in $newer; do + fetch_tag "$t" + c="$(resolve_tag "$t")" + if [ -n "$c" ] && contains "$c" >/dev/null; then + echo "core submodule $got_commit contains $t, so build.rs CORE_VERSION should be ${t#v}, not $want_version" >&2 + status=1 + fi +done + if [ "$status" -eq 0 ]; then - echo "vendored core pin OK: v$want_version ($want_commit)" + if [ "$via" = "$tag_commit" ]; then + how="its ancestor" + else + how="via $(short "$via"), its parent with the same tree" + fi + echo "vendored core pin OK: dev $want_commit, newest release it contains v$want_version ($(short "$tag_commit"), $how)" fi exit "$status"