Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,30 @@ jobs:
- name: Install toolchain deps
run: sudo apt-get update && sudo apt-get install -y clang libclang-dev build-essential

# bindgen needs to be told where libclang lives on the runner.
# bindgen loads libclang, LLVM's C API, while rayforce-sys's build script
# runs. Name that library exactly: a pattern as broad as `libclang*.so*`
# also matches the compiler runtime under llvm-<v>/lib/clang/<v>/lib/linux
# (libclang_rt.*), a directory holding no libclang, and on the runners of
# 2026-10-20 `find | head -1` picked it. Prefer the LLVM of the `clang`
# installed above, and load each candidate to check it exports
# clang_createIndex before bindgen is pointed at its directory.
- name: Locate libclang
run: |
LIB="$(find /usr/lib -name 'libclang*.so*' 2>/dev/null | head -1)"
if [ -z "$LIB" ]; then echo "libclang not found" >&2; exit 1; fi
major="$(clang -dumpversion | cut -d. -f1)"
LIB=""
for f in "/usr/lib/llvm-$major/lib/libclang.so" \
$(find /usr/lib -regextype posix-extended \
-regex '.*/libclang(-[0-9][0-9.]*)?\.so(\.[0-9]+)*' | sort -V -r); do
if python3 -c 'import ctypes, sys; ctypes.CDLL(sys.argv[1]).clang_createIndex' "$f" 2>/dev/null; then
LIB="$f"
break
fi
done
if [ -z "$LIB" ]; then
echo "::error::no libclang under /usr/lib exports clang_createIndex"; exit 1
fi
echo "LIBCLANG_PATH=$(dirname "$LIB")" >> "$GITHUB_ENV"
echo "Using LIBCLANG_PATH=$(dirname "$LIB")"
echo "Using $LIB, so LIBCLANG_PATH=$(dirname "$LIB")"

- name: Install Rust
uses: dtolnay/rust-toolchain@stable
Expand Down
24 changes: 21 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,30 @@ jobs:
- name: Install toolchain deps
run: sudo apt-get update && sudo apt-get install -y clang libclang-dev build-essential

# bindgen needs to be told where libclang lives on the runner.
# bindgen loads libclang, LLVM's C API, while rayforce-sys's build script
# runs. Name that library exactly: a pattern as broad as `libclang*.so*`
# also matches the compiler runtime under llvm-<v>/lib/clang/<v>/lib/linux
# (libclang_rt.*), a directory holding no libclang, and on the runners of
# 2026-10-20 `find | head -1` picked it. Prefer the LLVM of the `clang`
# installed above, and load each candidate to check it exports
# clang_createIndex before bindgen is pointed at its directory.
- name: Locate libclang
run: |
LIB="$(find /usr/lib -name 'libclang*.so*' 2>/dev/null | head -1)"
if [ -z "$LIB" ]; then echo "libclang not found" >&2; exit 1; fi
major="$(clang -dumpversion | cut -d. -f1)"
LIB=""
for f in "/usr/lib/llvm-$major/lib/libclang.so" \
$(find /usr/lib -regextype posix-extended \
-regex '.*/libclang(-[0-9][0-9.]*)?\.so(\.[0-9]+)*' | sort -V -r); do
if python3 -c 'import ctypes, sys; ctypes.CDLL(sys.argv[1]).clang_createIndex' "$f" 2>/dev/null; then
LIB="$f"
break
fi
done
if [ -z "$LIB" ]; then
echo "::error::no libclang under /usr/lib exports clang_createIndex"; exit 1
fi
echo "LIBCLANG_PATH=$(dirname "$LIB")" >> "$GITHUB_ENV"
echo "Using $LIB, so LIBCLANG_PATH=$(dirname "$LIB")"

- name: Install Rust
uses: dtolnay/rust-toolchain@stable
Expand Down
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ resolver = "2"
members = ["rayforce-sys", "rayforce"]

[workspace.package]
version = "1.3.1"
version = "1.3.2"
edition = "2021"
license = "MIT"
authors = ["RayforceDB"]
Expand All @@ -16,4 +16,4 @@ categories = ["database", "api-bindings"]
rust-version = "1.74"

[workspace.dependencies]
rayforce-sys = { path = "rayforce-sys", version = "1.3.1" }
rayforce-sys = { path = "rayforce-sys", version = "1.3.2" }
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ cargo test --workspace
```

`rayforce-sys/vendor/rayforce-q` works the same way, minus the constants — nothing is
stamped from it.
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.

To build against a core you are changing instead, point the build script at your own
checkout. These take precedence over the vendored copies:
Expand All @@ -160,8 +161,10 @@ repo's `.cargo/config.toml`. If bindgen can't auto-detect libclang, set it yours
```sh
# macOS (CTL):
export LIBCLANG_PATH="/Library/Developer/CommandLineTools/usr/lib"
# Linux:
export LIBCLANG_PATH="$(dirname "$(find /usr/lib -name 'libclang*.so*' | head -1)")"
# Linux: the directory of libclang itself. A pattern like libclang*.so* also
# matches libclang-cpp and the libclang_rt runtime, whose directory has none.
export LIBCLANG_PATH="$(dirname "$(find /usr/lib -regextype posix-extended \
-regex '.*/libclang(-[0-9][0-9.]*)?\.so(\.[0-9]+)*' | sort -V | tail -1)")"
```

The `chrono` is on by default for date/time/timestamp conversions.
Expand Down
53 changes: 53 additions & 0 deletions docs/docs/content/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,59 @@
All notable changes to `rayforce` are documented here. This project adheres to
[Semantic Versioning](https://semver.org).

## 1.3.2

### Added

- **`q::decode_response_cols`** decodes a complete Q response message keeping
only the named columns of a table, in the order named, as 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. rayforce-q measured a 100 000-row, 142-column window kept to 23
columns at ~43 ms, against ~182 ms for the whole message. Skipping reads only
lengths, so a timespan column, which `q::decode_response` refuses, can be
dropped. A name the table lacks is an `Err` whose message names it
(`` q: column `x` not in table ``), and so are a name given twice and one
holding a NUL; every name is checked before any column is decoded. For a
keyed table the key table comes back whole and the names pick among the
value columns. A message that is not a table, or an empty name list, decodes
as `q::decode_response` decodes it, and a compressed message is still
decompressed whole. `rayforce-sys` declares the C function, `q_decode_cols`.

### Changed

- **`rayforce-q` is 2.5.0 (`c7582d2`)**, from 2.4.0 (`df8ced9`). The vendored
core stays at v2.11.5 (`5d5f47c`). 2.5.0 adds `q_decode_cols` to `q.h`. The
rest of `q.c`'s change is the fix below, and `q_decode` and the dict and
keyed-table construction moved into helpers both decoders share. rayforce-q
has pushed no 2.5.0 tag, so it is pinned by the merge of its pull request,
whose tree is the "Release 2.5.0" commit's. `rayforce-sys`'s build script
refuses a `RAYFORCE_Q_SRC` checkout whose `q.h` does not declare
`q_decode_cols`, naming 2.5.0, where a caller of `q::decode_response_cols`
would have failed to link.

### Fixed

- **A table decoded from the Q wire is no longer released twice when a column
cannot be added to it.** `ray_table_add_col` consumes the table on every
path, failure included, and rayforce-q's table builder released it again. A
table whose column is an atom reaches this from the wire on every decode
path, where the error object reusing the freed block masked it; on
`ray_table_add_col`'s out-of-memory paths the block was freed twice.

- **`q::decode_response` passes its error buffer as `c_char`**, where it
spelled it `i8`, which does not type-check where `c_char` is unsigned, as on
aarch64 Linux.

- **CI and the release workflow point bindgen at libclang itself.** They took
the first file under `/usr/lib` matching `libclang*.so*`, which also matches
LLVM's `libclang_rt` runtime. On the runners of 2026-10-20 that came first,
so bindgen found no libclang and the build script panicked. They now take the
libclang of the installed `clang`'s LLVM, or the newest other one, and load
it to check it exports `clang_createIndex` first. The README's Linux example
had the same search and is fixed the same way.

## 1.3.1

### Changed
Expand Down
3 changes: 3 additions & 0 deletions docs/docs/content/documentation/ipc.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,9 @@ fn main() -> rayforce::Result<()> {
`Value::deserialize`.
- `q::decode_response` — decode a Q message your own transport already read,
when you want the socket in a separate thread rather than on the event loop.
- `q::decode_response_cols` — the same, keeping only the named columns of a
table. The others are skipped without being built, so a wide table costs
only the columns you keep.

## :material-server-network: Serving the Q wire

Expand Down
11 changes: 11 additions & 0 deletions rayforce-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,17 @@ fn main() {
It ships with rayforce-q >= 2.1.0; older checkouts have only q.c.",
q_server_c.display()
);
// `q_decode_cols` (the projected decode behind `q::decode_response_cols`)
// arrived in rayforce-q 2.5.0. Against an older checkout the build would
// only fail at link time, on an undefined symbol, so say so here.
let q_h = q_src.join("q.h");
assert!(
fs::read_to_string(&q_h).is_ok_and(|h| h.contains("q_decode_cols")),
"rayforce-q at {} does not declare q_decode_cols in q.h.\n\
It ships with rayforce-q >= 2.5.0; point RAYFORCE_Q_SRC at a newer \
checkout, or unset it to build the vendored one.",
q_src.display()
);
cc::Build::new()
.file(&q_c)
.file(&q_server_c)
Expand Down
18 changes: 18 additions & 0 deletions rayforce-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,24 @@ extern "C" {
err: *mut ::std::os::raw::c_char,
errlen: usize,
) -> *mut ray_t;
/// 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.
pub fn q_decode_cols(
resp: *mut u8,
resp_len: i64,
compressed: ::std::os::raw::c_int,
cols: *const *const ::std::os::raw::c_char,
ncols: ::std::os::raw::c_int,
err: *mut ::std::os::raw::c_char,
errlen: usize,
) -> *mut ray_t;
/// Serialize `msg` into a complete Q wire request (8-byte header + body).
/// The buffer is malloc'd by C and must be released with `libc::free`.
/// `q_encode` always stamps the header's message-type byte as SYNC; a
Expand Down
2 changes: 1 addition & 1 deletion rayforce-sys/vendor/rayforce-q
Submodule rayforce-q updated 8 files
+6 −0 README.md
+1 −1 VERSION
+18 −0 docs/CHANGELOG.md
+11 −0 docs/INTEGRATING.md
+388 −27 q.c
+13 −0 q.h
+360 −0 test/driver.c
+3 −0 test/run.sh
122 changes: 103 additions & 19 deletions rayforce/src/q.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::ffi::{c_void, CString};
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int};

use rayforce_sys as sys;

Expand Down Expand Up @@ -528,8 +529,95 @@ unsafe fn libc_free(p: *mut std::ffi::c_void) {
/// bytes and thread-safe anywhere, while this call allocates engine objects
/// and must run on the thread that owns the [`crate::Runtime`] (like every
/// other constructor in this crate). A Q server-side error surfaces as `Err`.
///
/// To keep only some columns of a wide table, use [`decode_response_cols`].
pub fn decode_response(msg: &[u8]) -> Result<Value> {
assert_on_runtime_thread("q::decode_response");
let (body, compressed) = response_body(msg)?;
let mut err = [0 as c_char; 256];
let res = unsafe {
sys::q_decode(
body.as_ptr() as *mut u8,
body.len() as i64,
compressed,
err.as_mut_ptr(),
err.len(),
)
};
unsafe { decoded(res, &err, "q_decode failed") }
}

/// [`decode_response`], keeping only the named columns of a table.
///
/// A table comes back with the columns `cols` names, in the order named, as
/// 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.
///
/// ```no_run
/// # use rayforce::{q, Runtime, Table};
/// # fn frame() -> Vec<u8> { unimplemented!() }
/// Runtime::scope(|_rt| {
/// let msg: Vec<u8> = frame(); // a response your own transport read
/// let fills = q::decode_response_cols(&msg, &["date", "Symbol", "LastPx"])?;
/// let t = Table::from_value(fills)?;
/// assert_eq!(t.shape().1, 3);
/// Ok(())
/// })?;
/// # Ok::<(), rayforce::RayError>(())
/// ```
///
/// - A name the table lacks is an `Err` naming it, and so is a name given
/// twice or one holding a NUL. Every name is checked before any column is
/// decoded.
/// - A keyed table comes back as [`decode_response`] returns one, a list of
/// its key table and value table. The key table is whole, and `cols` picks
/// among the value columns; naming a key column is allowed and changes
/// nothing.
/// - A message that is not a table, and an empty `cols`, decode as
/// [`decode_response`] decodes them. That includes a server error, which is
/// 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.
///
/// Needs `rayforce-q` 2.5.0 or later. Like [`decode_response`], it must run on
/// the thread that owns the [`crate::Runtime`].
pub fn decode_response_cols<S: AsRef<str>>(msg: &[u8], cols: &[S]) -> Result<Value> {
assert_on_runtime_thread("q::decode_response_cols");
let (body, compressed) = response_body(msg)?;
let names = cols
.iter()
.map(|c| {
let c = c.as_ref();
CString::new(c)
.map_err(|_| RayError::binding(format!("Q: column name {c:?} contains NUL")))
})
.collect::<Result<Vec<_>>>()?;
let ptrs: Vec<*const c_char> = names.iter().map(|c| c.as_ptr()).collect();
let ncols =
c_int::try_from(ptrs.len()).map_err(|_| RayError::binding("Q: too many column names"))?;
let mut err = [0 as c_char; 256];
// `names` owns the strings `ptrs` points into and outlives the call, which
// only reads them.
let res = unsafe {
sys::q_decode_cols(
body.as_ptr() as *mut u8,
body.len() as i64,
compressed,
ptrs.as_ptr(),
ncols,
err.as_mut_ptr(),
err.len(),
)
};
unsafe { decoded(res, &err, "q_decode_cols failed") }
}

/// Check the 8-byte wire header of a complete Q response message and return
/// its body and whether that body is compressed, as the decoders take them.
fn response_body(msg: &[u8]) -> Result<(&[u8], c_int)> {
// q_header_t (q.c): endianness, msgtype, compressed, reserved, u32 size.
// `size` counts the whole message, header included. Little-endian wire only.
const HEADER_LEN: usize = 8;
Expand All @@ -553,31 +641,27 @@ pub fn decode_response(msg: &[u8]) -> Result<Value> {
"Q: message length does not match wire header",
));
}
let compressed = i32::from(msg[2] != 0);
let compressed = c_int::from(msg[2] != 0);
let body = &msg[HEADER_LEN..];
if body.is_empty() {
return Err(RayError::binding("Q: empty response body"));
}
Ok((body, compressed))
}

let mut err = [0i8; 256];
let res = unsafe {
sys::q_decode(
body.as_ptr() as *mut u8,
body.len() as i64,
compressed,
err.as_mut_ptr(),
err.len(),
)
};
/// Turn what a decoder returned into a [`Value`]. Null is a decode failure
/// whose reason the decoder wrote to `err` (`fallback` when it wrote none); a
/// `RAY_ERROR`, such as a q server error, becomes `Err`.
///
/// # Safety
/// `res` must be null or an owned pointer the decoder just returned, and `err`
/// the buffer it was given.
unsafe fn decoded(res: *mut sys::ray_t, err: &[c_char], fallback: &str) -> Result<Value> {
if res.is_null() {
let msg = unsafe { std::ffi::CStr::from_ptr(err.as_ptr()) }.to_string_lossy();
let msg = if msg.is_empty() {
"q_decode failed".into()
} else {
msg
};
let msg = std::ffi::CStr::from_ptr(err.as_ptr()).to_string_lossy();
let msg = if msg.is_empty() { fallback.into() } else { msg };
return Err(RayError::binding(format!("Q: {msg}")));
}
let ok = unsafe { check(res)? };
Ok(unsafe { Value::from_owned(ok) })
let ok = check(res)?;
Ok(Value::from_owned(ok))
}
Loading
Loading