[Bug] JNI scanner leaks off-heap memory and fails queries when getNext throws an unchecked exception
Search before asking
- [x] I had searched in the issues and found no similar issues.
Version
master / 4.0
What's Wrong?
JNI scan threads are pooled and reused across queries, and a JNI exception is sticky per-thread: it stays pending until explicitly cleared. Two related problems arise:
-
FE
JniScanner.getNextBatchMeta()only catchesIOExceptionfromgetNext(). Scanner subclasses (and the libraries they call) routinely surface failures as uncheckedRuntimeException/NullPointerException. When such an exception escapes:releaseTable()is skipped, leaking the off-heapVectorTable;- a bare pending JNI exception is left on the pooled scan thread, later misattributed to an unrelated JNI call (e.g.
getStatistics) and able to fail an otherwise healthy query.
-
BE
JniReader::_get_statistics/JniReader::closeandJniTableReader::_get_statisticsrun JNI calls while a stale pending exception (left by an earlier call on the same pooled thread) may still be present — undefined behavior per the JNI spec. Inclose()the earlyRETURN_ERROR_IF_EXCaborts before the resource-release/close calls, leaking the Java scanner and the off-heap table.
What You Expected?
An unchecked exception from getNext() should always release the scanner table and be normalized to a checked exception, and BE best-effort statistics/close paths should not run under a stale pending exception or leak resources.
How to Reproduce?
Run a JNI-based scan (e.g. an external table via a JNI scanner) where getNext() throws an unchecked exception (a malformed record or a connector-library RuntimeException/NPE). The off-heap table is leaked and a subsequent unrelated JNI call on the reused scan thread can fail the query.
Anything Else?
Fix: FE catches Throwable, always calls releaseTable(), and normalizes non-IOException throwables to IOException; BE discards any residual pending exception up front (logging it) before touching the JVM again.
Are you willing to submit PR?
- [x] Yes I am willing to submit a PR!
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
Breakwater-GitHub-Analysis-Slot: slot_fc1d2497e5a7 This content is generated by AI for reference only.
Initial assessment: partially valid. The Java-side cleanup gap is real, but the reported “sticky JNI exception survives into a later pooled-thread call” mechanism is contradicted by the current native exception wrapper.
I checked the live issue metadata and the relevant code on current master (27cb451229c7a42dd089c5248847828eb0536d02) and upstream/branch-4.0 (823b3fa039c921047aaccd8cb097d5c3a205a918). At triage time the issue is open with no labels, assignee, milestone, or linked PR.
Confirmed Java-side issue:
fe/be-java-extensions/java-common/.../JniScanner.java:getNextBatchMeta()allocates and retainsvectorTable, but its catch block covers onlyIOException.- A
RuntimeExceptionorNullPointerExceptionfromgetNext()therefore bypasses the immediatereleaseTable()call. TheVectorTableremains referenced, including its native allocations, until a later scanner cleanup succeeds. - This is a valid deterministic resource-lifetime bug and should be fixed in the Java wrapper so cleanup does not depend on a later BE close path. However, the current evidence proves retention until close, not yet a permanent process-lifetime leak: both legacy and v2 BE close paths normally attempt
releaseTable().
The cross-query pending-exception claim is not reproduced by the current code:
- On
master,Jni::FunctionCall::call()invokesRETURN_ERROR_IF_EXCimmediately after every wrapped Java method call (be/src/util/jni-util.h).Jni::Env::GetJniExceptionMsg()obtains the throwable and callsExceptionClear()before returning the errorStatus(be/src/util/jni-util.cpp). - Both
JniReader::_do_get_next_block()andJniTableReader::_get_next_jni_block()use that wrapper forgetNextBatchMeta(). Thus an unchecked Java exception is converted to an error and cleared on the same JNI call; it is not left pending for a latergetStatistics()or another query. upstream/branch-4.0has the same effective behavior in the older path:JniConnector::get_next_block()callsRETURN_ERROR_IF_EXCimmediately afterCallLongMethod, andJniUtil::GetJniExceptionMsg()clears the exception.- The v2 close path is already best-effort and retryable after #65503:
_close_jni_scanner()attempts bothreleaseTable()and Javaclose()even if the first fails, and it retains state when cleanup fails. Its metric calls also use wrappers that consume/clear Java exceptions.
There is a separate legacy cleanup weakness worth fixing: JniReader::close() marks _closed before cleanup and uses early-return error handling for the metric getters, releaseTable(), and Java close(). An independent close-time JNI failure can therefore skip later cleanup and prevent retry. That is a real leak risk, but it is not caused by a pending exception left by getNextBatchMeta() under the current wrapper.
Recommended fix/review direction:
- Accept a Java-side change that releases the table for unchecked failures from
getNext(), preserves the original exception as the cause, and handles cleanup failures without silently replacing the primary failure. - Be careful with
catch (Throwable)plus unconditional normalization:Throwableincludes JVMErrors such asOutOfMemoryError. Cleanup should still be attempted, but fatalErrorsemantics should normally be preserved rather than downgraded toIOException; normalization is appropriate forRuntimeException/NPE. - Do not add blind BE “discard any residual exception” logic as the root-cause fix without identifying an actual unwrapped JNI call that can leave the exception pending. Clearing an unexplained exception at a later entry point can hide the real violating call. The current
getNextBatchMeta()path already clears it. - Independently harden legacy
JniReader::close()along the v2 lifecycle pattern: make profile collection best-effort, always attempt both table release and scanner close, and only commit the closed state after cleanup has completed or preserve retryable state.
Required tests:
- A Java unit test with a synthetic
JniScannerwhosegetNext()throwsRuntimeExceptionafter the table has been created; assert thatgetTable()is null afterward and that the reportedIOExceptionretains the original cause. - Equivalent coverage for an existing connector-style NPE/unchecked failure and idempotent cleanup.
- A JNI integration test showing that after the failed
getNextBatchMeta()call,env->ExceptionCheck()is false and a benign Java call on the same native thread succeeds. This directly validates or disproves the issue’s pooled-thread claim. - Legacy close-path tests where metric collection and resource release fail independently, verifying that Java
close()is still attempted and cleanup can be retried.
Missing evidence needed to establish the broader production failure described in the issue:
- The exact Doris build SHA and concrete connector/scanner used; “master / 4.0” is not enough for backport scope.
- A complete first-failure Java stack trace plus the allegedly misattributed later JNI error, including query IDs and BE thread IDs.
- A minimal deterministic reproducer that runs the failure and the later healthy call on the same scan thread.
- A BE memory-tracker snapshot/delta after scanner close, demonstrating that the native allocation remains outstanding after cleanup rather than only between
getNext()failure and close.
No Doris Profile is required to validate the Java exception-cleanup gap itself.