Skip to content

fix(bigquery-jdbc): enforce JDBC connection pooling lifecycle, state reset, and physical isolation - #15202

Open
keshavdandeva wants to merge 3 commits into
mainfrom
fix/jdbc-pooling-1-connection-reset
Open

keshavdandeva wants to merge 3 commits into
mainfrom
fix/jdbc-pooling-1-connection-reset

Conversation

@keshavdandeva

@keshavdandeva keshavdandeva commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Consolidates the 3-PR JDBC connection pooling stack (#15202, #15203, #15204) onto a single branch targeting main so all CI checks run against the complete change and the stack lands atomically.

Fixes physical connection isolation, JDBC 4.3 PooledConnection / logical Connection lifecycle contracts, and mutable connection/transaction/session state reset on pool return:

  • Connection state reset hook (BigQueryConnection.resetForReuse()): Closes remaining open Statement instances tracked in openStatements, resets autoCommit to true, rolls back any active transaction without starting a follow-up BEGIN TRANSACTION; (rollbackImpl(false) in both resetForReuse() and closeImpl()), aborts driver-created BigQuery sessions (CALL BQ.ABORT_SESSION(); when EnableSession=1) even when the calling thread is interrupted while preserving caller-configured QueryProperties=session_id=... properties, surfaces BigQueryException on pooled session abort while preserving un-aborted transaction/session state for fallback physical close(), clears clientInfo and sqlWarnings (backed by CopyOnWriteArrayList for concurrent snapshot reads), and restores holdability.
  • Lifecycle serialization, rejection-safe abort(Executor) & MDC preservation: Serializes resetForReuse() and closeImpl() via lifecycleLock; coordinates abort(Executor) and close() via closeStateLock so isClosed remains false until executor.execute accepts/starts while gating checkClosed() on closeInitiated; honors configured Timeout and inspects JobStatus on transaction commit/rollback job waits; and saves/restores outer thread MDC connectionId in BigQueryJdbcMdc.registerInstance, close(), and abort(Executor).
  • JDBC 4.3 BigQueryPooledConnection & dynamic handle/child proxies: Replaces BigQueryPooledConnectionWrapper with PooledConnectionInvocationHandler backed by a per-handle ReentrantReadWriteLock shared with pooled Statement and DatabaseMetaData proxies so operational calls hold the read lock during RPCs while close(), handle reclaim, and physical teardown await quiescence. Wraps child Statement / PreparedStatement / CallableStatement and DatabaseMetaData objects (and attaches pooled proxies on BigQueryStatement for ResultSet.getStatement()) so getConnection() enforces parentHandler.checkClosed() and returns the logical Connection handle. Fires connectionErrorOccurred and physically closes BigQueryConnection on reset failures or out-of-band physical closes, dispatches abort(Executor) teardown asynchronously, isolates listener RuntimeExceptions, and scopes MDC inside physicalLock.
  • Dedicated physical connections & concurrent LIFO checkout (PooledConnectionDataSource / PooledConnectionListener): Removes the cached shared bqConnection field from PooledConnectionDataSource so cache misses open a dedicated BigQueryConnection, recycles idle physical connections into fresh BigQueryPooledConnection holders while retiring prior holders (State.RETIRED), separates the internal pool listener from public ListenerPoolSize slots with sticky external ownership on addConnectionEventListener, uses atomic LIFO (addFirst/pollFirst) checkout under poolLock, closes excess driver-owned idle connections at ConnectionPoolSize (0 = unbounded), and clarifies ConnectionPoolSize and ListenerPoolSize in docs/USER_GUIDE.md.

Behavior Changes

  • Every cache miss on PooledConnectionDataSource.getPooledConnection() opens a dedicated physical BigQueryConnection, and idle-pool hits wrap the recycled physical connection in a new PooledConnection while retiring the previous holder.
  • Connection.close() on a pooled handle synchronously runs state/transaction/session reset RPCs when needed and propagates any reset SQLException after firing connectionErrorOccurred.
  • BigQueryPooledConnection.close() physically closes BigQueryConnection and removes the holder from PooledConnectionListener without firing connectionClosed.
  • BigQueryPooledConnection.getConnection() while a handle is open invalidates the prior handle and resets connection state without firing connectionClosed (PooledConnection#getConnection(), JDBC 4.3 section 11.1).
  • Returning a connection when the built-in idle pool is at ConnectionPoolSize closes the excess physical connection inline on the caller thread (ConnectionPoolSize=0 retains all idle connections).
  • Operational calls on a closed logical handle or retained child Statement / DatabaseMetaData throw BigQueryJdbcException (SQLClientInfoException with ClientInfoStatus.REASON_UNKNOWN for setClientInfo).

Testing

  • Added/updated unit tests in BigQueryConnectionTest, BigQueryJdbcMdcTest, BigQueryPooledConnectionTest, PooledConnectionDataSourceTest, and PooledConnectionListenerTest (1,384 unit tests passing).
  • Added integration tests in ITConnectionPoolingTest verifying independent concurrent checkouts and end-to-end session and uncommitted-transaction reset on pool return.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a resetForReuse() method to BigQueryConnection to safely reset mutable JDBC connection state, close open statements, roll back active transactions without starting a follow-up transaction, and abort driver-created sessions before the connection is returned to a pool. It also refactors exception handling and adds comprehensive unit tests to verify these behaviors. The reviewer suggested resetting the mutable isReadOnlyTokenUsed state to false during connection reuse to prevent state leakage across connections.

@keshavdandeva
keshavdandeva force-pushed the fix/jdbc-pooling-1-connection-reset branch from 4181266 to 151cf1d Compare November 24, 2026 22:46
@keshavdandeva keshavdandeva changed the title fix(bigquery-jdbc): add connection state and session reset hook for pooling fix(bigquery-jdbc): add connection state reset hook and async abort support Nov 24, 2026
@keshavdandeva
keshavdandeva force-pushed the fix/jdbc-pooling-1-connection-reset branch from 151cf1d to 41da6f5 Compare November 27, 2026 14:21
…upport

- Add package-private BigQueryConnection.resetForReuse() to close open statements, reset autoCommit to true, roll back active transactions without starting a follow-up transaction, abort driver-created sessions even when the calling thread is interrupted, surface BigQueryException on pooled session abort while preserving un-aborted session/transaction state for physical teardown, clear clientInfo and SQLWarnings, and restore holdability.
- Serialize resetForReuse() and closeImpl() via lifecycleLock, pass startNextTransaction=false from closeImpl() so physical close does not start a new transaction on caller-managed sessions, and preserve outer caller MDC context in BigQueryJdbcMdc.registerInstance, close(), and abort(Executor).
- Coordinate BigQueryConnection.abort(Executor) and close() via closeStateLock so rejecting executors never expose transient isClosed=true or cause concurrent close() to return early, gate checkClosed() on closeInitiated, and honor configured Timeout on transaction commit/rollback job waits.
- Track optional pooled logical Connection and Statement proxies on BigQueryStatement so ResultSet.getStatement().getConnection() returns the logical handle.
…dle guards

- Replace BigQueryPooledConnectionWrapper boilerplate with PooledConnectionInvocationHandler backed by a per-handle ReentrantReadWriteLock so close/reclaim/teardown wait for in-flight RPCs before resetting or closing.
- Wrap pooled Statement and DatabaseMetaData instances so getConnection() enforces parentHandler.checkClosed() and returns the logical handle, and retained DatabaseMetaData instances reject operations after handle close.
- Fire connectionErrorOccurred when an active or idle physical connection was closed out-of-band, isolate listener RuntimeExceptions, execute abort(Executor) teardown asynchronously, populate SQLClientInfoException failedProperties, and use method-scoped MDC preserving outer caller context.
…eckout in PooledConnectionDataSource

- Open a dedicated physical BigQueryConnection on cache misses and recycle idle physical connections into fresh BigQueryPooledConnection holders while retiring prior holders.
- Separate PooledConnectionDataSource's internal pool listener from public ConnectionEventListener slots, make external listener detachment sticky across removeConnectionEventListener -> close(), and preserve overflow teardown for standalone PooledConnectionListener instances.
- Use LIFO (addFirst/pollFirst) idle reuse in PooledConnectionListener, close excess driver-owned idle connections at capacity, and clarify ConnectionPoolSize and ListenerPoolSize in docs/USER_GUIDE.md.
@keshavdandeva
keshavdandeva force-pushed the fix/jdbc-pooling-1-connection-reset branch from 41da6f5 to 2064902 Compare November 27, 2026 17:06
@keshavdandeva keshavdandeva changed the title fix(bigquery-jdbc): add connection state reset hook and async abort support fix(bigquery-jdbc): enforce JDBC connection pooling lifecycle, state reset, and physical isolation Nov 27, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants