Repository navigation
Move the driver logic to Java on top of C API v2 entry points - #1017
Robinho-MR wants to merge 10 commits into
Conversation
…nerated native entry points
|
Thanks for the update! It will take some time to review it, meanwhile can you please check, whether the former |
|
@staticlibs thanks, I looked at it. In this PR What overlaps
What differs
What I'd do
A full replacement (the I'd rather do steps 1 and 2 as a separate follow-up PR, so that this one stays reviewable and the results/perf here don't change. Does that match what you had in mind, or did you want the lazy reader to be the only path? |
Yes, I agree with this. Ultimately we want to unify both code paths, modifying their lazyness and strictness (as needed and as much as allowed by JDBC spec). But it is indeed better to do this as a follow-up. I will submit the review to this PR (in its current form) when the review is ready. |
|
General comments:
/*
* Class: org_duckdb_DuckDBBindings
* Method: duckdb_init_get_column_count
* Signature: (Ljava/nio/ByteBuffer;)J
*/Also please check whether the following comments can be addressed: [
{
"file": "src/main/java/org/duckdb/DuckDBInstances.java",
"line": 27,
"summary": "`allowed_directories` and `allowed_paths` are now set with SET GLOBAL after startup. DuckDB refuses that when `enable_external_access=false`, which the old `config.cpp` worked around by writing them straight into DBConfig.",
"failure_scenario": "Properties `{enable_external_access=false, allowed_directories=[\"/data\"]}` is the usual sandboxing setup. `initInstance` calls `duckdb_v2_config_set_option_text`, which throws 'Cannot change allowed_directories when enable_external_access is disabled' (custom_settings.cpp:301), so `DriverManager.getConnection` fails. Before this change it succeeded."
},
{
"file": "src/main/java/org/duckdb/DuckDBV2Appender.java",
"line": 65,
"summary": "The appender takes its columns from `SELECT * FROM table`, which includes generated columns. It then builds `INSERT INTO t (all columns) SELECT * FROM buffer`, and DuckDB rejects that whenever the table has a generated column.",
"failure_scenario": "`CREATE TABLE t(a INT, b INT GENERATED ALWAYS AS (a*2))`. Appending through `DuckDBAppender` fails on every `flush()` with 'Cannot insert into a generated column'. The appender also asks the caller for 2 values per row instead of 1. The old `duckdb_appender_create_ext` only exposed physical columns and worked."
},
{
"file": "src/main/java/org/duckdb/DuckDBV2Appender.java",
"line": 215,
"summary": "Column defaults are looked up in `duckdb_columns()` with an exact, case-sensitive `table_name` match. When no schema or catalog is given, the lookup is not limited to one table, so defaults are missing or taken from the wrong table.",
"failure_scenario": "(a) Table created as `Foo`, appender opened as `foo`: no rows match, so `appendDefault` writes NULL instead of the declared DEFAULT. (b) Both `main.t` and `temp.t` exist and schema is null: the rows of both tables come back interleaved by column_index, so column i gets another table's default."
},
{
"file": "src/main/java/org/duckdb/DuckDBCore.java",
"line": 1390,
"summary": "`variantToVector` copies only the top-level vector's data (`retainConstlenData`) and then destroys the temporary vector. Child vectors of LIST/STRUCT/ARRAY values still point into the freed native memory (use-after-free).",
"failure_scenario": "`SELECT [1,2,3]::VARIANT`, then `rs.getObject(1)` and reading the array. The child INTEGER vector's direct buffer points into the destroyed `single` vector, so the read returns garbage or crashes the JVM under ASan. No test covers nested VARIANT values."
},
{
"file": "src/main/java/org/duckdb/DuckDBSingleValueAppender.java",
"line": 34,
"summary": "The rewritten `DuckDBSingleValueAppender` holds native collection, statement and chunk handles tied to the instance, but it is not tracked in `conn.appenders`. Closing the connection does not close it, and a later `close()` uses freed instance memory.",
"failure_scenario": "Open a connection, create the appender, append rows, close the connection (last ref, so the instance is destroyed), then call `appender.close()`. `appendChunk` and `column_data_collection_clear/destroy` run against a freed buffer manager. The old engine Appender held a `shared_ptr<ClientContext>`, which kept the DB alive."
},
{
"file": "src/main/java/org/duckdb/DuckDBCore.java",
"line": 475,
"summary": "`getSchema`, `getCatalog`, `setSchema` and `setCatalog` now run SQL statements on the user's connection instead of reading or setting the catalog search path directly.",
"failure_scenario": "With `jdbc_stream_results=true`, calling `conn.getSchema()` (or DatabaseMetaData code that calls it) while a streaming ResultSet is open runs a new query, which invalidates the open stream; the next `rs.next()` fails. Inside a transaction that already failed (autoCommit=false), `getSchema()` now throws 'Current transaction is aborted' where it used to return the schema."
},
{
"file": "src/main/java/org/duckdb/DuckDBInstances.java",
"line": 249,
"summary": "For cached instances, `dbAddress` is now a 32-bit `String.hashCode` of the path (ORed with 1) instead of the real DatabaseInstance address, so two different database files can share an identity.",
"failure_scenario": "Two cached databases whose normalized paths collide in `hashCode`, both opened with a JFR memory monitor. `DuckDBMemoryMonitor.monitors.compute(conn.dbAddress, ...)` merges them into one monitor, so memory is reported for the wrong DB and the monitor can be torn down while the other DB is still open."
},
{
"file": "src/main/java/org/duckdb/DuckDBCore.java",
"line": 706,
"summary": "`exportArrow` first copies the whole result, including all of a streamed result, into a ColumnDataCollection, then runs a second query to produce Arrow batches. Streaming results are fully held in memory, the rows are copied twice, and batch sizes are no longer exact (the TestArrow assertions were loosened to hide this).",
"failure_scenario": "A large streaming SELECT exported with `arrowExportStream`: the old code streamed batches directly from the QueryResult. The new code buffers every row in memory before the first batch, which can run out of memory on results that used to stream. Consumers that relied on fixed batch sizes now get variable, smaller batches."
},
{
"file": "src/main/java/org/duckdb/DuckDBV2Appender.java",
"line": 234,
"summary": "Each `appendDefault` call runs a full SQL query (`SELECT <default expr>`, which takes the connection's query lock) for every row and column. Each flush also re-plans the unprepared INSERT ... SELECT from scratch.",
"failure_scenario": "Appending 1M rows with 2 defaulted columns runs 2M separate parse/bind/execute round trips over JNI, plus one fresh INSERT plan per 2048-row chunk. Before, defaults were evaluated inside the engine's appender. Cheaper: rely on the column defaults of `INSERT INTO t (non-default columns)`, or prepare the INSERT once and reuse it, instead of evaluating defaults row by row."
}
] |
Moves the driver logic from C++ into Java, on top of thin native entry points that map 1:1 to C API v2 calls (
duckdb_v2_*inDuckDBBindings).src/jnidoes not include any engine header anymore. This is the direction discussed in #1010, it replaces that approach (the stable C++ API) with the C API v2.Details
What changed
src/jni/bindings_v2.cpphas the thin JNI entry points, one per C API v2 call, without driver logic: instances, connections, configuration and custom options, parsing, prepared statements, execution, schemas, results, values, types, vectors, column data collections, profiling. The names are the C API names, so they can later be replaced by FFM calls.DuckDBCoreimplements prepare, multi-statement handling, execute, pending queries, streaming and materialized results, result metadata, fetching (the formerProcessVector), the string casts, parameter conversion, schema and catalog in Java. TheDuckDBNative.duckdb_jdbc_*signatures that the rest of the driver calls are kept, they now delegate toDuckDBCoreandDuckDBInstances.DuckDBInstancesopens the instances (duckdb_v2_instance_open_sharedwith an initializer for the shared ones, an environment of its own for the others) and connections, registers thejdbc_stream_resultsoption, writes the settings that need a running instance, copies the session settings induplicate(). The connection reference is the C API v2 connection handle, the instance is reference counted in Java.DuckDBAppenderandDuckDBSingleValueAppenderuseDuckDBV2Appender: the chunks are collected into a column data collection and a preparedINSERT INTO table SELECT * FROM <collection>is executed on flush.src/jni/arrow_export.cpp. An Arrow stream is a C structure with callbacks, so it cannot be implemented in Java. The export binds the rows of a result toSELECT * FROM <rows>that runs with the Arrow result format on a connection of its own, the stream owns it and is closed with the connection if it is not released before.registerArrowStreamregisters the stream with a table function (__jdbc_arrow_stream_scan, written over the C API v2 table function and Arrow importer calls) that a view of the stream selects from.functions.*,generator.py),config.cpp,holdersof the engine,types.cpp,arrow.cpp, the appender bindings of the C API v1.Value::VariantToValue), the next run of the vendoring workflow replaces it.Differences that I know of
C API v2 has one live result per connection. Queries on a connection are run one by one (
DuckDBConnection.queryGate), and a result that is streamed (jdbc_stream_results) blocks the next query on its connection until it is closed.The batches of an exported Arrow stream are at most the requested size and can be smaller, as the threads of the query fill them (the Javadoc and two Arrow tests say so now).
Preparing a statement plans it twice, once to prepare and once (
statement_bind) to get the column and parameter types, as C API v2 has no metadata of a prepared statement.Error messages come from the C API v2. A shared instance that is opened with a different configuration fails with a message of the C API v2.
Reading results: the vectors are read from their raw data in Java: the fixed-size values and the validity directly from the vector buffers, the strings of up to 12 bytes from the 16-byte entries of the vector, and the longer ones (or the types that are read as strings, e.g. ENUM and INTERVAL, after a cast by the engine) with one call per vector. There are no calls per value.
Native calls per query: a few calls per result (the names and the type IDs of the columns are read for all the columns at once, the config and the factory of the connection are kept, the metadata of a statement is cached when the types have no parameters, the types of a prepared statement are read when its metadata is asked), which is what matters for the small queries.
Performance compared to the unchanged driver (
main), on the same loaded machine (load average of 70 on 96 cores, so noisy), seconds, lower is better:mainA tiny query is about 10-15% slower: the part that is left is in the C API v2 result (
prepared_statement_execute, then oneresult_fetch_chunkfor the rows and one for the end of the result), not in the driver.Tests
TestDuckDBJDBC(all the test classes it runs): 595 pass. The one failure istest_table_function_multiple_threads, which expects as many threads as processors and gets 1 when the machine is loaded, same as on the unchanged driver.src/test/external/test_arrow.sh: 35 of 35 pass.TestBindingshas the appender tests moved toDuckDBV2Appender, as the appender bindings of the C API v1 do not exist anymore.