Skip to content

fix(bigquery-jdbc): record adoption features once per object - #15044

Open
Neenu1995 wants to merge 14 commits into
mainfrom
jdbc-telemetry-updates
Open

Neenu1995 wants to merge 14 commits into
mainfrom
jdbc-telemetry-updates

Conversation

@Neenu1995

@Neenu1995 Neenu1995 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What & Why

  • Exclude driver-internal calls from usage telemetry: Route BigQueryDriver.connect startup logging, BigQueryConnection.isValid health checks, and BigQueryDatabaseMetaData internal queries through internal helpers (getMetaDataInternal, createStatementInternal, prepareStatementInternal) so driver housekeeping is not counted as user activity. Synchronize getMetaDataInternal so threads sharing a connection initialize and see a single DatabaseMetaData instance.
  • Deduplicate feature counts and fix batch error status: Record metadata retrieval and parameter binding once per Connection, ResultSet, or PreparedStatement rather than on every repeated call. In BigQueryPreparedStatement.executeBatch, record batch usage on success only and mark Storage Write failures (SQLException / RuntimeException) as STATUS_ERROR instead of STATUS_UNSPECIFIED.
  • Bound integration test memory: Cap maven-failsafe-plugin Java Virtual Machine (JVM) memory (-Xmx1536m -XX:MaxDirectMemorySize=1g -XX:+ExitOnOutOfMemoryError) and reduce ITStatementTest.testScript row 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 with OutOfMemoryError instead of killing the build container (exit 137).

How It Was Tested

  • Unit tests (make unittest): Added tests in BigQueryConnectionTest, BigQueryDatabaseMetaDataTest, BigQueryDriverTest, BigQueryJsonResultSetTest, BigQueryPreparedStatementSettersTest, and BigQueryStatementTest covering internal-call exclusion, once-per-object feature counts, concurrent getMetaData(), and batch error reporting.
  • Integration tests: ITStatementTest#testScript requires Google Cloud credentials and is verified in presubmit.

Risks / Follow-ups

  • Presubmit integration tests run in a single forked JVM; if another test exceeds the new 1.5 GB heap or 1 GB direct-memory limit, it will terminate the fork with OutOfMemoryError and should be right-sized similarly.

@Neenu1995
Neenu1995 requested review from a team as code owners November 16, 2026 21:08

@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 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.

@Neenu1995
Neenu1995 changed the base branch from main to turn-off-telemetry November 16, 2026 22:18
@Neenu1995
Neenu1995 requested review from a team as code owners November 16, 2026 22:18
@Neenu1995
Neenu1995 marked this pull request as draft November 16, 2026 22:19
@Neenu1995
Neenu1995 changed the base branch from turn-off-telemetry to main November 16, 2026 22:37
@Neenu1995
Neenu1995 changed the base branch from main to turn-off-telemetry November 16, 2026 22:38
… 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.
Base automatically changed from turn-off-telemetry to main November 17, 2026 00:48
@Neenu1995
Neenu1995 marked this pull request as ready for review November 17, 2026 15:24
@Neenu1995
Neenu1995 removed request for a team November 19, 2026 20:39

@keshavdandeva keshavdandeva 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.

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 raw RuntimeException (ApiException) violates JDBC executeBatch() (throws SQLException) and leaks shaded GAX exceptions in -all.jar; TelemetryManager.extractErrorCode currently maps all Storage ApiExceptions to fallback 1000; and DRIVER_FEATURE_BATCH_OPERATIONS is recorded inside the try-with-resources block before writeClient.close().
  • BigQueryConnection.getMetaData(): Missing checkClosed() (violates JDBC 4.3 and records telemetry on closed connections), and synchronized DatabaseMetaData getMetaDataInternal() locks this on every call, contending with blocking RPCs in public synchronized getDiscoveredProjects().
  • Internal statement flag & DatabaseMetaData.getExportedKeys(): Make recordTelemetry a final constructor parameter instead of mutating a non-volatile field post-construction via markInternal() (which races with cross-thread Statement.cancel() and misses constructor dry-runs), and avoid exposing the unproxied internal PreparedStatement via ResultSet.getStatement() in getExportedKeys().
  • Build / Scope (pom.xml, ITStatementTest): Consider splitting the Failsafe JVM / testScript sizing changes into a separate PR; see inline comment on -XX:+ExitOnOutOfMemoryError, <forkCount>, and missing @{argLine} in the java17 Surefire 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);

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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/idempotent cancel() calls on the same Statement (for example, a query-timeout watchdog and application cleanup) represent a single statement cancellation, so deduplicating once per object via AtomicBoolean matches Connection.getMetaData(), ResultSet.getMetaData(), and PreparedStatement parameter binding.
  • DRIVER_FEATURE_BATCH_OPERATIONS (per-executeBatch()): In chunked JDBC batching (addBatch() in a loop with periodic executeBatch() flushes on a reused PreparedStatement), each executeBatch() executes a distinct BigQuery job or Storage Write API stream commit with its own dynamic batch payload/state, matching StatementExecution and DRIVER_FEATURE_TRANSACTIONS (per-transaction) rather than per-row setX() calls.

Comment thread java-bigquery-jdbc/pom.xml Resolved
# 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 keshavdandeva 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.

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() in BigQueryConnectionTest#testGetMetaData_concurrentFirstCallsShareOneInstance (otherwise the assertion is tautological), and stub internalStatement.isInternal() + assert getStatement() == null in BigQueryJsonResultSetTest.
  • Minors (inline): Call TelemetryManager.resetGlobalDisableForTest() in TelemetryTestUtils.initCapturingPayloads, and set .setErrorCode(1000) in BigQueryPreparedStatement.executeBatch's finally fallback.
  • Nits:
    • Refresh the PR description (still references Synchronize getMetaDataInternal and -XX:+ExitOnOutOfMemoryError, and omits checkClosed(), ResultSet.getStatement(), STATEMENT_CANCEL dedup, RuntimeException wrapping, and ApiException extraction).
    • Mention ApiException in TelemetryManager.extractErrorCode's Javadoc.
    • Move helper methods (isRecordingTelemetry, isInternal, recordExecution, recordFeature in BigQueryStatement; recordBinding in BigQueryParameterHandler) below fields/static {}/constructors.

Comment on lines +1330 to +1335
long metadataFeatureCount =
captured.stream()
.flatMap(p -> p.getFeatureUsagesList().stream())
.filter(e -> e.getDriverFeature() == DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL)
.count();
assertEquals(1L, metadataFeatureCount);

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.

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);

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.

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);

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.

Minor: Call TelemetryManager.resetGlobalDisableForTest() before TelemetryManager.init(config, transport). If a prior test leaves globallyDisabled == true, TelemetryManager.init() silently no-ops (TelemetryManager.java:104).

Comment on lines +471 to +473
if (writeApiExecutionBuilder.getStatus() == Status.STATUS_UNSPECIFIED) {
writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR);
}

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.

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).

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