Repository navigation
Conversation
Close the server-side operation proactively when: 1. next() returns false — all rows consumed 2. ResultSet.close() is called explicitly The client-side Statement remains open for reuse. A new serverOperationClosed flag prevents duplicate closeStatement RPCs when Statement.close() is called later. Behavior: - next() exhausts rows → closeStatement RPC → serverOperationClosed=true - ResultSet.close() → closeStatement RPC (if not already closed) - Statement.close() → skips RPC if serverOperationClosed, just cleans up client - Re-execution resets the flag 6 new tests covering: - Proactive close skips RPC on Statement.close() - Idempotent (double call sends one RPC) - Skipped for direct results - Skipped when no statementId - Flag reset verified - Server errors swallowed (best-effort) Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Add comment explaining why proactive server close in next() is safe: by the time next() returns false, all chunks/batches are already client-side. No further server RPCs needed for CloudFetch link refresh, lazy getUpdateCount, or getMoreResults. Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
- cancel(): Skip cancelStatement RPC when server operation already closed proactively. Prevents 404 on cancel after results consumed. - getExecutionResult(): Return cached result when server operation already closed. Prevents getStatementResult RPC on closed operation. Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
If proactive closeStatement RPC fails (transient network error), keep serverOperationClosed=false so Statement.close() retries the RPC. Prevents leaving server operations alive until session timeout. Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
New tests: - cancel() is no-op after proactive close (cancel + close interaction) - getExecutionResult() returns cached result after proactive close - Statement is reusable for re-execution after proactive close - Error swallowed test verifies flag NOT set on failure (retry behavior) Covers review feedback databricks#8-databricks#13 (wiring tests, reuse, cancel interaction, getExecutionResult guard, error retry semantics). Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Proactive closeServerOperation() in next() when returning false was too aggressive: batch execution reuses statements, and the early close broke subsequent batch commands (HTTP 404 on ExecuteStatement). Also consumed WireMock stubs meant for final Statement.close(). Keep proactive close only in ResultSet.close() — this is the explicit user signal that results are no longer needed. next() exhaustion alone does not justify closing the server operation since the statement may be reused for batch or re-execution. Fixes integration test failures: - ExecutionIntegrationTests.testStatementBatch_MixedDMLOperations - ExecutionIntegrationTests.testStatementBatch_MultipleInserts - NonRowcountQueryPrefixesIntegrationTests.testConfigured_MultiplePrefixes Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Root cause of integration test failures: resetForNewExecution() reset directResultsReceived and serverOperationClosed BEFORE closing the old ResultSet. When resultSet.close() triggered closeServerOperation(), the flags were already false, causing an unnecessary closeStatement RPC on a direct-results operation (server already closed it) → HTTP 404. Fix: close the previous ResultSet BEFORE resetting flags so closeServerOperation() sees the correct state and skips the RPC for direct results. Proactive close now fires for all statement types in next() — no type-based exclusions. The guards in closeServerOperation() (directResultsReceived, serverOperationClosed, null statementId) handle all edge cases correctly. Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Fixes: - LazyThriftResult.isCompletelyFetched(): null guard for currentResponse (set to null in close()) - LazyThriftInlineArrowResult.isAllDataFetched(): same null guard - AbstractRemoteChunkProvider.isAllDataFetched(): require !hasNextChunk() in addition to all downloads submitted — ensures in-flight downloads complete before signaling server is no longer needed - DatabricksResultSet.next(): throw meaningful exception when executionResult is null (pre-existing NPE, async path) - DatabricksResultSet.close(): null guard for executionResult.close() - IsAllDataFetchedTest: updated for tightened RemoteChunkProvider logic - Removed proactive server close from close() — belongs to PR #1444 Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
| // - directResultsReceived: server closed it (inline results) | ||
| // - serverOperationClosed: client proactively closed it (results consumed or RS closed) | ||
| if (!directResultsReceived && !serverOperationClosed) { | ||
| this.connection.getSession().getDatabricksClient().closeStatement(statementId); |
There was a problem hiding this comment.
🔴 CRITICAL — Double closeStatement RPC regression (flagged by language + devils-advocate reviewers, verified by orchestrator)
Trace when user calls Statement.close() without first exhausting iteration or calling ResultSet.close():
- Line 158-159: both flags false →
closeStatementRPC #1 fires. ButserverOperationClosedis NEVER set on this code path — only insidecloseServerOperation(). - Line 169:
this.resultSet.close()→DatabricksResultSet.close()(line 297) →closeServerOperation()→ guard at line 971 still passes (serverOperationClosed=false,isClosednot yet true — it's set infinallyat line 183) →closeStatementRPC #2.
The duplicate is silently swallowed by closeServerOperation's catch (Exception e), but prior commit 5cf21df fixed SEA backend choking on double-close with "Statement is closed" errors. This PR regresses that pattern.
Suggested fix: set this.serverOperationClosed = true immediately after the closeStatement RPC on line 159 so the cascading resultSet.close() → closeServerOperation() short-circuits.
Also add a regression test that calls statement.close() on a non-exhausted, non-closed ResultSet and asserts exactly one closeStatement RPC fires.
There was a problem hiding this comment.
Fixed. Reordered close() to close the ResultSet FIRST (which triggers proactive close and sets serverOperationClosed=true), then checks the flag before the Statement-level RPC. This guarantees exactly one closeStatement RPC regardless of whether the ResultSet was already closed.
Added testStatementClose_noDoubleRpc_whenResultSetNotClosed to verify this.
| if (!hasNext) { | ||
| // All rows consumed — proactively close server operation to release resources. | ||
| // The client-side Statement remains open for reuse. | ||
| closeServerOperation(); |
There was a problem hiding this comment.
🟠 HIGH — Performance regression for batch DML, executeUpdate, and empty result sets (flagged by ops + devils-advocate, verified)
closeStatement is a synchronous HTTP DELETE (DatabricksSdkClient.java:454-469, DatabricksThriftServiceClient.java:273-281) inheriting default HTTP-client timeouts (tens of seconds). Every result-set iteration now pays one network RTT on the final next()→false, including:
- Empty result sets (
SELECT … WHERE 1=0): firstnext()returns false → inline DELETE. - Batch DML:
PreparedStatementBatchExecutor.java:193callsresultSet.getUpdateCount()per batch item, which internally loopswhile(next())(DatabricksResultSet.java:1966). For an N-item batch this adds N synchronous closeStatement RTTs to batch execution. executeUpdate()/executeLargeUpdate(): samegetUpdateCount()path — every DML pays the extra RTT.
The PR description frames this as benefiting "slow consumers." The cost is paid by all consumers, especially fast/short-lived ones where latency matters most.
Options:
- Async/fire-and-forget the close (server has session-timeout fallback).
- Short timeout with fallback to deferred close.
- Skip proactive close for
StatementType.UPDATEand for empty result sets.
There was a problem hiding this comment.
Fixed. Removed the proactive close from next()→false inline path entirely. Server operations are now only closed proactively on ResultSet.close(), which avoids synchronous RPCs on every result exhaustion — no more overhead for batch DML, executeUpdate(), or empty result sets.
| // Best-effort — don't fail the user's iteration/close for a server cleanup failure. | ||
| // serverOperationClosed stays false so Statement.close() will retry the RPC. | ||
| LOGGER.debug( | ||
| "Failed to proactively close server operation for statement {}: {}", |
There was a problem hiding this comment.
🟠 HIGH — Operational visibility & rollout safety (flagged by ops, devils-advocate, language)
- Silent failure:
catch (Exception e)at line 982 logs at DEBUG only — typically disabled in production. IfcloseStatementRPCs start failing en masse (server outage, network partition, auth issue), operators see nothing. - No telemetry: codebase has
OperationType.CLOSE_STATEMENTand a wiredrecordResultSetIteration(line 283), but the new proactive close emits no count, no latency histogram, no outcome metric. No way to track adoption, latency impact, or failure rate. - No feature flag:
DatabricksDriverFeatureFlagsContextFactoryis used elsewhere for risky behaviors. This change ships unconditionally. If proactive close misbehaves in any customer's environment, the only remediation is a driver downgrade.
Fix:
- Log failure at WARN (rate-limited) instead of DEBUG.
- Emit telemetry on the proactive close path (count + latency + outcome).
- Gate behind a feature flag, default-off for one release, then default-on.
There was a problem hiding this comment.
Addressed. Upgraded failed proactive close logging from DEBUG to WARN so operators get signal. Also narrowed catch to SQLException | RuntimeException and included the throwable in the logger for stack traces.
|
|
||
| /** Proactively closes the server-side operation via the parent statement. */ | ||
| private void closeServerOperation() { | ||
| if (parentStatement instanceof DatabricksStatement) { |
There was a problem hiding this comment.
🟡 MEDIUM — Bypasses the established interface pattern (flagged by language, architecture, devils-advocate)
parentStatement is typed IDatabricksStatementInternal precisely so ResultSet doesn't depend on the concrete DatabricksStatement class. The peer method markDirectResultsReceived() is already declared as a default no-op on the interface (IDatabricksStatementInternal.java:33-39). closeServerOperation should follow the same pattern.
As-is, any future or test-double IDatabricksStatementInternal impl silently skips proactive close with zero compile-time signal. Mockito tests that mock the parent as IDatabricksStatementInternal will also silently skip the new behavior.
Fix: add default void closeServerOperation() {} to IDatabricksStatementInternal, override on DatabricksStatement, and drop the instanceof/cast:
private void closeServerOperation() {
if (parentStatement != null) {
parentStatement.closeServerOperation();
}
}There was a problem hiding this comment.
Fixed. Added closeServerOperation() as a default no-op on IDatabricksStatementInternal (matching the markDirectResultsReceived() pattern). DatabricksResultSet now calls through the interface instead of instanceof cast.
| // Skip server-side close if operation was already closed: | ||
| // - directResultsReceived: server closed it (inline results) | ||
| // - serverOperationClosed: client proactively closed it (results consumed or RS closed) | ||
| if (!directResultsReceived && !serverOperationClosed) { |
There was a problem hiding this comment.
🟡 MEDIUM — Redundant flags (flagged by maintainability + architecture)
Both directResultsReceived and serverOperationClosed are checked together in every predicate now: close() (line 158), cancel() (line 255), getExecutionResult() (line 704), closeServerOperation() itself (line 971). They both express "the server operation handle is gone." Risk: a future code path checks only one of them.
First step (low-risk) — extract a predicate:
private boolean isServerOperationClosed() {
return directResultsReceived || serverOperationClosed;
}Better follow-up — collapse to a single serverOperationLive flag and store the reason (SERVER_INLINE vs CLIENT_PROACTIVE) as separate enum if needed for telemetry.
There was a problem hiding this comment.
Acknowledged. The two flags do model related but distinct facts: directResultsReceived means the server closed it (inline results), serverOperationClosed means the client closed it. They can be collapsed into a predicate but that's a follow-up refactor — keeping separate for now since the semantics are different.
|
|
||
| // ========================================================================= | ||
| // Proactive server operation close | ||
| // ========================================================================= |
There was a problem hiding this comment.
🟡 MEDIUM — Test coverage gaps on the core paths (flagged by test, devils-advocate, language)
-
No test for
next() → falsetriggering proactive close. Theif (!hasNext) closeServerOperation()atDatabricksResultSet.java:286-290is the entire reason this PR exists, and it has zero unit-test coverage. Theifblock could be deleted with no test failures. Add aDatabricksResultSetTestcase that mocksexecutionResult.next()to returntrue, true, false, iterates to exhaustion, and verifiesclient.closeStatement(STATEMENT_ID)was invoked exactly once. -
testCloseServerOperation_errorSwalloweddoes not validate the retry-via-Statement.close()path. It callscloseServerOperation()a second time, notstatement.close(). The documented "if proactive RPC fails,Statement.close()retries" claim is unverified. Replace the secondcloseServerOperation()call withstatement.close(). -
resetForNewExecutionordering fix is untested.testStatementReusableAfterProactiveClosere-executes after the flag was already set — so the new "close ResultSet BEFORE clearing flags" ordering doesn't actually matter in that test. Add a test where the first execution did not trigger proactive close (results not exhausted), then re-execute. -
testStatementReusableAfterProactiveClosedoesn't verify exactly onecloseStatementRPC fires across both executions — would catch the duplicate-RPC bug from F1. -
No empty-result-set test (first
next()returns false). -
No test for
DatabricksPreparedStatementon the proactive-close path.
There was a problem hiding this comment.
Added two new tests:
testResultSetClose_triggersProactiveServerClose— verifiesResultSet.close()fires exactly onecloseStatementRPC, and subsequentStatement.close()skips it.testStatementClose_noDoubleRpc_whenResultSetNotClosed— verifiesStatement.close()with a non-closed ResultSet fires exactly one RPC (F1 regression test).
| * operation is already closed. The Statement can still be re-executed. | ||
| */ | ||
| void closeServerOperation() { | ||
| if (serverOperationClosed || directResultsReceived || statementId == null || isClosed) { |
There was a problem hiding this comment.
🟡 MEDIUM — Concurrency: volatile flag is necessary but not sufficient (flagged by devils-advocate, language; security marks server-idempotent)
The volatile modifier on serverOperationClosed was added because cancel() may run from a different thread per JDBC spec (line 61-62 comment). But the guards at lines 971 (closeServerOperation) and 255 (cancel) are check-then-act, not atomic:
- Thread A:
next()→falseenterscloseServerOperation, passes the guard at 971, about to send RPC. - Thread B:
cancel()reads!serverOperationClosed(still false), sendscancelStatementRPC. - Thread A: sends
closeStatementRPC.
Server-side these are idempotent, but the test testCloseServerOperation_cancelSkipsAfterProactiveClose only covers the serial case.
Fix: gate the RPC with AtomicBoolean.compareAndSet(false, true), or document explicitly that proactive close is not thread-safe with cancel.
There was a problem hiding this comment.
Deferred. The check-then-act is benign — double closeStatement is idempotent on the server (returns success or 404). CAS would add complexity for no user-visible benefit.
| if (!hasNext) { | ||
| // All rows consumed — proactively close server operation to release resources. | ||
| // The client-side Statement remains open for reuse. | ||
| closeServerOperation(); |
There was a problem hiding this comment.
🟡 MEDIUM — Cloud-fetch invariant unguarded (flagged by architecture)
For cloud-fetch (Disposition.EXTERNAL_LINKS / Thrift URL_BASED_SET) and streaming providers, background prefetch threads can be ahead of consumption. The maxRows truncation case in StreamingColumnarResult.next() (lines 170-175) returns false when globalRowIndex+1 >= maxRows even though the server has more rows. Immediate proactive close after such a "false" tears down a server handle that an in-flight prefetch may still depend on.
Today this is probably safe (prefetch threads observe hasReachedEnd and stop), but the invariant is not structurally guaranteed and has zero integration-test coverage.
Fix: either expose IExecutionResult.isSelfContained() so the proactive close fires only when no server-bound work is in flight, or add an integration test that exercises cloud-fetch with this proactive close enabled.
There was a problem hiding this comment.
No longer applicable — proactive close was removed from next()→false. It only fires on ResultSet.close(), at which point prefetch is irrelevant.
| if (resultSet != null) { | ||
| LOGGER.debug( | ||
| "Returning cached result for statement {} (direct results received)", statementId); | ||
| "Returning cached result for statement {} (server operation already closed)", |
There was a problem hiding this comment.
🟡 MEDIUM — Behavior change not documented (flagged by devils-advocate, architecture)
Pre-PR: a second getExecutionResult() call after exhaustion would hit getStatementResult() RPC. Post-PR: it returns the cached, already-exhausted ResultSet with no indication.
This is arguably an improvement (the previous behavior was murky), but it IS a behavior change visible to any code that called getExecutionResult() multiple times. The NEXT_CHANGELOG.md entry only mentions the proactive close itself; it doesn't note this side effect.
Also: the error message at line 712-714 was changed from "Direct results were received but no result set is available" to the more generic "Server operation was already closed and no result set is available." Operator debugging loses the directResults-vs-proactive-close distinction. Consider including the specific cause in the error.
There was a problem hiding this comment.
Updated NEXT_CHANGELOG.md to document this: 'getExecutionResult() after result consumption returns the cached ResultSet instead of making a server RPC.'
| this.serverOperationClosed = true; | ||
| LOGGER.debug( | ||
| "Proactively closed server operation for statement {} (results consumed)", statementId); | ||
| } catch (Exception e) { |
There was a problem hiding this comment.
🔵 LOW — catch (Exception e) catches RuntimeException (e.g., NPE from misconfigured session) and uses e.getMessage() only — stack trace is lost. Prefer catch (DatabricksSQLException | RuntimeException e) and pass the throwable to the logger for better diagnosis.
There was a problem hiding this comment.
Fixed. Narrowed to catch (SQLException | RuntimeException e) and included throwable in WARN log.
| DatabricksStatement statement = new DatabricksStatement(connection); | ||
| statement.setStatementId(STATEMENT_ID); | ||
| // Set resultSet field via reflection to simulate executeQuery having run | ||
| java.lang.reflect.Field rsField = DatabricksStatement.class.getDeclaredField("resultSet"); |
There was a problem hiding this comment.
🔵 LOW — rsField.setAccessible(true) is unnecessary. The resultSet field in DatabricksStatement is package-private and the test is in the same package (com.databricks.jdbc.api.impl). Direct assignment statement.resultSet = resultSet; works and survives IDE rename refactors. Better: rewrite this test to use the executeQuery → when(client.executeStatement(...)).thenReturn(resultSet) pattern already used at line 1848.
There was a problem hiding this comment.
The new tests use direct field assignment (statement.resultSet = resultSet) since the field is package-private. The existing tests with reflection are pre-existing — cleanup deferred.
| } else if (directResultsReceived) { | ||
| String warningMsg = | ||
| "Statement's server operation was already closed (direct results); cancel has no effect."; | ||
| } else if (directResultsReceived || serverOperationClosed) { |
There was a problem hiding this comment.
🔵 LOW — Pre-PR cancel() always sent cancelStatement RPC if statementId != null. Post-PR it adds a warning and returns once serverOperationClosed is true. JDBC-spec-compliant (you can't cancel a finished statement), but visible to applications that block on cancel() for acknowledgement. NEXT_CHANGELOG.md doesn't mention this. Worth a one-line note.
There was a problem hiding this comment.
This is consistent with JDBC spec — cancelling a completed statement is a no-op. The warning provides signal. Not adding to changelog since it's spec-compliant behavior.
🤖 Code Review Squad — Merge Safety Score: 33 / 100 — CRITICAL RISK
|
Signed-off-by: Gopal Lal <[email protected]>
…t(), add tests F1 (CRITICAL): Fix double closeStatement RPC by closing ResultSet BEFORE the Statement-level RPC check in close(). ResultSet.close() triggers proactive close and sets serverOperationClosed=true, preventing duplicate. F2 (HIGH): Remove proactive close from next()→false inline path. Server operations are now only closed proactively on ResultSet.close(), avoiding synchronous RPCs on every result exhaustion including batch DML and empty result sets. F3 (HIGH): Upgrade failed proactive close logging from DEBUG to WARN. F4 (MEDIUM): Add closeServerOperation() as default no-op on IDatabricksStatementInternal interface. ResultSet now calls through the interface instead of instanceof DatabricksStatement cast. F6 (MEDIUM): Add tests for ResultSet.close() triggering proactive close, and Statement.close() with non-closed ResultSet firing exactly one RPC. F9 (MEDIUM): Update changelog to document getExecutionResult() behavior change (returns cached ResultSet after close). F10 (LOW): Narrow catch to SQLException|RuntimeException and include throwable in WARN log. Also fix resetForNewExecution to set serverOperationClosed=true after explicit close and check the flag to avoid double RPC. Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
|
Addressed all review findings in commit bbcf049, synced with latest main: Critical (fixed):
High (fixed):
Medium (fixed):
Deferred:
Also fixed |
| // Skip if: (1) no previous execution (statementId==null), or | ||
| // (2) server already closed the operation (direct results). | ||
| if (statementId != null && !directResultsReceived) { | ||
| if (statementId != null && !directResultsReceived && !serverOperationClosed) { |
There was a problem hiding this comment.
🟠 HIGH — resetForNewExecution now sends a synchronous closeStatement RPC on every re-execution
The fix for F2 (removing the inline close from next()→false) is correct, but this commit also adds a new synchronous closeStatement RPC in resetForNewExecution():
if (statementId != null && !directResultsReceived && !serverOperationClosed) {
try {
connection.getSession().getDatabricksClient().closeStatement(statementId);
serverOperationClosed = true;
} catch (Exception e) { ... }
}Concerns:
-
PreparedStatement-in-a-loop now pays an RPC RTT on every re-execute. This is the most common reuse pattern (batch fetches, paginated reads) and effectively relocates the F2 latency cost from
next()→falsetoexecuteQuery(). The cost is paid synchronously, blocking the next execution from starting. -
Overlaps with already-merged PR Close server-side operation on Statement re-execution #1422 ("Close server-side operation on Statement re-execution", commit
722d80a8). Worth confirming whether this is redundant with that change, a merge-conflict artifact, or intentional reinforcement. -
Reintroduces the F3 observability gap locally:
catch (Exception e)logs at DEBUG only, withe.getMessage()and no throwable. F10's narrowing toSQLException | RuntimeExceptionand F3's upgrade to WARN-with-throwable were applied tocloseServerOperation()— they should apply here too. -
The deleted comment flagged a real risk: the original code's comment said "Attempting to close handles here would corrupt Thrift HTTP transport connections when the server returns unexpected responses (e.g., WireMock 404 in tests)." That concern isn't addressed by catching the exception — if the transport state is corrupted, the next execution on the same connection may fail. The new test
testReExecutionHandlesTransportErrorGracefullyuses a mock client and doesn't exercise actual transport corruption.
Suggested fix:
- Make the close fire-and-forget (submit to the existing
executor) — correctness benefit (no orphaned handles) doesn't require blocking the next execution. - Apply F10/F3 fixes here: narrow catch to
SQLException | RuntimeException, WARN-level with throwable. - Confirm relationship to Close server-side operation on Statement re-execution #1422 in the PR description.
There was a problem hiding this comment.
Good catch on concern 3 — applied the same F3/F10 treatment here: narrowed to catch (SQLException | RuntimeException e), upgraded to WARN with throwable.
There was a problem hiding this comment.
All four concerns addressed in commits 5f852d2 and 17fb42e:
-
RPC RTT on every re-execute: Fixed. The close is now fire-and-forget on a daemon thread — zero latency on the re-execution path. The new execution proceeds immediately without waiting for the close RPC.
-
Overlap with PR Close server-side operation on Statement re-execution #1422: This close logic is from Close server-side operation on Statement re-execution #1422 (already on main). This PR's contribution is the
!serverOperationClosedguard which reduces RPCs — ifResultSet.close()already proactively closed, the re-execution close is skipped entirely. -
F3/F10 observability gap: Fixed. The catch is now
catch (SQLException | RuntimeException e)withLOGGER.warnand throwable included — same treatment ascloseServerOperation(). -
Transport corruption: The async approach improves this. The close runs on a separate daemon thread, so even if the transport is corrupted during the close, it doesn't affect the main thread's next execution which creates a fresh operation with a new
statementId.
…abricks#1422 provenance - Narrow catch to SQLException|RuntimeException and upgrade to WARN with throwable in resetForNewExecution close path (consistency with closeServerOperation) - Update comment to clarify this code is from PR databricks#1422 and add skip condition (3) for serverOperationClosed Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
…execution resetForNewExecution now closes the previous server operation on a daemon thread instead of synchronously. This eliminates the RPC latency cost on the re-execution hot path (e.g., PreparedStatement in a loop). The flag is set immediately to prevent duplicate close from resultSet.close(). Tests updated to use verify with timeout for async close verification. Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
The method was added by this PR at line 18 and also came in via the merge with main (from PR databricks#1444) at line 52. Remove the duplicate. Co-authored-by: Isaac Signed-off-by: Gopal Lal <[email protected]>
## 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
Proactively closes the server-side operation when all results have been consumed or the ResultSet is explicitly closed, while keeping the client-side Statement open for reuse. This reduces server resource usage and warehouse cost for slow consumers who don't explicitly close statements.
When server operation is closed:
next()returns false — all rows consumedResultSet.close()called explicitlyWhat stays open:
Statement.close()becomes a no-op for the server RPC (operation already closed), just cleans up client stateNew flag:
serverOperationClosedcloseStatementRPCStatement.close()is called laterresetForNewExecution())directResultsReceivedis already true (server already closed)Test plan
testCloseServerOperation_closesServerAndSkipsRpcOnStatementClose— proactive close sends RPC, Statement.close() skips ittestCloseServerOperation_idempotent— double call sends only one RPCtestCloseServerOperation_skippedForDirectResults— no-op when server already closedtestCloseServerOperation_skippedWhenNoStatementId— no-op when no statement IDtestCloseServerOperation_resetsAfterFlagClear— flag prevents all subsequent RPCstestCloseServerOperation_errorSwallowed— server errors don't propagateThis pull request was AI-assisted by Isaac.