Title: fix: serialise native handle lifetime against concurrent close by andygrove · Pull Request #115 · apache/datafusion-java · GitHub
Open Graph Title: fix: serialise native handle lifetime against concurrent close by andygrove · Pull Request #115 · apache/datafusion-java
X Title: fix: serialise native handle lifetime against concurrent close by andygrove · Pull Request #115 · apache/datafusion-java
Description: Which issue does this PR close? Closes #40. Rationale for this change SessionContext and DataFrame each held their native pointer in a plain long nativeHandle, and every public method followed the pattern if (nativeHandle == 0) throw new IllegalStateException(...); someNativeCall(nativeHandle, ...); The check and the use are separate operations on a non-volatile field, so a close() on another thread can free the native Box in between: thread A reads a live handle and enters JNI, thread B zeroes the field and Rust drops the Box, and thread A dereferences freed memory. The == 0 guard is a TOCTOU, not a fix. The docs said "not thread-safe", which made this defensible but not comfortable — the first multi-threaded user (a server, a Flink or Spark integration) would have hit it in production rather than in dev. It is also a shape that recurs every time a new long-lived handle is added. Reading the native side showed the problem is entirely Java-side. Every non-consuming JNI entry point already takes a shared reference — &*(handle as *const SessionContext) or &*(handle as *const DataFrame)}.clone() — and DataFusion's SessionContext and DataFrame are both Send + Sync. Exactly four entry points take ownership and free: collectDataFrame, executeStreamDataFrame, closeDataFrame, closeSessionContext. So only the handle's lifetime needed serialising; the operations themselves are already safe to overlap, and no Rust change is required. What changes are included in this PR? A new package-private NativeHandle owns the raw pointer and is the only thing that reads or writes it: acquire() / release() pin the handle for the duration of one native call. claim() / claimQuietly() take exclusive ownership, block until in-flight pins drain, and surrender the pointer for freeing or consumption. Every non-consuming method became acquire() / try / finally release(). DataFrame.collect and executeStream use claim(); both close() methods use claimQuietly(). Two properties drove the design: acquire() never blocks — it pins immediately or throws. That is what lets the eight set operations and join / joinOn pin two DataFrames at once without a lock-ordering hazard. A ReentrantReadWriteLock (suggested on the issue) would not: its readers queue behind a waiting writer, so a.union(b) and b.union(a) on two threads with close()s interleaved could deadlock. claim() is the only blocking operation, and it always makes progress — a thread holding a pin is inside a native call and never claims, so the pins it waits on are guaranteed to be released. The monitor is held only for bookkeeping, never across a JNI call, so independent operations on the same object still run concurrently. The Rust-side Arc refcounting listed as option 2 on the issue is not needed given the above, and would have meant touching every JNI entry point. Argument validation stays in its existing position relative to the closed check within each method, so no currently-observable exception changes. Are these changes tested? Yes, three new suites (18 tests): NativeHandleTest — pure JVM, exercises the lifetime state machine in isolation: pin counting, acquire() after claim(), claim() blocking until a latched pin releases, one winner among racing claimers, and interruption during the drain being absorbed with the flag restored. SessionContextConcurrencyTest — close() waiting on an in-flight call (held open by a TableProvider whose schema() parks on a latch), several threads querying while another closes, and concurrent close() idempotence. DataFrameConcurrencyTest — racing collect() resolving to exactly one winner, close() waiting on an in-flight execution (latched scan), concurrent non-consuming reads all succeeding, and opposing union orders across threads not deadlocking. I verified the tests actually detect the bug by temporarily removing the drain loop from NativeHandle: exactly the four drain-dependent tests fail, including both integration-level close() tests, and pass again once restored. The full suite is green (360 tests), as are spotless:check and cargo fmt. No Rust files are touched. Are there any user-facing changes? No API changes, but the documented contract is stronger, and the Javadoc plus README.md, docs/source/user-guide/quickstart.md and docs/source/user-guide/sessioncontext.md are updated accordingly: Both classes are now safe to share between threads. close() blocks until in-flight calls return, then releases the native object; it is a no-op after the first call, including concurrently. A call that loses the race to a close() throws IllegalStateException instead of producing a use-after-free. The docs are explicit that this covers the handle's lifetime and not the ordering of overlapping operations — registering a table concurrently with a query that reads it still races in the ordinary way.
Open Graph Description: Which issue does this PR close? Closes #40. Rationale for this change SessionContext and DataFrame each held their native pointer in a plain long nativeHandle, and every public method followed th...
X Description: Which issue does this PR close? Closes #40. Rationale for this change SessionContext and DataFrame each held their native pointer in a plain long nativeHandle, and every public method followed th...
Opengraph URL: https://github.com/apache/datafusion-java/pull/115
X: @github
Domain: github.com
IPv4 address: 140.82.112.3
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:f58426d5-621e-27fa-b8ff-c9093e2a290b |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | 9B8A:15EB96:233C10:30DEB6:6B04682C |
| html-safe-nonce | f45328e7f2c9dea9eb18999c84f284d2d679cfead2e8b0db269cfedc05dbe774 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5QjhBOjE1RUI5NjoyMzNDMTA6MzBERUI2OjZCMDQ2ODJDIiwidmlzaXRvcl9pZCI6IjQ4ODc2NDg3MzI4MjY1OTMzMjQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | fcedf8b3a8808653215a63dd500ec5024c8743da68eba76ffd5a11bdd79b399c |
| hovercard-subject-tag | pull_request:4221957347 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/apache/datafusion-java/pull/115/files |
| twitter:image | https://avatars.githubusercontent.com/u/934084?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/934084?s=400&v=4 |
| og:image:alt | Which issue does this PR close? Closes #40. Rationale for this change SessionContext and DataFrame each held their native pointer in a plain long nativeHandle, and every public method followed th... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | 83e4c0e58c5162177f3c161c5fbad38527ae04c11ac14980f9f9d85ae2027b1f |
| turbo-cache-control | no-preview |
| diff-view | unified |
| go-import | github.com/apache/datafusion-java git https://github.com/apache/datafusion-java.git |
| octolytics-dimension-user_id | 47359 |
| octolytics-dimension-user_login | apache |
| octolytics-dimension-repository_id | 1237105117 |
| octolytics-dimension-repository_nwo | apache/datafusion-java |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 1237105117 |
| octolytics-dimension-repository_network_root_nwo | apache/datafusion-java |
| turbo-body-classes | logged-out env-production page-responsive full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | ca4d07a7cef4e4b75f821dc25e7300d80c1450a9 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | no-cache |
Viewport: width=device-width