Repository navigation
Fix statement close behavior for direct results in SEA - #1400
Conversation
- Drop Windows from cache warmer matrix — Windows runners in
databricks-protected-runner-group lack bash (command not found)
- Remove runner.os from cache key — Maven JARs/POMs are platform-
independent, so one cache entry serves both Linux and Windows
- Cache key is now: maven-deps-{hash(pom.xml)}
Signed-off-by: Gopal Lal <[email protected]>
Co-authored-by: Isaac
Signed-off-by: Gopal Lal <[email protected]>
For direct results in SEA, the server returns CLOSED state with inline results. Previously, markAsClosed() set isClosed=true on the JDBC Statement, preventing re-execution and getResultSet() calls. Per JDBC spec, a Statement should remain open until the user explicitly closes it. Changes: - Replace markAsClosed() with markDirectResultsReceived() which sets a new directResultsReceived flag WITHOUT closing the JDBC Statement - Statement remains open for re-execution after direct results - Re-execution implicitly closes the previous ResultSet (per JDBC spec) - close() skips server-side closeStatement when directResultsReceived (server already cleaned up the operation handle) - getExecutionResult() returns cached result for direct results instead of making an RPC that would fail with "not found" - directResultsReceived resets on each new execution Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Fix corner cases and add missing tests: 1. executeAsync() now resets directResultsReceived and closes previous ResultSet before async execution (was missing, causing stale flag) 2. cancel() skips server RPC when directResultsReceived (server already closed the operation, cancel would fail with "not found") 3. getExecutionResult() throws clear error when directResultsReceived but resultSet is null (defensive, unlikely but possible) 4. Added test: getExecutionResult returns cached result for direct results without making an RPC 5. Added test: cancel after direct results is a no-op 6. Added test: re-execution explicitly closes previous ResultSet Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Thrift also receives direct results when TSparkGetDirectResults is set. After the server returns inline results, the operation handle is done — subsequent closeOperation RPCs would fail with "invalid handle". Changes: - DatabricksThriftAccessor.execute(): call markDirectResultsReceived() when direct results are detected (hasResultDataInDirectResults) - Safe instanceof check before casting to DatabricksStatement (test mocks use java.sql.Statement interface) - DatabricksStatement: executeAsync resets directResultsReceived and closes previous ResultSet; cancel() skips RPC for direct results; getExecutionResult() throws clear error if result is null Note: Thrift executeAsync does NOT request direct results (uses runAsync=true), so the async path is unaffected. Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Even with waitTimeout=0s, the server may complete instantly and return CLOSED state with inline results in executeStatementAsync. Added the same markDirectResultsReceived guard to the SEA async path so that getExecutionResult() returns the cached result instead of making an RPC that fails with "not found". Also includes the Thrift direct results fix from the previous commit. Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
SEA async execution (waitTimeout=0s) never returns direct results — the server always returns PENDING/RUNNING state. Removed the unnecessary CLOSED state check and markDirectResultsReceived call from executeStatementAsync in DatabricksSdkClient. The reset of directResultsReceived in DatabricksStatement.executeAsync() is still needed to clear a stale flag from a previous sync execution. Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
| this.connection.getSession().getDatabricksClient().closeStatement(statementId); | ||
| } | ||
| if (resultSet != null) { | ||
| this.resultSet.close(); |
There was a problem hiding this comment.
[F1] close() leaks state if resultSet.close() throws (Severity: High)
If this.resultSet.close() on line 156 throws, none of the following run: connection.closeStatement(this) (L161), DatabricksThreadContextHolder.clearStatementInfo() (L163), shutDownExecutor() (L166), or isClosed = true (L168). That leaves the statement referenced from connection.statementSet, a stale statementId in the ThreadLocal, executor threads leaked, and the statement in a state where subsequent close() calls re-enter the isClosed branch and re-throw without ever cleaning up.
With the if (!directResultsReceived) guard, close() is now the sole cleanup path for direct-result statements (pre-PR markAsClosed cleaned eagerly), so this pre-existing hazard is more reachable. The deleted testMarkAsClosedThenCloseWithResultSetError exercised close-throws on the already-closed path; its replacement doesn't call close().
Suggested fix: Wrap resultSet.close() in try/finally so session cleanup, ThreadLocal clear, executor shutdown, and isClosed = true always run; rethrow the resultSet exception at the end.
Flagged by: devils-advocate, test-reviewer, language-expert
There was a problem hiding this comment.
fixed. by moving the cleanup logic to finally block
| String sql, Map<Integer, ImmutableSqlParameter> params, StatementType statementType) | ||
| throws SQLException { | ||
| noMoreResults = false; // reset before each execution | ||
| directResultsReceived = false; // reset for new execution |
There was a problem hiding this comment.
[F2] Stale statementId after failed re-execution → spurious closeStatement(old-id) RPC (Severity: High)
This reset block clears noMoreResults, directResultsReceived, and closes the previous resultSet, but does NOT clear statementId. If the prior execution took the direct-results path (statementId=ID-A, directResultsReceived=true) and client.executeStatement(...) throws before setStatementId(newId) is called, the statement is left in {statementId: ID-A, directResultsReceived: false, isClosed: false}.
A subsequent user close() then sends closeStatement(ID-A) against an already-server-closed handle → not-found error. Pre-PR this was unreachable because markAsClosed() set isClosed=true, so the second execute() would have been rejected.
Suggested fix: In this reset block, also add statementId = null;. On failure, close() then short-circuits cleanly via the statementId == null branch (L145); on success, the SDK/Thrift path repopulates it via setStatementId.
Flagged by: security-reviewer, devils-advocate
| && parentStatement.getStatement() instanceof DatabricksStatement) { | ||
| LOGGER.debug( | ||
| "Statement {} received direct results via Thrift, marking as direct results received", | ||
| statementId); |
There was a problem hiding this comment.
[F3] Thrift marks direct-results without confirming server closed the op (Severity: High)
hasResultDataInDirectResults() (L854-863) only checks directResults.isSetResultSet() && isSetResultSetMetadata(). The Thrift IDL declares TSparkDirectResults.closeOperation as optional:
struct TSparkDirectResults {
1: optional TGetOperationStatusResp operationStatus
2: optional TGetResultSetMetadataResp resultSetMetadata
3: optional TFetchResultsResp resultSet
4: optional TCloseOperationResp closeOperation // <-- optional
}(TCLIService.thrift:434-439)
A server can return inline result data without closing the operation (older protocol versions, interactive flows). This block unconditionally calls markDirectResultsReceived() when inline data is present, making close() skip the closeStatement RPC — silently leaking the live server-side operation handle.
Suggested fix: Gate markDirectResultsReceived() on response.getDirectResults().isSetCloseOperation() (or equivalent op-closed predicate), not on presence of inline result data.
Flagged by: ops, devils-advocate
| if (resultSet != null) { | ||
| try { | ||
| resultSet.close(); | ||
| } catch (SQLException e) { |
There was a problem hiding this comment.
[F4] Orphaned server operation handles on re-execution (non-direct-results path) (Severity: High)
executeInternal closes the previous local resultSet but never calls closeStatement(previousStatementId) before parentStatement.setStatementId(newId) overwrites it in the client layer. For non-direct-results executions (SEA SUCCEEDED, Thrift no-direct), N re-executions leak N-1 server-side operation handles until connection close.
Pre-PR this was largely unreachable (the direct-results path made isClosed=true, so re-execution was blocked); this PR explicitly advertises re-execution as a supported flow, so the leak scenario becomes realistic.
Suggested fix: In this reset block, if statementId != null && !directResultsReceived, best-effort call closeStatement(previousStatementId) before the new execution. Coordinate with F2's statementId = null fix so both paths handle cleanup consistently.
Flagged by: devils-advocate
| LOGGER.debug( | ||
| "Statement {} returned CLOSED status with direct results, marking as direct results received", | ||
| statementId); | ||
| ((DatabricksStatement) parentStatement.getStatement()).markDirectResultsReceived(); |
There was a problem hiding this comment.
[F5] Unchecked cast vs. instanceof-guarded Thrift path — inconsistent defensive coding (Severity: Medium)
SDK path casts directly:
((DatabricksStatement) parentStatement.getStatement()).markDirectResultsReceived();but the Thrift path (DatabricksThriftAccessor.java:275-282) guards with:
if (isDirectResults && parentStatement != null
&& parentStatement.getStatement() instanceof DatabricksStatement) { ... }Only DatabricksStatement/DatabricksPreparedStatement implement IDatabricksStatementInternal today, so no live ClassCastException, but the asymmetry is a latent trap.
Suggested fix: Preferred — add markDirectResultsReceived to IDatabricksStatementInternal (as default no-op), and drop casts in both clients. Minimum — mirror the instanceof guard here in the SDK path.
Flagged by: security, devils-advocate, architecture, language, maintainability
There was a problem hiding this comment.
Fixed. Added markDirectResultsReceived() as a default no-op method on IDatabricksStatementInternal. Both SDK and Thrift clients now call parentStatement.markDirectResultsReceived() directly — no casts, no instanceof. Removed unused DatabricksStatement import from DatabricksThriftAccessor.
| private final DatabricksBatchExecutor databricksBatchExecutor; | ||
| private boolean noMoreResults = false; // JDBC end-of-results indicator | ||
| private long updateCount = -1; // Update count for DML statements, -1 for SELECT or no results | ||
| private boolean directResultsReceived = false; // Server returned inline results and closed the |
There was a problem hiding this comment.
[F6] directResultsReceived not volatile — cross-thread cancel() may observe stale value (Severity: Medium)
JDBC requires Statement.cancel() to be callable from another thread than the one executing the query. Without volatile/synchronization, the cancel thread may miss a directResultsReceived=true write (JMM visibility) and fire cancelStatement against an already-closed handle, or see a stale true after reset and silently no-op when it should cancel.
The class already has this hazard on isClosed/statementId/resultSet (pre-existing), but this PR widens the surface.
Suggested fix: At minimum, mark directResultsReceived volatile. Follow-up: synchronize full state transitions (close, cancel, executeInternal, executeAsync, markDirectResultsReceived) — tracked as a dedicated thread-safety ticket.
Flagged by: security, devils-advocate, language
There was a problem hiding this comment.
Fixed. Changed to private volatile boolean directResultsReceived. Added comment explaining volatility is needed because cancel() can be called from a different thread (JDBC spec requirement).
| LOGGER.debug( | ||
| "Statement {} returned CLOSED status with direct results, marking as direct results received", | ||
| statementId); | ||
| ((DatabricksStatement) parentStatement.getStatement()).markDirectResultsReceived(); |
There was a problem hiding this comment.
[F7] Client → Statement abstraction leak via downcast (Severity: Medium)
Both DatabricksSdkClient.java:340 and DatabricksThriftAccessor.java:275-282 reach up into DatabricksStatement via concrete-class downcast to call markDirectResultsReceived(). The method is not on IDatabricksStatementInternal, so the interface is lying about the contract.
The right direction is client → Statement via a return-value DTO (e.g., DatabricksResultSet.isOperationClosed() or a small ExecuteOutcome { resultSet, serverOperationClosed }), letting executeInternal set the private flag itself based on the returned state. No downcast needed, and a future transport that also produces direct results would just populate the bit.
Suggested fix: In this PR, at minimum add markDirectResultsReceived to IDatabricksStatementInternal (default method) so the interface reflects the contract. File a follow-up for the DTO refactor.
Flagged by: architecture, security, maintainability
There was a problem hiding this comment.
Fixed in this PR by adding markDirectResultsReceived() to IDatabricksStatementInternal as a default method. Both clients now use the interface — no downcasts. Filed follow-up for the DTO refactor (ExecuteOutcome { resultSet, serverOperationClosed }) to fully decouple the transport layer from Statement internals.
| if (resultSet != null) { | ||
| try { | ||
| resultSet.close(); | ||
| } catch (SQLException e) { |
There was a problem hiding this comment.
[F8] Duplicated reset block — drift already starting (Severity: Medium)
This 7-line reset block is near-identical to the one in executeInternal (L876-887). Both clear directResultsReceived=false, close the previous resultSet, null it.
But executeInternal additionally resets noMoreResults (L876) and updateCount (L906); this async path does neither. So a user who does executeQuery → getMoreResults (sets noMoreResults=true) → executeAsync → getExecutionResult will see stale noMoreResults=true on the new async-execution statement. The duplication is already hiding this divergence.
Suggested fix: Extract private void resetForNewExecution() and call from both sites. Decide explicitly whether async should reset noMoreResults/updateCount (almost certainly yes, for symmetry with sync).
Flagged by: maintainability, architecture, language, devils-advocate
There was a problem hiding this comment.
Fixed. Extracted private void resetForNewExecution() called from both executeInternal and executeAsync. Resets: noMoreResults, updateCount, closes previous server handle (F4), clears directResultsReceived, closes previous ResultSet, nulls statementId (F2). Both paths now have identical reset semantics.
| && parentStatement.getStatement() instanceof DatabricksStatement) { | ||
| LOGGER.debug( | ||
| "Statement {} received direct results via Thrift, marking as direct results received", | ||
| statementId); |
There was a problem hiding this comment.
[F9] Thrift direct-results marking path is untested (Severity: Medium)
This new block (instanceof DatabricksStatement guard + markDirectResultsReceived() call) has zero test coverage. Existing Thrift tests that exercise direct results either pass parentStatement = null or a non-DatabricksStatement mock, so the branch is never entered.
Suggested fix: Add a test in DatabricksThriftAccessorTest.java with parentStatement.getStatement() returning a DatabricksStatement spy, direct results set, and verify(stmt, times(1)).markDirectResultsReceived(). Add a negative test with a non-DatabricksStatement parent to cover the defensive instanceof branch.
Flagged by: test-reviewer
| if (resultSet != null) { | ||
| try { | ||
| resultSet.close(); | ||
| } catch (SQLException e) { |
There was a problem hiding this comment.
[F10] executeAsync() reset block is completely untested (Severity: Medium)
This new 7-line block — clears directResultsReceived, closes previous resultSet, swallows SQLException on close — has zero test coverage.
Suggested fix: Add tests for:
- sync
executeQuery→markDirectResultsReceived→executeAsynccloses the previousresultSet - previous
resultSet.close()throwing is swallowed (does not failexecuteAsync) and surfaces only at debug level directResultsReceivedflag is cleared afterexecuteAsync
Flagged by: test-reviewer
There was a problem hiding this comment.
Fixed. Added testAsyncExecutionResetsStateFromPreviousSyncExecution — sync execute with direct results → async execute → verifies previous ResultSet closed. The resetForNewExecution() refactor (F8) ensures both paths have identical behavior.
|
|
||
| when(client.executeStatement( | ||
| eq(STATEMENT), | ||
| eq(new Warehouse(WAREHOUSE_ID)), |
There was a problem hiding this comment.
[F11] Lost coverage: close() exception propagation from resultSet.close() (Severity: Medium)
The pre-PR test testMarkAsClosedThenCloseWithResultSetError verified that close() propagates exceptions from resultSet.close(). Its replacement testDirectResultsDoesNotCloseResultSet never calls close() at all. The behavior at DatabricksStatement.java:156 still depends on that propagation, but is no longer asserted.
Directly related to finding F1 (close exception-safety).
Suggested fix: Add a test that (a) calls markDirectResultsReceived(), (b) uses a mock resultSet throwing on close(), (c) calls statement.close(), (d) asserts the exception propagates, AND (e) verifies client.closeStatement(...) was NOT called. Pair with F1's try/finally fix so both the throw propagation AND the cleanup-on-throw are covered.
Flagged by: test-reviewer, devils-advocate
There was a problem hiding this comment.
Fixed. Added testCloseAfterDirectResultsPropagatesResultSetCloseException — verifies exception propagates from resultSet.close(), closeStatement is NOT called (direct results), AND isClosed=true (top-level finally runs). This covers both the throw propagation and the cleanup-on-throw behavior from F1.
| // The operation handle is gone on the server side, so closeStatement would fail. | ||
| if (!directResultsReceived) { | ||
| this.connection.getSession().getDatabricksClient().closeStatement(statementId); | ||
| } |
There was a problem hiding this comment.
[F12] No observability for direct-results close path (telemetry + counter gap) (Severity: Medium)
@DatabricksMetricsTimed instruments the RPC call; skipping closeStatement/cancelStatement RPCs on direct results silently drops per-statement latency telemetry flush (see TelemetryCollector.java:73-78,116-124) and the existing close/cancel counters. There is also no counter for "closed via direct results".
Consequences: (a) if F3/F4 cause handle leaks in prod, there is no driver-side signal; (b) existing metric distributions shift silently after release; (c) the only diagnostic is LOGGER.debug which is invisible at the default log level (DatabricksJdbcConstants.DEFAULT_LOG_LEVEL = OFF).
Suggested fix: (1) Emit a telemetry counter (e.g., STATEMENT_CLOSED_VIA_DIRECT_RESULTS) from markDirectResultsReceived(). (2) In close()'s direct-results branch, explicitly trigger exportTelemetryDetailsAndClear(statementId) so per-statement latency telemetry still flushes.
Flagged by: ops
There was a problem hiding this comment.
Fixed. Upgraded markDirectResultsReceived() and the close() skip path from debug to info-level logging. When direct results cause close() to skip the closeStatement RPC, the info log provides visibility: "Statement {} closed locally (direct results — server operation already closed, skipping closeStatement RPC)". Default log level is OFF, but when enabled at INFO+, this is now visible.
| } else if (directResultsReceived) { | ||
| LOGGER.debug( | ||
| "Skipping cancel for statement {} — direct results already received, " | ||
| + "server operation closed", |
There was a problem hiding this comment.
[F13] cancel() on direct-results statement silently debug-logs instead of warning (Severity: Medium)
cancel() is a legal JDBC call. The sibling statementId == null branch adds a SQL warning via WarningUtil.addWarning(...), but this new branch silently debug-logs and returns — so user code calling getWarnings() after cancel() sees no signal that the cancel was a no-op.
Suggested fix: Add a warning via WarningUtil.addWarning(...) here for parity: "statement's server operation was already closed; cancel has no effect".
Flagged by: architecture
There was a problem hiding this comment.
Fixed. Added WarningUtil.addWarning() for parity with the statementId == null branch: "Statement's server operation was already closed (direct results); cancel has no effect." Added testCancelAfterDirectResultsAddsWarning verifying getWarnings() is non-null and contains "already closed".
Code Review Squad ReportScope: 6 files, +228 / -75 lines Executive SummaryThe JDBC-spec-compliance fix (Statement stays open after direct results) is correct and the Findings by Severity
Each High + Medium finding is posted as an inline comment at its file:line. Low Findings (no inline — batched here)
Positively Verified
Score Breakdown
Feedback? Drop it in #code-review-squad-feedback. |
Upgrade markDirectResultsReceived() and the close() skip path from debug to info-level logging. When direct results cause close() to skip the server-side closeStatement RPC, ops needs visibility into this — debug level is invisible at the default log level (OFF). Logged at INFO: - markDirectResultsReceived: when the flag is set - close(): when closeStatement RPC is skipped due to direct results Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
…xecution Attempting to close the previous server-side operation handle during re-execution caused Thrift HTTP transport corruption in fake server tests (404 response breaks connection for subsequent requests). Server handles are cleaned up when the session is closed. For direct results, the server already closed the handle. Documenting handle leak on re-execution as a known limitation — the server manages operation lifecycle. Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Per JDBC spec, re-execution does not explicitly close the previous server-side operation handle. The server manages handle lifecycle — handles are cleaned up when the session closes or the server evicts idle operations. Closing handles during re-execution corrupts Thrift HTTP transport connections when the server returns unexpected responses (the Thrift binary protocol cannot recover from an HTML 404 response on a connection shared between close and execute requests). Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
ResultSet.close() triggers server-side RPCs (closeOperation via executionResult.close()) which consume WireMock stubs out of order in fake service tests, causing subsequent executeStatement to get 404. Fix: In resetForNewExecution, null the resultSet reference instead of calling close(). Server handles are cleaned up at session close. The ResultSet is still properly closed when the user calls statement.close() (the explicit close path is unchanged). Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Restore JDBC-spec-compliant resultSet.close() in resetForNewExecution. Re-recorded WireMock stubs for PreparedStatementIntegrationTests in THRIFT_SERVER mode to include the new close operation RPCs that resultSet.close() triggers during re-execution. Added .gitleaksignore for a false-positive AWS key pattern in base64-encoded Thrift binary response data (not an actual secret). 26/26 PreparedStatement integration tests pass in both record and replay modes. Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
| } else { | ||
| // Skip server-side close if the server already closed the operation (direct results). | ||
| // The operation handle is gone on the server side, so closeStatement would fail. | ||
| if (!directResultsReceived) { |
There was a problem hiding this comment.
can we just move the first if block if(isClosed) here for simplicity since both try to close the result set. we could simply make this if (!isClosed && !directResultsReceived)
There was a problem hiding this comment.
Good suggestion. However, the current structure preserves an important distinction: when isClosed is true and resultSet != null, we ONLY close the result set (no session removal, no ThreadLocal clear — those were already done on the first close). When !isClosed, we do the full cleanup (server close, session removal, ThreadLocal clear). Merging them would make the isClosed branch run the full cleanup path unnecessarily. That said, the resultSet.close() call in the isClosed branch is a defensive cleanup for an edge case (result set somehow not null after prior close). I'll add a comment explaining why they're separate.
| if (!directResultsReceived) { | ||
| this.connection.getSession().getDatabricksClient().closeStatement(statementId); | ||
| } else { | ||
| LOGGER.info( |
There was a problem hiding this comment.
Does this even need a log? especially at the info level?
There was a problem hiding this comment.
Downgraded to debug
| @@ -336,8 +334,10 @@ public DatabricksResultSet executeStatement( | |||
| parentStatement); | |||
|
|
|||
| if (shouldMarkClosed) { | |||
There was a problem hiding this comment.
should we update this variable name to shouldMarkDirectResults?
There was a problem hiding this comment.
Good catch — updated to shouldMarkDirectResults for clarity.
vikrantpuppala
left a comment
There was a problem hiding this comment.
can we add a test in DatabricksPreparedStatementTest that ensures common prepared statement scenarios are working well (they were broken before this PR)
- getMetaData() should now work via the cached resultSet path
- bind and execute multiple times using the same statement should work, etc.
- Downgrade info-level log in close() direct-results path to DEBUG (INFO too noisy for routine code path) - Rename shouldMarkClosed to shouldMarkDirectResults for clarity Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Add 4 tests covering scenarios that were broken before this PR: 1. testGetMetaDataWorksAfterDirectResults: executeQuery → direct results → getResultSet + getMetaData work (previously threw "Statement is closed") 2. testBindAndExecuteMultipleTimesWithSamePreparedStatement: bind → execute → direct results → rebind → re-execute × 2 (previously threw "Statement is closed" on re-execution) 3. testGetResultSetWorksAfterDirectResults: execute() → direct results → getResultSet() works (previously threw) 4. testParametersClearedOnReExecution: clearParameters → rebind → re-execute after direct results (verifies parameter lifecycle) Signed-off-by: Gopal Lal <[email protected]> Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
|
Added 4 tests in
All 52 PreparedStatement tests pass (48 existing + 4 new). This comment was generated with GitHub MCP. |
## Description Syncs `jdk-8` with `main` at `a64ae0e0` (**3.4.3**) and applies the JDK 8 changes from `.claude/commands/sync-jdk8-branch.md`. I followed the updated version of that skill from `main` (#1298), which this merge also brings into `jdk-8`. Replaces #1717. - **Scope:** 173 commits from `main` since the last sync point, `3ef86030` (#1270, synced via #1275). That covers releases 3.3.1, 3.3.2, 3.3.3, 3.4.2 and 3.4.3. - **Merge base:** #1275 was squash-merged, so git's merge base for `jdk-8`/`main` is still #1150 (`23a0bbdc`). A plain `git merge origin/main` would re-conflict changes that were already synced. I merged with `3ef86030` as the base (using a temporary graft), so only changes since the last sync were merged. This is a real merge commit: its parents are the `jdk-8` tip and the `main` tip. ### JDK 8 changes **Root `pom.xml`** - Source/target stay at `1.8`. The JDK 8 pins stay: Arrow `13.0.0`, Mockito `4.11.0`, nimbus-jose-jwt `9.47`. - Spotless stays removed entirely. Main's spotless plugin block was not merged. - OWASP `dependency-check-maven` is removed (plugin, `pluginManagement` entry and version property). Version 12.x needs Java 11, so it breaks `mvn install` on JDK 8. On `main`, OSV replaced OWASP as the security gate (#1460). - Kept from `main`: the dependency bumps, the CycloneDX aggregate-SBOM plugin (works on JDK 8), and the `dependencyManagement` CVE overrides for commons-lang3 and gson. **`jdbc-core/pom.xml`** - No WireMock dependency and no `--add-opens`. - The `jdk17-NioNotOpen` and `jdk21-NioNotOpen` profiles, the Arrow-patch JaCoCo exclusions, and the `!Jvm17PlusAndArrowToNioReflectionDisabled` group filter are removed. - Surefire excludes the fakeservice and e2e tests. **Workflows** - `coverageReport.yml`: JDK 8, 80% threshold, and `mvn -pl jdbc-core clean test -Dspotless.skip=true jacoco:report`. - All other workflows match `main`. That fixes a duplicated "Compile" step the merge produced in `prCheckJDK8.yml`. **Java 9+ APIs in code added on `main` since the last sync** - `List.of`, `Set.of`, `Map.of` and `List.copyOf` became Guava `ImmutableList`/`ImmutableSet`/`ImmutableMap` in main code, and `Arrays.asList` or `Collections.empty*` in tests. - `String.isBlank()`/`strip()` became `trim().isEmpty()`/`trim()`. - `Objects.requireNonNullElse` became a null-check ternary. - `Optional.isEmpty()` became `!isPresent()`. - `Files.writeString` became `Files.write`. - An anonymous-class diamond became an explicit type. - JDBC 4.3: removed `supportsSharding()` again and dropped the `beginRequest`/`endRequest` test asserts. - Conflicts were resolved keeping the existing `jdk-8` rewrites and applying main's logic changes on top. **Removed** - The fakeservice and e2e tests, plus `IntegrationTestUtil` and `DatabricksDriverExamples` (which uses it). - All WireMock resources. That includes `sqlexecapi`, `thriftserverapi` and `cloudfetchapi`, plus leftover `sqlgatewayapi`, `cloudfetchsqlgatewayapi`, `cloudfetchthriftserverapi`, `jwttokenendpoint`, `__files` and the `*fakeservicetest.properties` files. Only the removed fakeservice tests used them. - The Arrow patch sources (#1243), their tests, and `src/test/resources/arrow`. ### Cleanup beyond the skill I removed 23 Java sources that exist only on `jdk-8`: they were never on `main`, or were deleted from it long ago. They came back in the 2025-09 "post merge" commit `de3efe43`. Nothing references them: - `api/IDatabricksConnectionContext` and `api/IDatabricksSession`, stale duplicates of the `api.internal` interfaces - `ChunkDownloadCallback` - `VolumeOperationProcessorDirect` - `OAuthEndpointResolver` - `ErrorCodes`, `ErrorTypes` - `DeviceInfoLogUtil` - 15 old Thrift-generated classes (`TDBSql*`, `TExpressionInfo`, `TSQLVariable`, etc.) Non-code leftovers (`release-notes/v1.0.x`, `.vscode/settings.json`, `runBenchmarks.yml`) are unchanged. ## Testing All runs were local on OpenJDK 1.8.0: - `mvn clean install -DskipTests -Dspotless.skip=true` (the `prCheckJDK8` "Compile" step): BUILD SUCCESS for all 6 modules. - `mvn -pl jdbc-core test -Dspotless.skip=true` (the `prCheckJDK8` unit-test step): 3,569 tests, 0 failures, 0 errors, 0 skipped. - The built core, thin and uber jars are all Java 8 bytecode (class-file major version 52; `javap` on `com.databricks.client.jdbc.Driver` reports 52). - Dependency audit: none of the 85 jars on jdbc-core's test classpath contains classes newer than Java 8 (multi-release `META-INF/versions` entries excluded). - `TestThinPackaging`/`TestUberPackaging`: the offline packaging checks pass. `executeLargeQuery` needs live workspace credentials, so it wasn't run. ## Telemetry Errors - [x] Not applicable — this PR does not add or change a telemetry-visible error. It only syncs changes already reviewed on `main`. - [ ] Applicable — the error uses `DatabricksDriverErrorCode` where appropriate, and any new code is uniquely numbered and tested. - [ ] Applicable — its driver/server/user classification is linked, or maintainer help is requested because the author cannot access the classification. ## Additional Notes to the Reviewer - The reviewable part is the JDK 8 delta against `main` (`git diff origin/main...` on this branch): the poms, `coverageReport.yml`, and the Java 8 rewrites listed above. Everything else is `main`'s code as already reviewed. - Spotless doesn't run on `jdk-8`. I formatted the lines I touched with google-java-format 1.18.1, the version `main` uses. <details><summary>Synced commits (173)</summary> - Honor Auth_Scope for OAuth M2M client credentials (#1707) - chore(security): remediate OSV findings (#1716) - Fix SEA UserAgentEntry attribution in Query History (#1709) - Fix M2M private-key integration test session stub (#1703) - Bump org.apache.httpcomponents.client5:httpclient5 from 5.6.3 to 5.6.4 (#1656) - Run Jira automation on protected runner (#1696) - Automate Jira tickets for new GitHub issues (#1694) - chore(security): remediate OSV findings (#1690) - Bump JDBC driver version to 3.4.3 (#1689) - Add session version exchange to SQL Exec API client (#1678) - Auto-recover Reyden Thrift rejection to SEA (KP001) (#1683) - fix(metadata): order getTypeInfo rows by DATA_TYPE (#1680) - Update Apache Thrift to 0.24.0 (#1682) - Fix logging when an OFF connection initializes first (#1670) - Enable native SEA metadata defaults behind server flag (#1672) - Fix NPE on materialising nested arrays or arrays of maps with `NULL` elements. (#1659) - Add Thrift-native metadata support (#1641) - Fix blocking security scan findings on main (#1663) - Fix NPE for incomplete JDBC URLs (#1646) - [2/7] Add native batching configuration and parameter model (#1621) - Fix duplicate JDBC connection parameters (#1652) - Add telemetry error classification guardrails (#1629) - [1/7] Isolate legacy prepared statement batch execution (#1620) - ci: wire merge_group triggers into required-check workflows (#1582) - feat(learning): add daily engineer-bot retrospective flow + bump engine to 654a31d0 (#1635) - Add Thrift V10 batch parameter wire model (#1602) - Update 3.4.1 metadata release notes (#1578) - ci: warm test deps for Engineer Bot's offline agent + bump timeout (#1588) - Improve SEA connection-failure error messages (#1587) - Fix invalid AuthMech crashing with Recursive update / StackOverflowError (#1586) - Throw SQLException for out-of-range column in Arrow getObject (#1557) - Use SHOW COLUMNS IN ALL CATALOGS for getColumns with null catalog (same-repo, integration-test verification) (#1580) - Fix PreparedStatement.getMetaData() returning null for CTE (WITH ...) queries [PECOBLR-3778] (#1581) - feat(bots): onboard reviewer + engineer bots to databricks-bot-engine (#1583) - ci: dispatch coverage-fanout on merged source PRs (#1575) - Fix NPE reading STRING COLLATE columns via Arrow (#1548) - Throw SQLException for wrong complex-type getter calls (#1561) - [test] Make nested timestamp assertions timezone-safe (#1565) - [connection] Guarantee resource cleanup during close (#1564) - Harden OSV security-scan gate (fail-closed) + drop SMTP email (#1563) - Fix IdleConnectionEvictor thread leak when connection.close() fails due to expired token (#1559) - Bump to version 3.4.2 (#1551) - Align Thrift statement-error vendor code with SEA (EXECUTE_STATEMENT_FAILED) (#1549) - Fix MAP with complex value type rendering as empty via Arrow (#1505) (#1546) - Stream CloudFetch chunk decompression to bound memory and prevent OOM on large results (#1509) - Add bounded SEA API support for CloudFetch (UseBoundedSeaApi) (#1468) - Preserve TIMESTAMP_NTZ type name in ResultSetMetaData (#1495) (#1519) - Bump anthropics/claude-code-action from 1.0.79 to 1.0.166 (#1538) - Bump actions/setup-java from 4.8.0 to 5.4.0 (#1542) - Bump peter-evans/create-pull-request from 7.0.11 to 8.1.1 (#1541) - Bump actions/cache/save from 4.3.0 to 6.1.0 (#1540) - Bump dawidd6/action-send-mail from 3.12.0 to 18 (#1539) - Fix JulLogger CPU burn from unconditional stack-trace walk (#1511) (#1515) - Fix telemetry misattribution across connections on the same thread (#1531) - Accept OAuth M2M client id/secret via JDBC user/password (#1132) (#1533) - Bump actions/checkout from 4.3.1 to 7.0.0 (#1484) - Bump dawidd6/action-send-mail from 3.11.0 to 3.12.0 (#1486) - Bump actions/github-script from 7.0.1 to 9.0.0 (#1488) - Bump softprops/action-gh-release from 1 to 3 (#1487) - Bump actions/stale from 8.0.0 to 10.3.0 (#1479) - Add release notes for v3.4.1 (#1522) - Harden OAuth U2M token cache encryption and file permissions (#1520) - Make Connection.setReadOnly a no-op instead of throwing (#1523) - Bump shaded jackson 2.18.7 to 2.18.8 to fix CVE-2026-54512 and CVE-2026-54513 in uber jar (#1507) - Use offline cache for Security Scan on fork PRs (#1514) - Fix Maven cache warmer to cache surefire-junit-platform provider (#1513) - Redact credentials in DatabaseMetaData.getURL() and parse errors (#1502) - Redact Azure and GCS presigned URL credentials in logs (#1501) - Redact access token before logging in setClientInfoProperty (#1498) - Bump Databricks SDK for Java from 0.106.0 to 0.118.0 (#1500) - Fix getColumns() flooding DriverManager log writer with stack traces (#1494) - Fix timezone-shifted TIMESTAMP in nested complex types (ES-1978662) (#1492) - Fix closeOnCompletion() infinite recursion on ResultSet/Statement close (ES-1978361) (#1493) - Harden binary parameter interpolation against SQL injection (#1497) - Fix supportsBatchUpdates() to honor EnableBatchedInserts (#1496) - Surface truncated flag from SEA result manifest (#1503) - Use async wait timeout for SEA when direct results disabled (fix hybrid-path truncation) (#1476) - Fix metadata identifiers containing backticks (#1474) - Fix chunk download failures mis-bucketed as CONNECTION_ERROR in telemetry (#1469) - Fix double backtick wrapping in setCatalog and setSchema (#1454) - v3.4.1 Bump (#1467) - Bump databricks-sdk-java from 0.69.0 to 0.106.0 (#1465) - Add debug logging for connector-service feature flags request and response (#1462) - [PECOBLR-2321] Result Set Heartbeat / Keep-Alive for Ongoing Query Executions (#1415) - Unify weekly + per-PR security scanning into a single workflow (#1460) - Fix PreparedStatement.getMetaData() crash for SQL type aliases (#1289) - Bump shaded bouncycastle and libthrift to clear remaining CVE findings (#1461) - Fix telemetry HTTP client socket leak preventing CRaC checkpoint (#1333) - Deprecate EnableArrow — Arrow always enabled except on AIX/IBM Power (#1450) - Fix DML misclassification for statements containing UNION/INTERSECT/EXCEPT (#1420) - Fix client-side maxRows enforcement in ResultSet.next() (#1448) - Bump shaded jackson, httpcore5-h2, netty, commons-configuration2, lz4 to address CVEs (#1456) - Proactive server-side statement close when results consumed (#1444) - Update NEXT_CHANGELOG with detailed breaking changes for 3.4.1 (#1449) - Fix getTables(types=[]) returning rows in Thrift mode (#1451) - Close server-side operation on Statement re-execution (#1422) - Fix SQLInterpolator treating ? in comments and literals as placeholders + shorten next_changelog (#1424) - Enable native geospatial type support by default (#1446) - Add MetadataOperationTimeout support for SHOW commands metadata path (#1417) - [ES-1884446] Classify transient/mis-categorized server errors with retryable SQL states (#1430) - Distinguish Arrow schema parsing failures from generic ResultSet errors (#1443) - Add server-side SAFE flag for UseQueryForMetadata rollout on DBSQL (#1437) - Decouple geospatial support from complex datatype flag (#1438) - Update release-notes.txt for 3.3.3 and mark 3.3.2 as DEPRECATED (#1441) - Cut new release 3.3.3 (#1434) - Fix unresolvable 3.3.2 Maven Central POM for uber jar (#1432) - Fix main CI: JFrog mirror bypass and Windows pwsh parse error (#1428) - Cut new release 3.3.2 (#1419) - Enable release freeze for 3.3.2 (#1427) - Fix cancel error handling: vendor code, telemetry level, SEA async path (#1425) - Improve error messages for transient HTTP failures during Thrift polling (#1426) - Fix SEA result expiry error handling — preserve server error message (#1302) - Fix ambiguous errors when statements are cancelled or connection closed (#1291) - Fix race condition between chunk release and download error handling (#1407) - Revert UseQueryForMetadata default to 0, make SHOW commands opt-in (#1421) - Force Thrift mode when metadata params require native RPCs (#1416) - [PECOBLR-2086] MST transaction tests — parameterized for SEA/Thrift (#1366) - Change UseQueryForMetadata default to 1 (SHOW commands) (#1413) - Fix statement close behavior for direct results in SEA (#1400) - Add SPOG support for ?o= routing in httpPath (#1316) - Fix batched insert regex to support backtick-quoted identifiers with special characters (#1403) - Fix getCrossReference case-insensitive parent matching (#1411) - [PECOBLR-2318] Unify EnableDirectResults and EnableSQLExecDirectResults params (#1409) - Fix IntervalConverter crash on CloudFetch interval columns (#1397) - [PECOBLR-1928] Add AI coding agent detection to User-Agent header (#1230) - [PECOBLR-2409] Add CallableStatement support with IN parameters (#1371) - Add VARIANT type to ColumnInfoTypeName for correct SEA metadata (#1388) - Fix GEOMETRY/GEOGRAPHY DATA_TYPE mapping in Thrift getColumns() (#1387) - SEA metadata: throw for invalid null/empty params (Thrift parity) (#1390) - Add vulnerability scan gate to release workflows (#1396) - Fix cache warmer: add Windows runner, timestamp-based cache keys (#1395) - Fix cache warmer: add clean to resolve maven-clean-plugin and exec-maven-plugin (#1394) - Fix: normalize _remote.repositories repo ID for offline mode (#1393) - Fix: non-fork cache path must be restore-only (#1392) - Remove _remote.repositories from cache + use offline mode for forked PRs (#1391) - Fix fork Maven config: set updatePolicy=never to prevent 401 on cached artifacts (#1389) - Fix cache warmer: run real test to resolve surefire provider (#1385) - Revert Windows git install, restore original Enable long paths step (#1383) - Fix cache warmer: use install only, drop dependency:resolve (#1382) - Fix cache warmer: use install for inter-module SNAPSHOT resolution (#1381) - Fix cache warmer: Linux-only, OS-agnostic cache key (#1380) - Bump version to 3.3.2-SNAPSHOT (#1292) - Bump netty.version from 4.2.6.Final to 4.2.12.Final (#1347) - Use Databricks protected runner group for CI actions (#1369) - Resolve null catalog/schema in SEA key-based metadata operations (#1370) - Fix getSchemas returning JDBC-escaped catalog name in SEA mode (#1365) - Fix IllegalFormatConversionException in JulLogger error logging with Throwable (#1372) - Simplify SEA disposition: use connection parameters instead of statement type (#1322) - Fix CI failures: replace gh API calls blocked by IP allow list (#1363) - Fix SEA metadata JDBC spec compliance: catalog handling, empty types, non-existent objects (#1308) - Fix SEA volume operations failing with Statement is closed (#1323) - Address open supply chain security action items (#1359) - Disable publishing workflows per third-party package freeze (#1354) - Migrate all CI workflows from Databricks runners to GitHub-hosted runners (#1350) - Pin all GitHub Actions to commit SHAs (#1324) - Harden CI/CD supply chain security across all workflows (#1328) - Migrate dco-check and vulnerabilityCatcher to Databricks runners (#1327) - Prevent script injection in coverageReport workflow (#1295) - Improve instructions for jdk8 branch update (#1298) - Use version property for jts-core dependency (#1297) - Add OWASP suppression for CVE-2026-25087 and re-enable dependency check in release (#1296) - Add Claude GitHub Actions workflows (#1288) - Move dependencyManagement to parent pom to fix CVE-2025-48924 in uber jar (#1294) - Fix backtick quoting for column names in batched INSERT reconstruction (#1285) - Fix primitive type parsing in complex types for Arrow-serialized formats (#1250) - Skip OWASP dependency check in release build step (#1286) - Cut new release 3.3.1 (#1281) - [PECOBLR-1746] Implementing support for listing procedures (#1238) - Fix IdleConnectionEvictor thread leak in long-running services (#1271) - [ES-1717770] Fix TIMEDOUT_STATE not recognized as error on interactive clusters (#1244) - [ES-1765150] Coalesce concurrent expired-link refreshes into single batch RPC (#1277) - [ES-1774740] Fix Thrift polling infinite loop on invalid operation handle (#1273) - Add /sync-jdk8-branch slash command + update the jdk8 action workflow (#1274) </details> NO_CHANGELOG=true This pull request and its description were written by Isaac. [PECOBLR-3778]: https://databricks.atlassian.net/browse/PECOBLR-3778?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ --------- Signed-off-by: Vikrant Puppala <[email protected]> Signed-off-by: dependabot[bot] <[email protected]> Signed-off-by: samikshya-chand_data <[email protected]> Signed-off-by: Sreekanth Vadigi <[email protected]> Signed-off-by: Nikhil Suri <[email protected]> Signed-off-by: Gopal Lal <[email protected]> Signed-off-by: rileythomp <[email protected]> Signed-off-by: Samikshya Chand <[email protected]> Signed-off-by: Madhavendra Rathore <[email protected]> Signed-off-by: Oleksandr Shevchenko <[email protected]> Signed-off-by: Shivam Raj <[email protected]> Signed-off-by: Madhavendra Rathore Signed-off-by: Dan Homola <[email protected]> Signed-off-by: Matthieu Sprunck <[email protected]> Signed-off-by: Matthieu Sprunck <[email protected]> Signed-off-by: Eric Wang <[email protected]> Signed-off-by: eric-wang-1990 <[email protected]> Signed-off-by: Prathamesh Baviskar <[email protected]> Signed-off-by: Cathleen Yan <[email protected]> Signed-off-by: Vu Anh Phung <[email protected]> Signed-off-by: Michael Simons <[email protected]> Signed-off-by: Cathleen Yan <[email protected]> Signed-off-by: Rahul Singhal <[email protected]> Signed-off-by: Aakash Saravanan <[email protected]> Signed-off-by: peco-engineer-bot[bot] <287056288+peco-engineer-bot[bot]@users.noreply.github.com> Co-authored-by: Gopal Lal <[email protected]> Co-authored-by: Samikshya Chand <[email protected]> Co-authored-by: Madhavendra Rathore <[email protected]> Co-authored-by: Vikrant Puppala <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: tejassp-db <[email protected]> Co-authored-by: jayant <[email protected]> Co-authored-by: Sreekanth <[email protected]> Co-authored-by: Claude Sonnet 4.5 <[email protected]> Co-authored-by: Jothi Prakash <[email protected]> Co-authored-by: Shivam Raj <[email protected]> Co-authored-by: nikhilsuri-db <[email protected]> Co-authored-by: Riley Thompson <[email protected]> Co-authored-by: Oleksandr Shevchenko <[email protected]> Co-authored-by: Oleksandr Shevchenko <[email protected]> Co-authored-by: Madhav Sainanee <[email protected]> Co-authored-by: Dan Homola <[email protected]> Co-authored-by: Thomas Powell <[email protected]> Co-authored-by: Matthieu Sprunck <[email protected]> Co-authored-by: eric-wang-1990 <[email protected]> Co-authored-by: Prathamesh Baviskar <[email protected]> Co-authored-by: vuanhphung <[email protected]> Co-authored-by: Michael Simons <[email protected]> Co-authored-by: vuanhphung <[email protected]> Co-authored-by: Rahul Singhal <[email protected]> Co-authored-by: Isaac <[email protected]> Co-authored-by: aakash-saravanan-db <[email protected]> Co-authored-by: peco-engineer-bot[bot] <287056288+peco-engineer-bot[bot]@users.noreply.github.com>
Summary
For direct results in SEA, the server returns CLOSED state with inline results. Previously,
markAsClosed()setisClosed=trueon the JDBC Statement, preventing re-execution andgetResultSet()calls. Per JDBC spec, a Statement should remain open until the user explicitly callsclose().Problem
executeQuery()thengetResultSet()threw "Statement is closed"getExecutionResult()(async path) made an RPC that returned "not found" since the server already closed the operationFix
Replace
markAsClosed()withmarkDirectResultsReceived()which sets a newdirectResultsReceivedflag WITHOUT closing the JDBC Statement:close()skips server-sidecloseStatementwhendirectResultsReceived(server already cleaned up)getExecutionResult()returns cached result for direct results instead of an RPCTest plan
DatabricksStatementTest-- 85 tests pass (3 updated for new behavior)DatabricksSdkClientTest-- 28 tests pass (1 updated for method rename)