Repository navigation
Drivers for executable user-defined functions - #105131
Conversation
Introduce "drivers" for executable user-defined functions. A driver is a
small adapter program declared in a server config under
`<user_defined_executable_function_drivers_config>` that knows how to take a
user-supplied code snippet and produce a runnable executable user-defined
function configuration.
New CREATE FUNCTION syntax:
CREATE [OR REPLACE] FUNCTION [IF NOT EXISTS] name [ON CLUSTER c]
ARGUMENTS (a UInt8, b String) RETURNS UInt64
ENGINE = DriverName(key1 = 'value1', key2 = 42)
AS '...code body...'
On CREATE FUNCTION, the corresponding `create_command` of the driver is
invoked: arguments are passed via `--name`, `--return`, `--args` and the
declared engine arguments; the body is sent on stdin; the driver writes the
resulting executable UDF configuration (XML or YAML) to stdout, which is
saved into the new `<dynamic_user_defined_executable_functions_path>` and
picked up by the existing executable UDF loader. The corresponding SQL is
persisted as `ATTACH FUNCTION ...` in `<user_defined>` and re-evaluated on
restart: if the dynamic configuration is still present, the driver is not
invoked; otherwise the driver is re-run to materialize it.
On DROP FUNCTION, the `drop_command` (if any) is invoked, then the dynamic
configuration file and per-function working directory are removed.
Includes a proof-of-concept driver `c_function_body`, which compiles a user
C body into a binary (inside Docker by default for build-time isolation) and
runs it inside Docker at query time with strict sandboxing (`--network=none`,
`--read-only`, dropped capabilities, no-new-privileges, unprivileged user,
resource limits) in `executable_pool` mode for batched per-row evaluation.
See #71172
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When an executable UDF driver returns a non-zero exit code from `create_command`, the resulting exception now includes the exit code and the complete stderr the driver produced. Previously the wrapper caught the generic `CHILD_WAS_NOT_EXITED_NORMALLY` from `ShellCommand::wait` and dropped the code, so callers only saw a vague "child process was exited with return code N" without the diagnostic output the driver had written. The same treatment is applied to `drop_command`. A failing `drop_command` is still caught by the DROP interpreter so cleanup of the dynamic config and the user-defined SQL entry continues, with the exit code and stderr logged. `CREATE FUNCTION` also removes the per-function working directory if the driver fails, so a failed attempt leaves no state behind. Added stateless test 04242_executable_udf_driver_errors that exercises: - non-zero exit code with multi-line stderr (asserts both code and lines) - silent driver that exits zero but produces no stdout - reference to an unknown driver - absence of leftover work-dir, dynamic config, or persisted SQL after failed creation Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
A driver describes how to create executable user-defined functions; calling the surrounding element `<function>` was misleading - it suggested the file described a single function. Rename to `<driver>` everywhere (example config, parsing in the registry, the doc comment, both stateless tests). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Workflow [PR], commit [7215a3e] Summary: ✅
AI ReviewSummaryThis PR adds experimental driver-based executable UDFs: Findings❌ Blockers
Final VerdictStatus: ❌ Block Minimum required actions: make the artifact lifecycle transactional or explicitly accepted by the owning maintainers as an experimental-risk tradeoff, make destructive drop/recovery paths fail close or persist retryable cleanup state, and close the remaining secret-log and sandbox/resource-limit gaps before exposing the example drivers to untrusted users. |
Validate `CREATE FUNCTION ... ENGINE` against existing user-defined function storage before invoking driver `create_command`, so failed creates and `IF NOT EXISTS` no-ops do not run driver side effects. Persist the normalized `ATTACH FUNCTION` query before reloading the generated executable UDF configuration. Drain driver stdout and stderr concurrently in `UserDefinedExecutableFunctionDriverInvoker` to avoid pipe-buffer deadlocks, and keep stderr attached to non-zero and abnormal child exits. Resolve relative `create_command` and `drop_command` paths relative to the driver config file, fix the example XML for `xmllint`, and clean up the dynamic executable UDF config repository during context shutdown. Tests: `ninja -C build programs/clickhouse` `./tests/clickhouse-test -b ./build/programs/clickhouse 04241_executable_udf_driver` `./tests/clickhouse-test -b ./build/programs/clickhouse 04242_executable_udf_driver_errors` Refs: #105131
Call `loadUserDefinedExecutableFunctionDrivers` during initial `clickhouse-server` startup before persisted user-defined functions are loaded. This makes source-tree driver configs such as `c_function_body` available without waiting for a later config reload. Resolve driver config directories to absolute paths before applying relative `create_command` and `drop_command` entries. Driver commands run from a per-function work directory, so a relative config directory would otherwise make source-tree example commands relative to the wrong directory. Improve the unknown-driver exception so it distinguishes an empty driver registry from a typo in the requested driver name. Tests: `ninja -C build programs/clickhouse` `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04241_executable_udf_driver.sh` `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04242_executable_udf_driver_errors.sh` `clickhouse-server` default-config smoke with `c_function_body` Refs: #105131
| } | ||
| catch (...) | ||
| { | ||
| removeDriverArtifacts(current_context, function_name); |
There was a problem hiding this comment.
removeDriverArtifacts here is destructive on failure paths where we may already have a valid function.
If this is CREATE OR REPLACE and storeObject throws (for example metadata write exception), this cleanup removes the existing dynamic config (.xml/.yaml) and working directory of the previous function version. The statement fails, but the old function is now broken.
Please make the replace flow transactional: keep old artifacts untouched until SQL metadata persistence succeeds (e.g. write generated config to temporary paths/workdir, commit metadata, then atomically swap), and only clean artifacts created by the current attempt.
|
|
||
| if (!stored) | ||
| { | ||
| removeDriverArtifacts(current_context, function_name); |
There was a problem hiding this comment.
This !stored branch can be hit under a race (CREATE FUNCTION IF NOT EXISTS on the same name from two sessions): the loser gets stored = false after the winner already committed.
Calling removeDriverArtifacts here then deletes the winner’s just-created dynamic config/working dir, so a successful create in another session gets broken by the no-op path.
Please avoid touching final artifacts when storeObject returns false; at most clean per-attempt temporary files.
| } | ||
| catch (...) // NOLINT(bugprone-empty-catch) | ||
| { | ||
| /// Ignore reload errors here - they will be surfaced when the user tries to call the function. |
There was a problem hiding this comment.
Swallowing reloadFunction exceptions here lets CREATE FUNCTION ... ENGINE = ... succeed even when the generated config is invalid/unloadable.
That leaves persisted SQL metadata pointing to a function that was never registered by the executable UDF loader, so the user gets a false-success create and a broken function state.
Can we fail the create on reload exceptions (with rollback of this create attempt) instead of logging-and-continuing?
The source-tree `c_function_body` example driver used Docker with `--security-opt=no-new-privileges`, but this option prevents containers from executing on some developer hosts. Keep Docker for the example, but drop that option from both the build container and the generated runtime command. Run the Docker containers as the server OS user so they can read and write the server-created per-function work directory without changing directory permissions. Tests: `python3 -m py_compile programs/server/user_defined_executable_function_drivers/c_function_body_driver.py` `git diff --check` `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04241_executable_udf_driver.sh` `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04242_executable_udf_driver_errors.sh` `clickhouse-server` default-config smoke with Docker-backed `c_function_body` Refs: #105131
| { | ||
| if (const auto * driver_ast = existing_ast->as<ASTCreateFunctionWithDriverQuery>()) | ||
| { | ||
| handleDriverBasedDrop(*driver_ast, current_context); |
There was a problem hiding this comment.
handleDriverBasedDrop is executed before removeObject. If removeObject throws (for example metadata write exception), the statement fails but we have already removed the dynamic config/working directory and reloaded the external UDF loader.
That leaves the function definition still persisted in SQL-object storage while the executable artifacts are gone, so the function is broken despite failed DROP.
Can we make this flow transactional by removing SQL metadata first (or otherwise rolling back artifact deletion on failure), and only then deleting driver artifacts / reloading the loader?
Create driver-owned working directories under `dynamic_user_defined_executable_functions_path` with random UUID names, as specified in #71172 (comment). Keep generated `.xml` and `.yaml` configs named after the function and store a function-named `.workdir` sidecar so `DROP FUNCTION` can invoke the driver and remove the UUID directory. This avoids reusing stale function-named directories such as `test.d` and makes the source-tree `c_function_body` example match the RFC. Also reload the executable UDF config repository on drop instead of reloading the removed function by name, avoiding a normal `not found` exception in logs. Tests: - `ninja -C build programs/clickhouse` - `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04241_executable_udf_driver.sh` - `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04242_executable_udf_driver_errors.sh` - default-config smoke with `c_function_body`: `CREATE FUNCTION`, `SELECT` returned `42`, `DROP FUNCTION` Refs: #105131 Refs: #71172 (comment)
| writeString(std::filesystem::path(result.working_dir).filename().string(), working_dir_out); | ||
| working_dir_out.finalize(); | ||
|
|
||
| std::filesystem::rename(tmp_path, final_path); |
There was a problem hiding this comment.
executeCreateFunctionWithDriver can leave a broken function artifact state on an exception in this file-write sequence.
In OR REPLACE, config_exists is true. After rename(tmp_path, final_path) succeeds, a failure in the subsequent .workdir rename enters the catch block, but final_path is not rolled back because cleanup only removes it when !config_exists.
At that point the old config has already been replaced, and we then delete result.working_dir; the statement fails, but the persisted SQL metadata still points to a config that may reference deleted artifacts.
Please make the config + .workdir update atomic as a pair (or restore the previous config on post-rename failures) so failed replace attempts do not corrupt previously working state.
Update the source-tree `c_function_body` example driver to generate an `executable_pool` function using `RowBinary` with `send_chunk_header` enabled. The generated wrapper now reads the text chunk row count, consumes that many `RowBinary` argument rows, writes the same number of `RowBinary` result rows, and flushes once per chunk. Remove the generated `setvbuf` call; chunk-level flushing is enough and matches the executable UDF protocol better than per-row line buffering. Tests: - direct generated-wrapper protocol check with one 3-row chunk - `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04241_executable_udf_driver.sh` - `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04242_executable_udf_driver_errors.sh` Refs: #105131
| return BlockIO(); | ||
|
|
||
| /// 1. Invoke driver, write generated config to dynamic_path. | ||
| DriverCreateResult create_result = executeCreateFunctionWithDriver(*create_function_query, current_context); |
There was a problem hiding this comment.
executeCreateFunctionWithDriver publishes the final dynamic config (<name>.xml/.yaml + .workdir) before storeObject decides whether this query actually won.
Under concurrent CREATE FUNCTION IF NOT EXISTS for the same name, both sessions can pass shouldRunCreateFunctionWithDriver, both run the driver, and both rename into the same final paths. The loser then gets stored = false, but by that time it may already have overwritten the winner's artifacts, so a no-op IF NOT EXISTS can still change function behavior.
Can we make artifact publication conditional on successful SQL-object commit (for example by keeping per-attempt temp paths and only atomically swapping to final names after storeObject succeeds)?
Replace the generated wrapper's `stdio`-based `RowBinary` IO with a small buffered `read` and `write` layer. Parse the text `send_chunk_header` row count manually and serialize primitive values by copying fixed-width `RowBinary` values directly to and from the in-memory buffers. This keeps the example protocol-compatible while avoiding per-value C library IO and formatting overhead in the generated executable. Tests: - generated-wrapper protocol check with one 3-row chunk - generated-wrapper benchmark: 200000 rows, about 25M rows/sec in this run - `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04241_executable_udf_driver.sh` - `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04242_executable_udf_driver_errors.sh` Refs: #105131
Extend the `c_function_body` example driver from #105131 to support the `String` type in `RowBinary`. `String` arguments and return values are exposed to the C body as `struct buf { const char * data; size_t size; }`. The generated wrapper also provides `alloc`, a simple chunk-scoped bump allocator for returning strings. The allocator keeps buffers stable for the whole chunk and resets after the chunk is flushed. Also compile generated functions with `-O3 -march=native`, while keeping the Docker build static. Tests: * `python3 -m py_compile programs/server/user_defined_executable_function_drivers/c_function_body_driver.py` * direct `RowBinary` protocol check in `build/test_c_function_body_driver_string_protocol.log` * `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04241_executable_udf_driver.sh` * `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04242_executable_udf_driver_errors.sh` * `git diff --check`
Rewrite the `c_function_body` example driver from #105131 to use the `Buffers` format instead of row-wise `RowBinary`. The generated wrapper now reads one `Buffers` block per `send_chunk_header` chunk, validates the column count and row count, exposes arguments row-by-row to the user body, and writes the result as a single-column `Buffers` block. `String` columns are parsed once per chunk into `struct buf` views over the serialized column buffer, while returned `String` values are serialized into the result column buffer after calls to `alloc`. Tests: * `python3 -m py_compile programs/server/user_defined_executable_function_drivers/c_function_body_driver.py` * direct `Buffers` protocol check in `build/test_c_function_body_driver_buffers_protocol.log` * `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04241_executable_udf_driver.sh` * `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04242_executable_udf_driver_errors.sh` * `git diff --check`
Fix executable UDF argument preparation for #105131. The executable UDF path already called `castColumnAccurate` for arguments whose actual type differs from the declared `ARGUMENTS` type, but then restored the original `ColumnWithTypeAndName`. This made calls such as `SELECT test(1, 2)` pass literal integer columns to a function declared as `UInt64`. With the `Buffers` format the external process receives only raw column buffers, so the generated wrapper sees an `Int8`-sized buffer where it expects `UInt64` and reports `input column read error`. Keep the casted column and type, and add coverage for a `c_function_body` function declared with `UInt64` arguments but called with integer literals. Reported query: `SELECT test(1, 2)` Tests: * `ninja -C build programs/clickhouse` * `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04241_executable_udf_driver.sh` * `CLICKHOUSE_BINARY=./build/programs/clickhouse tests/queries/0_stateless/04242_executable_udf_driver_errors.sh` * `git diff --check`
| working_directory, engine_argument_values); | ||
|
|
||
| auto log = getLogger("UserDefinedExecutableFunctionDriverInvoker"); | ||
| LOG_DEBUG(log, "Invoking driver '{}' create_command: {}", driver.name, cmd.describe()); |
There was a problem hiding this comment.
cmd.describe() expands every configured driver env entry as KEY=VALUE into the debug log, and this path is used for both create_command and drop_command. Driver environment values are an operator-facing config surface and can reasonably contain credentials or tokens for compilers, package registries, or sandbox infrastructure; engine argument values may also carry user-supplied data. Logging the fully expanded command leaks those values to server logs whenever debug logging is enabled.
Please redact values here (for example log only env variable names plus the command path, or replace values with <redacted>) and avoid logging raw engine argument values unless they are explicitly non-secret.
There was a problem hiding this comment.
Redacted the driver-invocation debug log in 8c28b9f: buildCommand now builds a separate redacted_description that replaces every driver env value and engine-argument value with [HIDDEN], while keeping the names and the non-secret structural arguments (command path, --name/--return/--args, working directory) visible. The arguments actually passed to the driver are unchanged. Verified at runtime: a driver with a secret env var and a secret engine argument now logs ... MY_TOKEN=[HIDDEN] ... --apikey [HIDDEN], with the raw values appearing zero times in the LOG_DEBUG.
One caveat I'm flagging rather than silently leaving: because driver env vars are passed as /usr/bin/env KEY=VALUE ... argv tokens, ShellCommand::logCommand still prints the raw KEY=VALUE and engine-argument values at TRACE level (Will start shell command '/usr/bin/env' with arguments ...). Fully closing that would mean either redacting in the shared ShellCommand argv trace (affects every shell-command caller) or passing env through the child's environment instead of as argv — both broader than this log line, so I left them for you to decide and kept this thread open.
There was a problem hiding this comment.
Thanks for the debug-log redaction, but the same values are still emitted through ShellCommand at TRACE: buildCommand still appends both driver env values (KEY=value) and engine argument values into cmd.arguments (src/Functions/UserDefined/UserDefinedExecutableFunctionDriverInvoker.cpp:77-105), and ShellCommand::executeImpl calls logCommand, which logs every argv entry verbatim (src/Common/ShellCommand.cpp:139-150). So a server with trace logging still records raw values such as MY_TOKEN=... and --apikey ....
Please either pass driver env through the child environment rather than argv and add a redaction path for engine arguments, or teach ShellCommand::Config which argv positions must be redacted before logCommand.
The `system.query_log` query added in `04241_executable_udf_driver.sh` for the executable-UDF classification assertion was missing the `current_database = currentDatabase()` condition that the dedicated style check (`ci/jobs/scripts/check_style/various_checks.sh`) requires. The query runs in an isolated single-process `clickhouse-local`, so the condition is satisfied and the assertion still matches the expected row. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105131&sha=77cfd0fbd0ba5ba4506a7ccae86d9d0d19d629b6&name_0=PR&name_1=Style%20check Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`UserDefinedExecutableFunctionDriverInvoker` logged the fully expanded `/usr/bin/env ...` command line at debug level via `DirectCommand::describe`, which included every driver `env` `KEY=VALUE` entry and every engine argument value. Driver `env` values and engine-argument values are an operator/user-facing surface that can carry credentials or tokens, so this leaked secrets into the server log whenever debug logging was on. Build the logged form with the values replaced by `[HIDDEN]` while keeping the variable/argument names and the non-secret structural arguments visible. The arguments actually passed to the driver keep the real values and are never logged. Addresses review feedback: #105131 (comment) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed 1. Style check (the only failing check), 2. Redact driver Caveat I'm flagging rather than silently leaving (kept the thread open): because env is passed as No master-merge (merge-base As in the previous pushes, the one non-dismissed AI finding is narrow, reviewer-requested, reversible, and happy-path-preserving; happy to revert either commit if you'd prefer a different approach (e.g. resolving the env leak at the |
|
Dear @vdimir, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
The `query_log` assertion block added to `04241_executable_udf_driver` used a global `SYSTEM FLUSH LOGS;`, which the `various` style check (`ci/jobs/scripts/check_style/various_checks.sh`) rejects with "Please use SYSTEM FLUSH LOGS log_name over global SYSTEM FLUSH LOGS". The block only reads from `system.query_log`, so flush just that log. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105131&sha=8c28b9ff0ff5bfb268e28ba8b8294bd3ebc6cab1&name_0=PR&name_1=Style%20check Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…drivers Resolve include-region conflicts in programs/local/LocalServer.cpp and programs/server/Server.cpp: master added <Functions/pointInPolygon.h> and this branch added <Functions/UserDefined/UserDefinedSQLFunctionFactory.h> at the same location; keep both (both are used in each file). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| dynamic_dir.push_back('/'); | ||
|
|
||
| const String escaped = escapeForFileName(function_name); | ||
| const String working_dir = dynamic_dir.empty() ? String() : DriverUtils::readDriverWorkingDirectory(current_context, function_name); |
There was a problem hiding this comment.
DROP FUNCTION needs the persisted .workdir sidecar to run the driver cleanup in the same context that CREATE used. If this file is missing or empty, readDriverWorkingDirectory returns an empty string here, runDropCommand omits env -C, and the drop driver runs from the server's current directory before the code removes the dynamic config and SQL metadata. For DockerC, that makes stop_docker_container derive a different container prefix and exit successfully without removing driver-owned state; after this drop there is no durable metadata left to retry cleanup.
Please fail close when a driver-backed function has no working-directory metadata (or persist enough cleanup state outside the sidecar) before deleting artifacts/SQL metadata.
Startup recovery (`reloadDriverBasedFunctions`) re-runs the driver to rebuild lost dynamic state and already handles a missing `.workdir` sidecar or working directory. A *corrupted* sidecar (invalid UUID) was not handled: the recreate path re-read the same sidecar via `readDriverWorkingDirectory`, which throws on the invalid UUID before the driver runs, so no replacement config/workdir was written and the function stayed permanently unavailable. Make the previous-working-directory read best-effort in `executeCreateFunctionWithDriver`: the value is only used to clean up the old artifacts after a successful replace, so an unreadable sidecar is treated as "no previous working directory" and the fresh config/workdir/sidecar overwrites the broken state. Added `04489_executable_udf_driver_invalid_workdir` covering recovery from a corrupted sidecar. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Fixed the one narrow, non-deferred AI finding (invalid
|
|
CIEverything is green except one job:
There is no open tracking issue for it. @groeneai, please investigate the flaky
Why no re-mergeThe branch is behind Review threadsThe AI review verdict is No new actionable, non-deferred items remain. Blocked only on the maintainer decision on the deferred design items and the |
|
@alexey-milovidov Fix already in progress: #107438 (open, approved by @ alesapin). Tracked since #100651. Root cause: on macOS, #107438 downgrades only the |
Adds a "Driver-based Executable User Defined Functions" section to `docs/en/sql-reference/functions/udf.md`, documenting the new public SQL and configuration surface introduced by this feature: - the experimental gate (`allow_experimental_executable_udf_drivers`) and the `user_defined_executable_function_drivers_config` / `dynamic_user_defined_executable_functions_path` configuration keys, - the driver configuration schema (`name`, `create_command`, `drop_command`, `engine_arguments`, `env`), - the driver invocation contract (`--name`/`--return`/`--args`, declared engine arguments, code body on stdin, generated config on stdout with XML/YAML auto-detection), - the `CREATE FUNCTION ... ENGINE = DriverName(...) AS '...'` and `DROP FUNCTION` lifecycle, - persistence as `ATTACH FUNCTION` and restart recovery, - limitations (experimental, non-replicated storage, `RESTORE` not re-running the driver), - the proof-of-concept `DockerC`/`GVisorC`/`UnsafeC` example drivers and their not-installed-by-packages status. This addresses the missing-documentation review feedback for the new feature. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
continue-pr status (automated pass) Action taken: Added the missing user documentation for the feature — pushed CI: Fully green — the AI Review verdict (❌ Block): Every blocker and major in the verdict is marked Open human-reviewer threads left for your/the reviewer's call (both predate substantial code evolution and
No further code changes were made beyond the documentation. Ready for your review/merge decision. |
|
Clarification on the docs commit: the documentation finding ( I added the docs anyway because documentation is mandatory for a new feature per the project conventions, and it is purely additive (one isolated commit touching only |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 785/1022 (76.81%) · Uncovered code |
|
Public CIFully green on the current head
|
`UserDefinedExecutableFunctionDriverInvoker` logged the fully expanded `/usr/bin/env ...` command line at debug level via `DirectCommand::describe`, which included every driver `env` `KEY=VALUE` entry and every engine argument value. Driver `env` values and engine-argument values are an operator/user-facing surface that can carry credentials or tokens, so this leaked secrets into the server log whenever debug logging was on. Build the logged form with the values replaced by `[HIDDEN]` while keeping the variable/argument names and the non-secret structural arguments visible. The arguments actually passed to the driver keep the real values and are never logged. Addresses review feedback: ClickHouse#105131 (comment) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…df-drivers Drivers for executable user-defined functions
Implements the feature requested in #71172 - operator-supplied "drivers" that turn a user code snippet into an executable user-defined function. Supersedes the draft in #77128 (which used a different, mostly-incorrect design).
A driver is described by an XML/YAML file under
<user_defined_executable_function_drivers_config>. It declares:name- the driver name as used inCREATE FUNCTION ... ENGINE = <name>(...)create_command- shell script invoked to create a UDF from a code snippetdrop_command(optional) - invoked when the function is droppedengine_arguments(optional) - allowed args insideENGINE = Driver(a='x', b=1), with<required>flagenv(optional) - environment variables passed to the driverNew SQL form:
CREATE FUNCTIONinvokescreate_commandwith--name,--return,--args, plus any declared engine arguments, sets the configured env vars, sends the user body on stdin, and reads the resulting executable UDF configuration from stdout. Format is auto-detected (XML if it starts with<, otherwise YAML) and written into<dynamic_user_defined_executable_functions_path>; the existing executable UDF loader picks it up. The originating SQL is persisted asATTACH FUNCTION ...in<user_defined>so it survives restart. On server start, if a persisted ATTACH has no matching file in the dynamic directory, the driver is re-run.DROP FUNCTIONinvokesdrop_command(if present), removes the dynamic config and the per-function working directory, reloads the UDF loader, and removes the persisted SQL.If
create_commandexits non-zero, an exception is thrown that includes the exit code and the full driver stderr; the per-function working directory is removed so failed attempts leave no state.Includes a proof-of-concept driver
c_function_body: takes a C function body, generates a TabSeparated stdin/stdout wrapper, compiles it inside a sandboxed Docker container, and emits anexecutable_poolUDF that runs the compiled binary inside another sandboxed Docker container (--network=none --read-only --cap-drop=ALL --security-opt=no-new-privileges --user 65534:65534+ memory/cpu/pids limits).CLICKHOUSE_C_DRIVER_FORCE_LOCAL=1switches to direct compile + run for environments without Docker (used by the tests).Stateless tests:
04241_executable_udf_driver- create, call, simulated config-loss recreate, drop, file cleanup04242_executable_udf_driver_errors- non-zero exit code + multi-line stderr propagation, empty driver output detection, unknown driver detection, absence of leftover state on failureChangelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added "drivers" for executable user-defined functions. A driver declared in
<user_defined_executable_function_drivers_config>can be used inCREATE FUNCTION name ARGUMENTS (...) RETURNS T ENGINE = DriverName(...) AS '...code...'to compile or otherwise process a user code snippet at function-creation time and produce a runnable executable UDF. The resulting configuration is stored in<dynamic_user_defined_executable_functions_path>, and the originating query is persisted asATTACH FUNCTIONso the function survives server restarts. A proof-of-conceptc_function_bodydriver compiles and runs C function bodies inside sandboxed Docker containers inexecutable_poolmode.Documentation entry for user-facing changes
docs/en/sql-reference/functions/udf.md.Note
High Risk
Adds a new SQL pathway that executes operator-configured external driver commands, writes/loads generated UDF configs from disk, and changes startup/reload behavior; this touches execution, filesystem, and security-sensitive surfaces.
Overview
Adds driver-based executable UDFs: a new
CREATE/ATTACH FUNCTION ... ENGINE = DriverName(...) AS 'code'SQL form that invokes an operator-configuredcreate_command, persists the generated XML/YAML UDF config underdynamic_user_defined_executable_functions_path, and stores the originating query asATTACH FUNCTIONfor restart durability.Introduces a driver registry loaded from
<user_defined_executable_function_drivers_config>(on startup and config reload), wires it intoclickhouse-serverandclickhouse-local, and adds startup recovery that re-runs drivers for persisted functions whose dynamic configs are missing.Extends the executable UDF loader to watch the dynamic config directory, supports per-function working directories for direct execution, and adds optional
<command_pipe_capacity>plumbing down toShellCommandpipe sizing.Includes proof-of-concept C-body drivers/scripts and stateless tests covering create/call/recreate/drop flows plus failure cleanup and error propagation.
Reviewed by Cursor Bugbot for commit 5576b9e. Bugbot is set up for automated code reviews on this repo. Configure here.