Skip to content

Call Rust functions from SQL as scalar UDFs - #75

Merged
wudidapaopao merged 6 commits into
chdb-io:mainfrom
wudidapaopao:scalar-udf
Dec 2, 2026
Merged

wudidapaopao merged 6 commits into
chdb-io:mainfrom
wudidapaopao:scalar-udf

Conversation

@wudidapaopao

@wudidapaopao wudidapaopao commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

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.

use chdb_rust::scalar_function::{drop_scalar_function, ScalarFunctionSignature, Value, VArrowScalar};

// Row style: a closure called once per row with `Value`s.
conn.register_row_function("plus_one", ScalarFunctionSignature::exact(&["Int64"], "Int64"),
    |args| Ok(Value::from(args[0].as_i64().ok_or("expected an Int64")? + 1)))?;

// Arrow style: one RecordBatch in, one array out, per block.
struct Scale;
impl VArrowScalar for Scale {
    type State = i64;
    fn invoke(f: &i64, input: RecordBatch) -> Result<ArrayRef, Box<dyn std::error::Error>> {
        let v = input.column(0).as_primitive::<Int64Type>();
        Ok(Arc::new(v.unary::<_, Int64Type>(|x| x * f)))
    }
    fn signature() -> ScalarFunctionSignature { ScalarFunctionSignature::exact(&["Int64"], "Int64") }
}
conn.register_scalar_function_with_state::<Scale>("scale", 10)?;
// SELECT plus_one(scale(toInt64(number))) FROM numbers(3)  ->  1, 11, 21
drop_scalar_function("plus_one")?;
  • Signatures use ClickHouse type names. The flags are .with_volatile, .with_special_null_handling and .with_binary_strings.
  • The API is behind the existing arrow feature, because the ABI exchanges Arrow C Data.
  • Differences from duckdb-rs:
    • chDB registers one signature per name, so there are no overloads.
    • The state is moved in rather than cloned.
    • Functions are process-wide. They outlive connections, and drop_scalar_function needs no connection. The docs state this.

Design

  • Threading. User code runs directly on chDB's engine threads, concurrently, so state and closures are Send + Sync + 'static. No lock is held while user code runs.
  • Calls back into chDB. A query issued from inside a callback on the same connection hangs the engine; this was reproduced in C against rc.3. The callback and destroy therefore mark their thread. On a marked thread the crate returns Error::CalledFromScalarFunction instead of connecting, running a statement, registering, dropping or shutting down.
  • Panics never unwind into chDB. A panic in the function, in formatting its error, or in dropping its state becomes the query's error, for example panicked: kaboom.
  • Ownership.
    • Arguments are moved out of chDB's struct, so the RecordBatch owns them and a function may return an input column.
    • The result is exported into chDB's zeroed structs only on success, and chDB's release frees it on any thread.
    • user_data is a boxed closure. It is freed exactly once, in destroy, or by the binding when a registration fails.
  • Detection is at build time. The crate generates its bindings from the header with bindgen. Built against an engine without the ABI, it still builds warning-free, and registration returns Error::ScalarFunctionsUnavailable with the minimum version. A binary that never registers a function does not import the two symbols.

Commits

  1. Move the engine pin from v26.11.1 to v26.11.2-rc.3. Changes build.rs, update_libchdb.sh, Cargo.toml [package.metadata.chdb], the docs.rs header snapshot and the docs. ⚠️ 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.

  2. Gate the arrow_registration test on the arrow feature. Without the gate, --no-default-features did not compile on main.

  3. Register scalar functions written in Rust. Adds:

    • src/scalar_function.rs
    • the re-entry guard in src/callback.rs
    • tests (tests/scalar_function.rs, 19 cases), example 17
    • README and docs sections, and the agent skill note
  4. CI (rust.yml). On ubuntu-latest, adds a --no-default-features test step and a check against v26.11.1: clippy --deny warnings and cargo test --lib on an engine without the ABI.

  5. 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 destroy directly with argument data built the way chDB hands it over, and a buffer reference count shows exactly when the arguments are released. They cover:

    • results built from inputs;
    • failures (returned errors, panics, a panicking Display, a wrong result length) still releasing the arguments;
    • unreadable arguments;
    • offsets at every level;
    • zero-argument batches;
    • destroy once, and a panicking drop;
    • write_error at UTF-8 boundaries;
    • bounded cause cycles;
    • row-executor unification in any order;
    • flag bits;
    • the re-entrancy guard across about 20 entry points.

    Each test was checked against a targeted break in the production code.

  6. 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::CalledFromScalarFunction inside a function or destroy, and leave the stream as it was:

    • QueryStream::next_chunk and ArrowQueryStream::next_batch, and Iterator::next through them;
    • InsertStream::append, io::Write and finish.

    Paths that cannot return an error leak instead of waiting, as ArrowRegistration already does:

    • stream and insert cancel/drop;
    • 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 --check and cargo clippy --all-targets -- --deny warnings: clean, both with default features and with durable.
  • cargo doc with DOCS_RS=1 and broken intra-doc links denied: ok.
  • Against v26.11.1 via CHDB_LIB_DIR: clippy is clean, and cargo test --lib passes, including the unavailable-ABI path.
  • Static linking, linux-x86_64: the scalar_function tests pass, and check-static-link.sh passes.
  • The scalar_function suite was repeated 5× in parallel and 3× serially: 19/19 every time.

The UDF tests cover:

  • row and Arrow styles
  • every mapped type
  • NULL skipping vs special NULL handling
  • volatile vs deterministic zero-argument functions
  • errors and panics as query errors
  • name collisions and bad types
  • drop, drop again, re-register, and state dropped once
  • a query that already uses a dropped function finishing with it
  • multi-threaded blocks and concurrent host threads
  • every query entry point
  • calls back into chDB being refused

macOS, linux-aarch64 and the other static builds are left to CI.

Known limitations

  • Found while testing, not fixed (pre-existing). In the durable module, the heartbeat thread waits on its stop signal without checking the flag first, a lost wakeup. A durable object dropped right after it opens can therefore block for a full heartbeat interval, 10 s by default.
  • Row API. It has no nested results (use VArrowScalar for those), and Time and other unmapped types return an error. Strings are copied per row.
  • Pre-existing issue, not fixed here. With --no-default-features, cargo clippy --deny warnings reports an unused mut in tests/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

  • Adds a new scalar_function module (arrow-gated) that lets users register Rust functions callable from SQL, either row-based (receiving Value arguments) or batch-based via VArrowScalar on Arrow RecordBatch values. 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.
  • Adds reentrancy guards (callback.rs): calling chDB operations (queries, streams, inserts, Arrow registration, admin backup/restore, shutdown) from inside a scalar callback returns CalledFromScalarFunction instead of deadlocking.
  • Updates the pinned chdb-core engine from v26.11.1 to v26.11.2-rc.3 across build.rs, Cargo.toml, and update_libchdb.sh; build.rs emits has_scalar_function_abi only when the engine declares the new ABI symbols, so older engines report ScalarFunctionsUnavailable.
  • Adds extensive tests in scalar_function.rs covering type conversion, NULL handling, panics, concurrency, and reentrancy, plus CI compatibility checks against v26.11.1 and a no-default-features build.
  • Behavioral Change: connections, query streams, and insert streams dropped inside a scalar callback are leaked rather than closed (connection.rs, query_stream.rs, insert_stream.rs); durable.Core.reclaim no longer removes the scratch directory in that context.

Macroscope summarized 0a6a2fd.

wudidapaopao and others added 6 commits December 1, 2026 05:42
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>
@wudidapaopao
wudidapaopao merged commit 9bb5c8f into chdb-io:main Dec 2, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant