diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1fb47d6..8bd0470 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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-/lib/clang//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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8eca9cd..f430361 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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-/lib/clang//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 diff --git a/Cargo.toml b/Cargo.toml index fc52a8f..8327417 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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"] @@ -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" } diff --git a/README.md b/README.md index f6feee8..5d7d5a3 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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. diff --git a/docs/docs/content/CHANGELOG.md b/docs/docs/content/CHANGELOG.md index e2dcda3..ca94a09 100644 --- a/docs/docs/content/CHANGELOG.md +++ b/docs/docs/content/CHANGELOG.md @@ -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 diff --git a/docs/docs/content/documentation/ipc.md b/docs/docs/content/documentation/ipc.md index 7aeefdb..842ed7e 100644 --- a/docs/docs/content/documentation/ipc.md +++ b/docs/docs/content/documentation/ipc.md @@ -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 diff --git a/rayforce-sys/build.rs b/rayforce-sys/build.rs index 087555d..d0a86e2 100644 --- a/rayforce-sys/build.rs +++ b/rayforce-sys/build.rs @@ -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) diff --git a/rayforce-sys/src/lib.rs b/rayforce-sys/src/lib.rs index 37adbd5..7f765af 100644 --- a/rayforce-sys/src/lib.rs +++ b/rayforce-sys/src/lib.rs @@ -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 diff --git a/rayforce-sys/vendor/rayforce-q b/rayforce-sys/vendor/rayforce-q index df8ced9..c7582d2 160000 --- a/rayforce-sys/vendor/rayforce-q +++ b/rayforce-sys/vendor/rayforce-q @@ -1 +1 @@ -Subproject commit df8ced99a21d4bd2545f7ec18cce1798c52a3f17 +Subproject commit c7582d2822b19e7113853469d8876b6bfb338d60 diff --git a/rayforce/src/q.rs b/rayforce/src/q.rs index 4afccbd..61a5881 100644 --- a/rayforce/src/q.rs +++ b/rayforce/src/q.rs @@ -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; @@ -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 { 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 { unimplemented!() } +/// Runtime::scope(|_rt| { +/// let msg: Vec = 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>(msg: &[u8], cols: &[S]) -> Result { + 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::>>()?; + 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; @@ -553,31 +641,27 @@ pub fn decode_response(msg: &[u8]) -> Result { "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 { 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)) } diff --git a/rayforce/tests/q.rs b/rayforce/tests/q.rs index dfc55f8..aaeac49 100644 --- a/rayforce/tests/q.rs +++ b/rayforce/tests/q.rs @@ -5,7 +5,7 @@ use std::io::{Read, Write}; use std::net::TcpListener; use std::thread; -use rayforce::{q, q::QConnection, Runtime, Table}; +use rayforce::{q, q::QConnection, Runtime, Table, Value}; // --- Q wire-format builders (server side) --------------------------------- @@ -30,6 +30,39 @@ fn sym_vec(syms: &[&str]) -> Vec { b } +/// Float (f64) vector: type 9, attrs, int32 len, data. +fn float_vec(vals: &[f64]) -> Vec { + let mut b = vec![9u8, 0u8]; + b.extend_from_slice(&(vals.len() as i32).to_le_bytes()); + for v in vals { + b.extend_from_slice(&v.to_le_bytes()); + } + 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. +fn timespan_vec(vals: &[i64]) -> Vec { + let mut b = vec![16u8, 0u8]; + b.extend_from_slice(&(vals.len() as i32).to_le_bytes()); + for v in vals { + b.extend_from_slice(&v.to_le_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]; + b.extend_from_slice(&(vals.len() as i32).to_le_bytes()); + for v in vals { + b.extend_from_slice(&[10u8, 0u8]); + b.extend_from_slice(&(v.len() as i32).to_le_bytes()); + b.extend_from_slice(v.as_bytes()); + } + b +} + /// Table: type 98, attrs(0), dict-marker(99), KS-keys, general-list of columns. fn table(names: &[&str], cols: &[Vec]) -> Vec { let mut b = vec![98u8, 0u8, 99u8]; @@ -43,6 +76,14 @@ fn table(names: &[&str], cols: &[Vec]) -> Vec { b } +/// Keyed table: a dict (type 99) from a key table to a value table. +fn keyed(key: Vec, val: Vec) -> Vec { + let mut b = vec![99u8]; + b.extend(key); + b.extend(val); + b +} + /// Wrap a serialized object as a Q response message (8-byte header + body). fn msg(body: &[u8]) -> Vec { let size = (8 + body.len()) as u32; @@ -179,3 +220,192 @@ fn decode_response_rejects_non_response_messages() { }) .unwrap(); } + +// --- 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. +fn wide_table() -> Vec { + table( + &["seq", "sym", "note", "span", "px"], + &[ + long_vec(&[1, 2, 3]), + sym_vec(&["AAPL", "MSFT", "GOOG"]), + string_col(&["a", "bc", ""]), + timespan_vec(&[1, 2, 3]), + float_vec(&[1.5, 2.5, 3.5]), + ], + ) +} + +/// The wire form of a column, to compare two decodes by. +fn wire(v: &Value) -> Vec { + v.serialize().unwrap() +} + +#[test] +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)); + assert_eq!(t.column_names(), ["px", "note", "seq", "sym"]); + assert_eq!( + t.column("px").unwrap().as_slice::().unwrap(), + &[1.5, 2.5, 3.5] + ); + assert_eq!( + t.column("seq").unwrap().as_slice::().unwrap(), + &[1, 2, 3] + ); + let sym = t.column("sym").unwrap(); + assert_eq!(sym.get(1).unwrap().as_sym().unwrap(), "MSFT"); + let note = t.column("note").unwrap(); + 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(), ""); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn decode_response_cols_equals_decoding_the_projection() { + Runtime::scope(|_rt| { + // What q would have sent for `sym`note`px#t`, decoded whole. + let projection = msg(&table( + &["sym", "note", "px"], + &[ + sym_vec(&["AAPL", "MSFT", "GOOG"]), + string_col(&["a", "bc", ""]), + float_vec(&[1.5, 2.5, 3.5]), + ], + )); + let want = Table::from_value(q::decode_response(&projection).unwrap()).unwrap(); + + let names = vec!["sym".to_string(), "note".to_string(), "px".to_string()]; + let got = q::decode_response_cols(&msg(&wide_table()), &names).unwrap(); + let got = Table::from_value(got).unwrap(); + + assert_eq!(got.column_names(), want.column_names()); + for (g, w) in got.columns().unwrap().iter().zip(want.columns().unwrap()) { + assert_eq!(wire(g), wire(&w)); + } + Ok(()) + }) + .unwrap(); +} + +#[test] +fn decode_response_cols_names_a_column_the_table_lacks() { + Runtime::scope(|_rt| { + let err = q::decode_response_cols(&msg(&wide_table()), &["seq", "nope"]).unwrap_err(); + assert!( + err.to_string().contains("`nope`"), + "unexpected error: {err}" + ); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn decode_response_cols_refuses_bad_names() { + Runtime::scope(|_rt| { + let full = msg(&wide_table()); + let err = q::decode_response_cols(&full, &["seq", "px", "seq"]).unwrap_err(); + assert!( + err.to_string().contains("`seq` named twice"), + "unexpected error: {err}" + ); + let err = q::decode_response_cols(&full, &["s\0q"]).unwrap_err(); + assert!(err.to_string().contains("NUL"), "unexpected error: {err}"); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn decode_response_cols_without_a_table_or_names_is_decode_response() { + Runtime::scope(|_rt| { + // Not a table: the names are ignored. + let longs = msg(&long_vec(&[1, 2, 3])); + let v = q::decode_response_cols(&longs, &["seq"]).unwrap(); + assert_eq!(v.as_slice::().unwrap(), &[1, 2, 3]); + + // No names: every column, as `decode_response` would. + let narrow = msg(&table( + &["seq", "sym"], + &[long_vec(&[1, 2]), sym_vec(&["AAPL", "MSFT"])], + )); + let none: &[&str] = &[]; + let t = Table::from_value(q::decode_response_cols(&narrow, none).unwrap()).unwrap(); + assert_eq!(t.column_names(), ["seq", "sym"]); + + // A server error is an error either way. + let mut body = vec![(-128i8) as u8]; + body.extend_from_slice(b"type\0"); + let err = q::decode_response_cols(&msg(&body), &["seq"]).unwrap_err(); + assert!(err.to_string().contains("type"), "unexpected error: {err}"); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn decode_response_cols_projects_a_keyed_tables_value_side() { + Runtime::scope(|_rt| { + let kt = msg(&keyed( + table(&["k"], &[sym_vec(&["x", "y"])]), + table( + &["a", "span", "c"], + &[ + long_vec(&[1, 2]), + timespan_vec(&[1, 2]), + float_vec(&[0.5, 1.5]), + ], + ), + )); + // A keyed table decodes as (key table; value table). Naming the key + // column is allowed and changes nothing. + let v = q::decode_response_cols(&kt, &["c", "k", "a"]).unwrap(); + assert!(v.is_list() && v.len() == 2, "type {}", v.type_code()); + let key = Table::from_value(v.get(0).unwrap()).unwrap(); + let val = Table::from_value(v.get(1).unwrap()).unwrap(); + assert_eq!(key.column_names(), ["k"]); + assert_eq!( + key.column("k").unwrap().get(1).unwrap().as_sym().unwrap(), + "y" + ); + assert_eq!(val.column_names(), ["c", "a"]); + assert_eq!( + val.column("c").unwrap().as_slice::().unwrap(), + &[0.5, 1.5] + ); + + let err = q::decode_response_cols(&kt, &["k", "b"]).unwrap_err(); + assert!(err.to_string().contains("`b`"), "unexpected error: {err}"); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn decode_response_cols_checks_the_wire_header() { + Runtime::scope(|_rt| { + let mut request = msg(&wide_table()); + request[1] = 1; // sync request, not response + let err = q::decode_response_cols(&request, &["seq"]).unwrap_err(); + assert!( + err.to_string().contains("expected response message type 2"), + "unexpected error: {err}" + ); + Ok(()) + }) + .unwrap(); +}