Repository navigation
Call Rust functions from SQL as scalar UDFs - #75
Merged
Merged
Conversation
Move the pin in the three places that carry it, as the release check's propose_bump step does: CHDB_ENGINE_PIN in update_libchdb.sh and build.rs, and engine under [package.metadata.chdb] in Cargo.toml. The docs.rs header snapshot moves with it, since build.rs refuses a DOCS_RS build whose bundled chdb.h does not carry the pinned CHDB_VERSION: docs/chdb-ffi-v26.11.1.h becomes docs/chdb-ffi-v26.11.2-rc.3.h, the header shipped in the release's linux-x86_64-libchdb.tar.gz (sha256 cd07ba6f...a8a7, as listed in the release's SHA256SUMS). The docs that name the engine a normal build downloads, and the Arrow contract link, follow the pin. Against v26.11.1 the header adds the scalar function ABI (chdb_create_scalar_function, chdb_drop_scalar_function, the chdb_scalar_function_options struct, its callback and flags) and documents --restrict_local_filesystem_access; everything else is unchanged apart from CHDB_VERSION. This is a release candidate, a GitHub pre-release: the crate's release gate applies again, so it does not publish against this pin. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
tests/arrow_registration.rs calls register_arrow_reader and imports insert_record_batch_reader and InsertOptions, all of which exist only with the arrow feature, but it had no [[test]] entry to say so. That made `cargo test --no-default-features` fail to compile, which the query_with_params entry exists to prevent. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
chdb-core v26.11.2-rc.3 added chdb_create_scalar_function and chdb_drop_scalar_function, which let a host function be called from SQL, one block of rows at a time, with arguments and result exchanged as Arrow C Data. This binds them in a new scalar_function module, behind the arrow feature, in the shape of duckdb-rs's vscalar API: - VArrowScalar, duckdb-rs's trait adapted to chDB: invoke(state, RecordBatch) -> ArrayRef and one signature() rather than a list of overloads, registered with Connection::register_scalar_function (default state) or register_scalar_function_with_state, which moves the state in instead of cloning it per overload. - Connection::register_row_function, a closure called once per row with the arguments as Values, for when per-row code is simpler. - ScalarFunctionSignature: ClickHouse type names, checked by chDB at registration, plus the volatile, special NULL handling and binary strings flags. - drop_scalar_function, which takes no connection, since chDB's registry belongs to the process and outlives every connection. The callback runs user code directly on the engine's threads, which Rust allows, so the state and the closure are Send + Sync. Nothing unwinds into chDB: a panic in the function, in formatting its error or in dropping its state is caught and reported through the error buffer, interior NULs escaped and the message cut at a character boundary. Ownership follows the header. The argument array is moved out of chDB's struct, so the RecordBatch owns its buffers and a function can return one of its input columns. The result is exported with FFI_ArrowArray::new, whose release callback keeps the Rust buffers alive until chDB releases them. user_data is a boxed closure owned by chDB after a successful create and dropped in destroy; a failed create drops it here. A function must not call back into chDB: a query on the connection whose query is running the function waits for it forever, measured against rc.3 with a C reproducer. The callback and destroy mark their thread, and on a marked thread the crate's calls that connect, run a statement, register or drop anything, or shut down return Error::CalledFromScalarFunction instead. build.rs reads the ABI from the header, as it does for the durable ABI, and sets has_scalar_function_abi. Against an older engine the API still compiles, everything else works, and registration returns Error::ScalarFunctionsUnavailable. A runtime dlsym probe does not fit this crate: it links libchdb at build time, Rust links with BIND_NOW so a missing symbol fails the load, and Connection::open already checks that the loaded engine is the one the build fetched. The Arrow formats chDB sends were measured against rc.3 for every type in the mapping table. tests/scalar_function.rs covers both styles, the type mapping, NULL handling, volatility, binary strings, errors and panics, registration failures and state ownership, drop semantics, the process-wide registry, multi-threaded queries, concurrent host threads, every query entry point and the refused re-entry. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…in CI The scalar function tests need no workflow change to run: the pin is v26.11.2-rc.3, and tests/scalar_function.rs runs in the existing `cargo test` steps on all four platforms, dynamic and static. What no step covered is the two builds the feature promises to keep working. - Without default features. Nothing in CI built the crate without arrow, which is how tests/arrow_registration.rs came to break that build unnoticed, and the scalar function module and the guard against calls back into chDB are compiled in and out with the feature. - Against an engine without the ABI. build.rs reads the ABI from the header, and against an older engine the crate has to build without warnings and run everything else, with registration reporting Error::ScalarFunctionsUnavailable. The step builds every target with clippy and runs the library tests against v26.11.1, the newest engine without the ABI, through CHDB_LIB_DIR; it comes last because that rebuilds the crate. Both run on ubuntu-latest only, like the other single-cell checks. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Most of the binding can be exercised without chDB. The tests call the extern "C" callback and destroy directly, with C Data built by arrow-rs the way chDB hands it over, and read a buffer's reference count to see when the arguments are released. - The callback: a batch round trip that releases its arguments, and a result made of its input that holds them until it is released. Errors, panics, an error whose Display panics and a result of the wrong length fail the batch with their message, release the arguments and leave the thread unmarked. A NULL struct row, a plain column, an unknown format and a schema that does not match the array are refused, the last through arrow-rs's panic. Struct and child offsets are honoured, a batch without arguments keeps its row count, and the function runs with its thread marked. - destroy drops the state once with the thread marked, and contains a state whose Drop panics. - write_error keeps four-byte characters whole, counts escaped NULs, writes nothing past the terminator and leaves a missing or empty buffer alone. describe bounds a chain of causes, a cycle included. panic_message contains a payload whose Drop panics. - The row executor reads the remaining scalar types, sliced columns with NULL bits off a byte boundary and Decimal256; returns dates and timestamps with their unit and time zone; unifies results whatever their order; and names the kinds that mix with nothing else. Its row loop keeps argument order, stops at the first failing row, names an unreadable argument by position and runs a function without arguments once per row. - Value conversions and accessors, the flag bits chdb.h defines, and signature types kept as written. - The guard leaves the thread unmarked after a panic, and every call that starts work in chDB, from connecting to shutting down, refuses inside a function; a refused registration drops its state. - A NUL in an argument or return type fails registration before chDB is called and drops the state, and the ABI test checks the state is dropped with or without the ABI. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The re-entry guard refused calls that start work in chDB, but not those that go on with work already started: a stream's next chunk or batch, an insert's append and finish, their cancels and drops, and closing a connection. Each waits on the engine as a query does, and chDB's contract forbids all of them inside a function or the destroy of its state. - next_chunk and next_batch, and so both streams' Iterator::next, append, finish, and io::Write's write and flush on an insert return Error::CalledFromScalarFunction there, leaving the stream as it was. - A cancel has no error to return. QueryStream::cancel and ArrowQueryStream::cancel do nothing there, leaving the stream for a cancel or a drop outside; InsertStream::cancel leaks the insert. - A drop cannot report either, and does what ArrowRegistration already does when it cannot unregister: it leaks. A stream or an insert is left open, and a connection is left open with its registry slot, so the crate keeps counting what the engine still holds; a durable object keeps its scratch tree under its leaked connection. Measured against rc.3, chDB still closes a connection whose stream or insert was leaked, and until then a connection with an insert left open refuses other statements with an error rather than hanging. Not guarded, since they wait on no query: QueryResult's accessors and drop, which read and free one materialized result; the one-shot ArrowReader, whose callbacks read and release a standalone Arrow table as the function itself releases chDB's argument structs; chdb_version; and the signal-handler switches. The streams are not Send, so they cannot sit in a function's state; a Connection, a Session or a DurableObject can, and their drops are the ones a user reaches in practice. callback.rs tests each newly guarded call on real streams and inserts, with the thread marked by hand. Two new test binaries drop a function whose state owns a connection or a durable object, each in a process of its own since the leaked connection holds the engine from then on. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Rust functions can now be called from SQL as scalar user-defined functions. This uses the scalar function C ABI added in chdb-io/chdb-core#352, first released in v26.11.2-rc.3. The API follows duckdb-rs's
VScalar/VArrowScalar, and it is the same feature chdb-io/chdb-go#92 adds to Go..with_volatile,.with_special_null_handlingand.with_binary_strings.arrowfeature, because the ABI exchanges Arrow C Data.drop_scalar_functionneeds no connection. The docs state this.Design
Send + Sync + 'static. No lock is held while user code runs.destroytherefore mark their thread. On a marked thread the crate returnsError::CalledFromScalarFunctioninstead of connecting, running a statement, registering, dropping or shutting down.panicked: kaboom.RecordBatchowns them and a function may return an input column.user_datais a boxed closure. It is freed exactly once, indestroy, or by the binding when a registration fails.Error::ScalarFunctionsUnavailablewith the minimum version. A binary that never registers a function does not import the two symbols.Commits
Move the engine pin from v26.11.1 to v26.11.2-rc.3. Changes⚠️ This is a pre-release, so the release gate applies again and the crate cannot be published on this pin. Keep this commit, or drop it and wait for a stable engine.
build.rs,update_libchdb.sh,Cargo.toml[package.metadata.chdb], the docs.rs header snapshot and the docs.Gate the
arrow_registrationtest on thearrowfeature. Without the gate,--no-default-featuresdid not compile on main.Register scalar functions written in Rust. Adds:
src/scalar_function.rssrc/callback.rstests/scalar_function.rs, 19 cases), example 17CI (
rust.yml). On ubuntu-latest, adds a--no-default-featurestest step and a check against v26.11.1: clippy--deny warningsandcargo test --libon an engine without the ABI.Test the scalar function binding's own logic without the engine. Adds 26 lib tests, taking the lib suite from 75 to 101. They call the C callback and
destroydirectly with argument data built the way chDB hands it over, and a buffer reference count shows exactly when the arguments are released. They cover:Display, a wrong result length) still releasing the arguments;destroyonce, and a panicking drop;write_errorat UTF-8 boundaries;Each test was checked against a targeted break in the production code.
Refuse going on with a stream or an insert inside a scalar function. The tests showed the guard only refused calls that start work. These now return
Error::CalledFromScalarFunctioninside a function ordestroy, and leave the stream as it was:QueryStream::next_chunkandArrowQueryStream::next_batch, andIterator::nextthrough them;InsertStream::append,io::Writeandfinish.Paths that cannot return an error leak instead of waiting, as
ArrowRegistrationalready does:Connection::drop, which keeps its registry slot so that counts and shutdown stay consistent.Measured against rc.3, chDB still closes a connection whose stream or insert was leaked, and a leaked insert only makes its connection refuse other statements; it never hangs. There are new single-process test binaries for dropping a function whose state owns a connection or a durable object.
Tests
Run locally on linux-x86_64 against v26.11.2-rc.3:
cargo test -- --test-threads=1: lib 103 (42 new), scalar_function 19 and scalar_function_destroy 1 (new), doc tests 66 (2 new). Every existing binary is unchanged.cargo test --features durable -- --test-threads=1: all pass.cargo test --no-default-features -- --test-threads=1: all pass.cargo fmt --checkandcargo clippy --all-targets -- --deny warnings: clean, both with default features and withdurable.cargo docwithDOCS_RS=1and broken intra-doc links denied: ok.CHDB_LIB_DIR: clippy is clean, andcargo test --libpasses, including the unavailable-ABI path.check-static-link.shpasses.The UDF tests cover:
macOS, linux-aarch64 and the other static builds are left to CI.
Known limitations
VArrowScalarfor those), andTimeand other unmapped types return an error. Strings are copied per row.--no-default-features,cargo clippy --deny warningsreports anunused mutintests/runtime_faces.rs. The new CI step runs the tests without--deny warnings.🤖 Generated with Claude Code
Note
Add scalar UDF support for calling Rust functions from SQL
scalar_functionmodule (arrow-gated) that lets users register Rust functions callable from SQL, either row-based (receivingValuearguments) or batch-based viaVArrowScalaron ArrowRecordBatchvalues. Registration is process-wide and functions outlive their connections; signatures, NULL handling, volatility, and binary-string options are supported. See scalar_function.rs and the example in 17_scalar_function.rs.CalledFromScalarFunctioninstead of deadlocking.build.rsemitshas_scalar_function_abionly when the engine declares the new ABI symbols, so older engines reportScalarFunctionsUnavailable.durable.Core.reclaimno longer removes the scratch directory in that context.Macroscope summarized 0a6a2fd.