Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request ensures that driver-internal database operations (such as connection validation, metadata queries, and pooled connection delegation) are not reported as user activity in usage telemetry. It introduces internal statement creation methods, tracks metadata retrieval and parameter binding to record them at most once, and improves error status reporting for Write API batch failures. Feedback from the review highlights a potential data race in BigQueryConnection.getMetaDataInternal() due to unsynchronized lazy initialization, and suggests replacing absolute local file paths in SKILL.md with relative paths.
… from tracked skills It was swept into the main merge by accident; main tracks only the shared bigquery-jdbc-testing and bigquery-jdbc-prepare-pr skills.
keshavdandeva
left a comment
There was a problem hiding this comment.
Requesting changes for a few JDBC 4.3 contract, concurrency, and error-telemetry issues (plus branch rebase/conflict resolution against main after #15211):
BigQueryPreparedStatement.executeBatch(): Rethrowing rawRuntimeException(ApiException) violates JDBCexecuteBatch()(throws SQLException) and leaks shaded GAX exceptions in-all.jar;TelemetryManager.extractErrorCodecurrently maps all StorageApiExceptions to fallback1000; andDRIVER_FEATURE_BATCH_OPERATIONSis recorded inside the try-with-resources block beforewriteClient.close().BigQueryConnection.getMetaData(): MissingcheckClosed()(violates JDBC 4.3 and records telemetry on closed connections), andsynchronized DatabaseMetaData getMetaDataInternal()locksthison every call, contending with blocking RPCs inpublic synchronized getDiscoveredProjects().- Internal statement flag &
DatabaseMetaData.getExportedKeys(): MakerecordTelemetryafinalconstructor parameter instead of mutating a non-volatilefield post-construction viamarkInternal()(which races with cross-threadStatement.cancel()and misses constructor dry-runs), and avoid exposing the unproxied internalPreparedStatementviaResultSet.getStatement()ingetExportedKeys(). - Build / Scope (
pom.xml,ITStatementTest): Consider splitting the Failsafe JVM /testScriptsizing changes into a separate PR; see inline comment on-XX:+ExitOnOutOfMemoryError,<forkCount>, and missing@{argLine}in thejava17Surefire profile.
| com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_SUCCESS); | ||
| // Success-only, matching BigQueryStatement.executeBatch; failures are already captured | ||
| // by the StatementExecution status recorded in the finally block. | ||
| recordFeature(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS); |
There was a problem hiding this comment.
In standard chunked JDBC batching (ps.addBatch() in a loop with periodic ps.executeBatch() flushes on a single PreparedStatement), DRIVER_FEATURE_PREPARED_STATEMENT and DRIVER_FEATURE_PARAMETER_BINDING now record once per statement, whereas DRIVER_FEATURE_BATCH_OPERATIONS here (and in line 490 / BigQueryStatement.executeBatchImpl) still records on every flush—and BigQueryStatement.cancel() still records DRIVER_FEATURE_STATEMENT_CANCEL on every repeated/idempotent call.
Should DRIVER_FEATURE_BATCH_OPERATIONS and DRIVER_FEATURE_STATEMENT_CANCEL also deduplicate once per Statement instance (using an AtomicBoolean for cross-thread cancel()) to match the PR title ("record adoption features once per object"), or are those intentionally per-execution counters?
There was a problem hiding this comment.
Updated DRIVER_FEATURE_STATEMENT_CANCEL to record once per Statement instance via an AtomicBoolean cancelRecorded guard in BigQueryStatement#cancel() (thread-safe across cross-thread cancel() calls and idempotent retries), and kept DRIVER_FEATURE_BATCH_OPERATIONS per-executeBatch() occurrence.
Reasoning:
DRIVER_FEATURE_STATEMENT_CANCEL(once-per-object): Repeated/idempotentcancel()calls on the sameStatement(for example, a query-timeout watchdog and application cleanup) represent a single statement cancellation, so deduplicating once per object viaAtomicBooleanmatchesConnection.getMetaData(),ResultSet.getMetaData(), andPreparedStatementparameter binding.DRIVER_FEATURE_BATCH_OPERATIONS(per-executeBatch()): In chunked JDBC batching (addBatch()in a loop with periodicexecuteBatch()flushes on a reusedPreparedStatement), eachexecuteBatch()executes a distinct BigQuery job or Storage Write API stream commit with its own dynamic batch payload/state, matchingStatementExecutionandDRIVER_FEATURE_TRANSACTIONS(per-transaction) rather than per-rowsetX()calls.
# Conflicts: # java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java # java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatement.java # java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaDataTest.java # java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatementSettersTest.java
keshavdandeva
left a comment
There was a problem hiding this comment.
Production changes and the reasoning for keeping DRIVER_FEATURE_BATCH_OPERATIONS per executeBatch() look good. Approving with a few small inline comments to address before merge or in a quick follow-up:
- Test findings (inline): Fix
.count()->.mapToLong(FeatureUsage::getCount).sum()inBigQueryConnectionTest#testGetMetaData_concurrentFirstCallsShareOneInstance(otherwise the assertion is tautological), and stubinternalStatement.isInternal()+ assertgetStatement() == nullinBigQueryJsonResultSetTest. - Minors (inline): Call
TelemetryManager.resetGlobalDisableForTest()inTelemetryTestUtils.initCapturingPayloads, and set.setErrorCode(1000)inBigQueryPreparedStatement.executeBatch'sfinallyfallback. - Nits:
- Refresh the PR description (still references
Synchronize getMetaDataInternaland-XX:+ExitOnOutOfMemoryError, and omitscheckClosed(),ResultSet.getStatement(),STATEMENT_CANCELdedup,RuntimeExceptionwrapping, andApiExceptionextraction). - Mention
ApiExceptioninTelemetryManager.extractErrorCode's Javadoc. - Move helper methods (
isRecordingTelemetry,isInternal,recordExecution,recordFeatureinBigQueryStatement;recordBindinginBigQueryParameterHandler) below fields/static {}/constructors.
- Refresh the PR description (still references
| long metadataFeatureCount = | ||
| captured.stream() | ||
| .flatMap(p -> p.getFeatureUsagesList().stream()) | ||
| .filter(e -> e.getDriverFeature() == DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL) | ||
| .count(); | ||
| assertEquals(1L, metadataFeatureCount); |
There was a problem hiding this comment.
Test bug: .count() counts FeatureUsage entries (always 1 per flush because TelemetryBatcher.FeatureAccumulator aggregates occurrences by key into FeatureUsage.count), not the total recorded count. Even if all 8 threads called recordFeatureUsage, e.getCount() would be 8 while .count() still returns 1.
Replace .count() with .mapToLong(FeatureUsage::getCount).sum() (and import FeatureUsage).
| public void testGetMetaData_recordsEvenWhenOwningStatementIsInternal() throws SQLException { | ||
| // ResultSet.getMetaData() is only ever a user call, even on result sets produced by | ||
| // driver-internal statements (e.g. DatabaseMetaData.getExportedKeys), so it must count. | ||
| BigQueryStatement internalStatement = mock(BigQueryStatement.class); |
There was a problem hiding this comment.
Test gap: An unstubbed mock(BigQueryStatement.class) returns false for isInternal(). Stub when(internalStatement.isInternal()).thenReturn(true) and assert assertNull(internalResultSet.getStatement()) so both this test and the new BigQueryBaseResultSet.getStatement() branch are covered.
| captured.add(invocation.getArgument(0)); | ||
| return new TransportResult(true, -1); | ||
| }); | ||
| TelemetryManager.init(config, transport); |
There was a problem hiding this comment.
Minor: Call TelemetryManager.resetGlobalDisableForTest() before TelemetryManager.init(config, transport). If a prior test leaves globallyDisabled == true, TelemetryManager.init() silently no-ops (TelemetryManager.java:104).
| if (writeApiExecutionBuilder.getStatus() == Status.STATUS_UNSPECIFIED) { | ||
| writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR); | ||
| } |
There was a problem hiding this comment.
Minor: Set .setErrorCode(1000) alongside Status.STATUS_ERROR so Error paths don't record errorCode = 0 (matching BigQueryStatement.runQuery(), which uses UNKNOWN_ERROR_CODE = 1000).
What & Why
BigQueryDriver.connectstartup logging,BigQueryConnection.isValidhealth checks, andBigQueryDatabaseMetaDatainternal queries through internal helpers (getMetaDataInternal,createStatementInternal,prepareStatementInternal) so driver housekeeping is not counted as user activity. SynchronizegetMetaDataInternalso threads sharing a connection initialize and see a singleDatabaseMetaDatainstance.Connection,ResultSet, orPreparedStatementrather than on every repeated call. InBigQueryPreparedStatement.executeBatch, record batch usage on success only and mark Storage Write failures (SQLException/RuntimeException) asSTATUS_ERRORinstead ofSTATUS_UNSPECIFIED.maven-failsafe-pluginJava Virtual Machine (JVM) memory (-Xmx1536m -XX:MaxDirectMemorySize=1g -XX:+ExitOnOutOfMemoryError) and reduceITStatementTest.testScriptrow counts from 500k/700k/900k to 30k/40k/50k (still above the 30k Arrow Read activation threshold) so direct-memory (memory allocated outside the Java heap) spikes fail the offending test withOutOfMemoryErrorinstead of killing the build container (exit 137).How It Was Tested
make unittest): Added tests inBigQueryConnectionTest,BigQueryDatabaseMetaDataTest,BigQueryDriverTest,BigQueryJsonResultSetTest,BigQueryPreparedStatementSettersTest, andBigQueryStatementTestcovering internal-call exclusion, once-per-object feature counts, concurrentgetMetaData(), and batch error reporting.ITStatementTest#testScriptrequires Google Cloud credentials and is verified in presubmit.Risks / Follow-ups
OutOfMemoryErrorand should be right-sized similarly.