tdcmeehan opened a new pull request, #60349:
URL: https://github.com/apache/spark/pull/60349

   ### What changes were proposed in this pull request?
   
   This PR adds native scalar functions: scalar functions implemented in a 
native library, for example in C++ or Rust, that Spark calls in the executor 
JVM through the Arrow C data interface, with no Python worker.
   - They ship in the native packages (`.sparkpkg`) of native data sources 
(SPARK-60101).
   - They follow the conventions of `spark_datasource.h` as version 1 settled 
them (SPARK-60723).
   - A library can implement both interfaces.
   
   1. **The C interface `spark_udf.h`, version 1**, next to 
`spark_datasource.h`.
      - **Init:** `spark_udf_init(host, &library)` runs once per JVM and 
negotiates the version as `spark_ds_init` does.
      - **The lifecycle of each call of a function in a query, in each task:**
        - `create` gets the function's name, the argument and result schemas, 
the session time zone and the task context;
        - `eval` runs once per batch;
        - `close` runs exactly once, also after a failure or an early stop.
      - **Batches:** a batch is one struct array with one child per argument. 
Inputs may have offsets. A result has one value per row, offset 0 and the 
declared type, and Spark checks it before reading it.
      - **Errors** are `int` return codes plus an optional `last_error`; no 
exception or panic may cross the interface.
      - **Growth:** structs start with their size and only grow at the end, so 
later kinds, such as table functions, can be added within version 1.
   2. **The manifest.**
      - **New fields:** `spark-native-datasource.json` gains `udfAbiVersion` 
and `functions`. Each function has a `name`, a `kind` (`scalar`), argument and 
result types as DDL strings, and `deterministic`.
      - **Function-only packages:** `dataSources` may now be absent or empty 
when `functions` is not, and such a package needs no `abiVersion`, the data 
source version. With data sources, `abiVersion` stays required.
      - **Checks:** they run when a session adds a package, and again when a 
function is registered. They cover the version 1 types, NUL in names, and the 
interface version.
      - **Unknown kinds:** functions of a kind that Spark doesn't know are 
skipped, so that later packages still load.
   3. **Registration.**
      - **The statement:** `CREATE [OR REPLACE] TEMPORARY FUNCTION f AS '<name 
in the manifest>' USING PACKAGE '<package>'`, with a new function resource 
type, `package`.
      - **Where the package comes from:** a package added with 
`spark.addArtifact`, one under `spark.sql.dataSource.native.paths`, or a path 
or URI.
      - **Types:** they come from the manifest, so the driver never loads the 
library, and the analyzer casts the arguments to them.
      - **Calls:** functions are called by name from SQL and with 
`call_function`, in classic and in Spark Connect, with no change to the 
protocol.
      - **Persistent functions:** `CREATE FUNCTION ... USING PACKAGE` without 
`TEMPORARY` fails with `UNSUPPORTED_FEATURE.PERSISTENT_NATIVE_UDF` for now, 
since storing a package resource in the catalog needs its own design.
   4. **Evaluation.**
      - **The plan:**
        - the rule `ExtractNativeUDFs` runs first in the "Extract UDFs" batch;
        - the logical node `EvalNativeUDFs`, in catalyst, lets filters and 
limits move below it, as for the Python and external UDF nodes;
        - `EvalNativeUDFsExec` evaluates the calls in the task thread.
      - **Batches:** they are written with `ArrowWriter`, capped by 
`spark.sql.execution.arrow.maxRecordsPerBatch` and `maxBytesPerBatch`.
      - **Which calls share an operator:** sibling calls on one child share an 
operator and its batches, a nested call gets one operator per level, and native 
calls mix with Python UDFs in both orders.
      - **Output rows:** they are read back from the input vectors when every 
input column is an argument; otherwise the input rows are kept until the 
batch's results arrive.
      - **The bindings:** `NativeUdfLibrary` reaches the Foreign Function and 
Memory API through `NativeLibrary`'s method handles, so Spark still compiles on 
older JDKs; native functions run on Java 22 or later.
      - **Driver-side work:** partition pruning and runtime filters leave 
native calls out, as they do Python UDFs.
      - **Call sites rejected at analysis:** a native call inside a lambda, and 
a call that needs both sides of a non-inner join.
   5. **The setting and the errors.**
      - **The setting:** `spark.sql.udf.native.enabled`, static, true by 
default, as `spark.sql.dataSource.native.enabled` is.
      - **New error classes:** `NATIVE_UDF_ERROR` (38000), 
`NATIVE_UDF_DISABLED`, `NATIVE_UDF_NOT_FOUND`, `NATIVE_UDF_PACKAGE_NOT_FOUND`, 
`NATIVE_UDF_UNSUPPORTED_JAVA_VERSION`, `NATIVE_UDF_UNSUPPORTED_KIND` and 
`NATIVE_UDF_UNSUPPORTED_PLATFORM`.
      - **New subclasses:** `UNSUPPORTED_FEATURE.NATIVE_UDF_IN_LAMBDA`, 
`.NATIVE_UDF_IN_ON_CLAUSE`, `.PERSISTENT_NATIVE_UDF`, and 
`INVALID_NATIVE_DATA_SOURCE_PACKAGE.UNSUPPORTED_UDF_ABI_VERSION`.
   6. **Tests:** a C++ test library, `test_native_udf.cc`, written against the 
header, and three suites (see below).
   7. **Distribution:** `dev/make-distribution.sh` copies `spark_udf.h` into 
`include/`, next to `spark_datasource.h`.
   
   New classes, under `sql/core/src/main/.../execution/datasources/v2/ffi/` 
unless noted:
   
   ```
   NativeFunctionSpec.scala      the manifest's function entries and their 
checks
   NativeFunctionRegistry.scala  CREATE TEMPORARY FUNCTION ... USING PACKAGE, 
and the NativeUDF expression
   NativeUdfLibrary.java         the FFM bindings of spark_udf.h
   ExtractNativeUDFs.scala       the optimizer rule
   EvalNativeUDFsExec.scala      the strategy and the physical node
   NativeUDFEvaluator.scala      batches, calls, result checks and cleanup
   catalyst/.../plans/logical/nativeUDFOperators.scala   the logical node 
EvalNativeUDFs
   ```
   
   Changes to the native data source code, for its owners. None changes the 
behavior of a package without functions.
   - **`NativeLibrary.java`:** `private` is removed from seven members (`C`, 
`Ffm`, `rootCause`, `LogLevel`, `Memory`, `toCString`, `readCString`), so the 
function bindings reuse them.
   - **`NativeDataSourcePackage.scala`, the manifest:**
     - the manifest gains the two fields, and its `abiVersion` becomes an 
`Option[Int]`;
     - the parser accepts a package with only functions, which may omit 
`abiVersion`; with data sources, `abiVersion` is required and checked as 
before, and a present one is always checked;
     - a package with an invalid `functions` field, or with a `udfAbiVersion` 
that Spark does not support, is now rejected.
   - **`NativeDataSourcePackage.scala`, the loader:**
     - function libraries get their own cache;
     - extraction and `spark_ds_init` now run under a lock per library file, 
which `spark_udf_init` also takes, so a library with both interfaces never 
initializes them at the same time.
   - **`NativeDataSourceRegistry.scala`:** `configuredPackageFiles` becomes 
`private[ffi]`.
   - **`spark_datasource.h`:** unchanged.
   
   ### Why are the changes needed?
   
   Native data sources let Spark run native code in the JVM through a stable C 
interface. Today there is no such path for scalar functions. Native code can be 
called from a Python UDF, which sends every batch to a Python worker and back, 
or from a Scala UDF through JNI, which each project writes by hand.
   
   This PR lets a native library implement functions once, against a versioned 
C interface:
   - they ship in the same packages and are distributed as native data sources 
are;
   - they are registered with SQL;
   - they are called from SQL, the DataFrame API and Spark Connect, without a 
Python worker.
   
   Measured with a Spark Connect server on `local[1]`, with the default batches 
of 10,000 rows. The numbers are ns per row, from the best of 3 runs at two 
sizes, and every run checks its sum.
   
   | | `add_one` (bigint) | `shout` (string) | edit distance (two strings) |
   |---|---:|---:|---:|
   | built-in expression | 0.69 | 76.1 | 363.9 |
   | native function (this PR) | 67.5 | 189.2 | 468.2 |
   | Python `arrow_udf` with pyarrow compute | 107.5 | 209.8 | 5,704.9 (a 
Python loop; no pyarrow kernel) |
   | Python `@udf` (Arrow-optimized, the default) | 103.9 | 208.6 | 5,926.1 |
   | Scala UDF (classic session) | 1.56 | 143.6 | 221.0 |
   
   - **Against Python:** native functions are faster than Python UDFs, by 1.5x 
for the int function and by an order of magnitude for compute-heavy work.
   - **Against built-ins and Scala UDFs:** they are slower. Profiles put under 
2% of the time in the library, and under 1.5% in the C data interface. The rest 
is the conversion between rows and Arrow around the call, including a per-row 
synchronization between the consumer and the end-of-task listener. Reducing 
that is a follow-up and needs no change to the interface.
   - **Caveat on edit distance:** the edit distance rows cover ids of different 
lengths per case (6 digits for the Python cases, 7 for the built-in and native 
ones), so they compare only roughly.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes, on master. It's a new feature, and native data sources have not been 
released yet.
   - **New SQL:** `CREATE [OR REPLACE] TEMPORARY FUNCTION ... USING PACKAGE`.
   - **A new static setting,** `spark.sql.udf.native.enabled`, true by default.
   - **New error classes,** listed above.
   - **Native packages:**
     - a manifest may now list functions;
     - a package may have only functions, and then needs no `abiVersion`;
     - a package with an invalid `functions` field, or with an unsupported 
`udfAbiVersion`, is now rejected when it is added. Before, such a field was 
ignored.
   - **The binary distribution** contains `include/spark_udf.h`.
   
   For example, with a package `udfs.sparkpkg` whose library implements 
`add_one`:
   
   ```python
   spark.addArtifact("udfs.sparkpkg")
   spark.sql("CREATE TEMPORARY FUNCTION add_one AS 'add_one' USING PACKAGE 
'udfs.sparkpkg'")
   spark.sql("SELECT add_one(id) FROM range(3)").show()
   spark.range(3).select(call_function("add_one", "id")).show()
   ```
   
   ### How was this patch tested?
   
   **New tests.** The suites compile `test_native_udf.cc` with the C++ compiler 
of the machine, as the data source suites do, and skip when there is no 
compiler or before Java 22.
   - **`NativeUDFSuite` (107 tests).** It covers:
     - every version 1 type, nested ones too;
     - nulls; `useLargeVarTypes`; inputs with offsets, through the bindings;
     - concurrent tasks and states per call;
     - batches capped by records and by bytes;
     - errors with and without `last_error`; invalid results; failed `create` 
and init;
     - version negotiation and table sizes;
     - cancellation, and the end of a task during `eval`;
     - planning: sibling and nested calls, mixes with Python UDFs, filters and 
limits pushed below, partition pruning, joins, aggregates, lambdas;
     - registration and its errors, and the manifest checks;
     - the error before Java 22.
   - **`NativeUDFClusterSuite` (2 tests):** `local-cluster`, with the package 
distributed to the executors.
   - **`NativeUDFConnectSuite` (1 test):** `CREATE TEMPORARY FUNCTION`, then 
SQL and `call_function`, through Spark Connect.
   
   **Runs.**
   - **Java 25 (OpenJDK 25.0.5):** all pass, except the test for Java before 
22, which cancels there by design.
   - **Java 21 test JVM:** the native tests skip, and the Java-before-22 test 
passes.
   
     ```
     build/sbt -Phive \
       'sql/testOnly *NativeUDFSuite *NativeUDFClusterSuite 
*NativeDataSourceSuite *NativeDataSourceClusterSuite' \
       'connect/testOnly *NativeUDFConnectSuite *NativeDataSourceConnectSuite'
     ```
   
     `JAVA_HOME` points to a JDK 25. The tests that mix in Python UDFs need 
`PYSPARK_PYTHON` set to a Python with pyarrow and pandas.
   - **Existing suites, all passing:**
     - the native data source suites;
     - `FilterPushdownSuite`, `LimitPushdownSuite`;
     - `PruneFileSourcePartitionsSuite`, `PushDownUtilsSuite`, 
`DataSourceV2EnhancedPartitionFilterSuite`, `InjectRuntimeFilterSuite`, 
`PruneHiveTablePartitionsSuite`;
     - `SparkThrowableSuite`, `DDLParserSuite`.
   - **The header** compiles as C11 and as C++17 with `-Wall -Wextra -Werror`, 
alone and with `spark_datasource.h` in either order, and a compile-time check 
asserts that its structs end without padding. The test library compiles with 
each of its macro variants.
   - **Style:** scalastyle, checkstyle and scalafmt pass.
   - **The measurements above** were run on a local machine, not in GitHub 
Actions.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Claude Code (Claude Opus 5.5)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to