From b9516db2ec3dba772a5557fffda9a3f7a9b158b1 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:02:40 +0000 Subject: [PATCH 01/13] fix(bigquery-jdbc): initialize or suppress Clearcut telemetry in BigQueryConnection after credential resolution --- .../java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java | 1 + 1 file changed, 1 insertion(+) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java index 702b3c690df9..484a6990fdad 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java @@ -420,6 +420,7 @@ static String maskPropertyValue(String key, Object value) { this.reqGoogleDriveScope, httpTransportFactory, this.connectionClassName); + BigQueryJdbcDiagnosticTelemetry.initializeOrDisable(ds, this.credentials); this.defaultDataset = BigQueryJdbcUrlUtility.parseDefaultDataset(ds.getDefaultDataset()); this.location = ds.getLocation(); this.enableHighThroughputAPI = ds.getEnableHighThroughputAPI(); From 328bc607c2f2634d807a134341523ed67d862180 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:04:15 +0000 Subject: [PATCH 02/13] feat(bigquery-jdbc): add last-wins raw URI property parser helper --- .../bigquery/jdbc/BigQueryJdbcUrlUtility.java | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java index 6c34cddfec06..832cdd3ba273 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java @@ -768,9 +768,23 @@ static String parseUriProperty(String uri, String property) { * @return The String value of the property, or null if the property is not found. */ static String parseUriPropertyWithoutValidation(String uri, String property) { + return parseUriPropertyWithoutValidation(uri, property, false); + } + + /** + * Parses the last matching value for {@code property} from the URI without validating other + * properties, matching last-wins precedence when {@link Properties} are appended to the URL. + */ + static String parseLastUriPropertyWithoutValidation(String uri, String property) { + return parseUriPropertyWithoutValidation(uri, property, true); + } + + private static String parseUriPropertyWithoutValidation( + String uri, String property, boolean lastWins) { if (uri == null) { return null; } + String rawMatchedValue = null; int start = 0; int len = uri.length(); while (start < len) { @@ -781,14 +795,19 @@ static String parseUriPropertyWithoutValidation(String uri, String property) { if (eqIndex > start && eqIndex < end) { String key = uri.substring(start, eqIndex).trim(); if (key.equalsIgnoreCase(property)) { - String value = uri.substring(eqIndex + 1, end); - return CharEscapers.decodeUriPath(value.replace("+", "%2B")); + rawMatchedValue = uri.substring(eqIndex + 1, end); + if (!lastWins) { + return CharEscapers.decodeUriPath(rawMatchedValue.replace("+", "%2B")); + } } } start = end + 1; } - return null; + if (rawMatchedValue == null) { + return null; + } + return CharEscapers.decodeUriPath(rawMatchedValue.replace("+", "%2B")); } /** From fdcca6991be41b0339e2f62bbde43a3084851f1a Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:05:31 +0000 Subject: [PATCH 03/13] fix(bigquery-jdbc): suppress Clearcut telemetry for custom universes and endpoint overrides --- .../cloud/bigquery/jdbc/BigQueryDriver.java | 21 +- .../jdbc/BigQueryJdbcDiagnosticTelemetry.java | 187 ++++++++++++++++++ .../telemetry/v1/TelemetryConfiguration.java | 10 + .../jdbc/telemetry/v1/TelemetryManager.java | 33 +++- 4 files changed, 233 insertions(+), 18 deletions(-) create mode 100644 java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetry.java diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index 561cc75d918b..9e4a17d76374 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -130,25 +130,17 @@ public static BigQueryDriver getRegisteredDriver() throws IllegalStateException public Connection connect(String url, Properties info) throws SQLException { LOG.finest("++enter++"); AuthenticationType authType = AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED; + String connectionUri = null; + DataSource ds = null; try { if (acceptsURL(url)) { Properties connectInfo = info == null ? new Properties() : (Properties) info.clone(); Object customOpenTelemetryObj = connectInfo.remove("customOpenTelemetry"); - String connectionUri = + connectionUri = BigQueryJdbcUrlUtility.appendPropertiesToURL( url.substring(5), this.toString(), connectInfo); - String telemetryOptOut = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME); - - if (telemetryOptOut != null) { - connectInfo.setProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, telemetryOptOut); - } - TelemetryManager.getInstance(connectInfo); - Level logLevel; String logPath; boolean ignoredUrlLogPath; @@ -199,7 +191,6 @@ public Connection connect(String url, Properties info) throws SQLException { BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY); } - DataSource ds; try { ds = DataSource.fromUrl(connectionUri); } catch (BigQueryJdbcRuntimeException e) { @@ -240,12 +231,10 @@ public Connection connect(String url, Properties info) throws SQLException { return null; } } catch (IOException e) { - TelemetryManager.recordConnectionAttempt( - Status.STATUS_ERROR, TelemetryManager.extractErrorCode(e), authType); + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection(connectionUri, ds, authType, e); throw new BigQueryJdbcException("Failed to establish connection", e); } catch (Throwable t) { - TelemetryManager.recordConnectionAttempt( - Status.STATUS_ERROR, TelemetryManager.extractErrorCode(t), authType); + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection(connectionUri, ds, authType, t); throw t; } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetry.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetry.java new file mode 100644 index 000000000000..06961e9e3a4d --- /dev/null +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetry.java @@ -0,0 +1,187 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.bigquery.jdbc; + +import com.google.auth.Credentials; +import com.google.auth.oauth2.ComputeEngineCredentials; +import com.google.auth.oauth2.ImpersonatedCredentials; +import com.google.cloud.bigquery.jdbc.telemetry.v1.AuthenticationType; +import com.google.cloud.bigquery.jdbc.telemetry.v1.Status; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import java.io.IOException; + +/** + * Coordinates Clearcut diagnostic telemetry eligibility and lifecycle transitions for BigQuery JDBC + * connections. + */ +final class BigQueryJdbcDiagnosticTelemetry { + + private BigQueryJdbcDiagnosticTelemetry() {} + + /** + * Initializes Clearcut diagnostic telemetry for an eligible connection, or permanently disables + * it if the connection opts out or targets a non-default universe or endpoint override. + */ + static void initializeOrDisable(DataSource ds, Credentials credentials) { + if (TelemetryManager.isGloballyDisabled()) { + return; + } + TelemetryManager.runSafely( + () -> { + if (isSuppressed(ds, credentials)) { + TelemetryManager.disableGlobally("non-default universe or endpoint override"); + return; + } + TelemetryManager.initializeForConnection(ds.getEnableDiagnosticTelemetry()); + }); + } + + /** + * Enforces suppression and opt-out rules on failed {@link BigQueryDriver#connect} calls and + * records a failed connection attempt when diagnostic telemetry is eligible. + */ + static void recordFailedConnection( + String connectionUri, DataSource ds, AuthenticationType authType, Throwable failure) { + if (connectionUri == null || TelemetryManager.isGloballyDisabled()) { + return; + } + TelemetryManager.runSafely( + () -> { + TelemetryManager manager = + ds != null + ? initializeOrDisableForFailedDataSource(ds) + : initializeOrDisableFromRawUri(connectionUri); + if (manager != null) { + TelemetryManager.recordConnectionAttempt( + Status.STATUS_ERROR, TelemetryManager.extractErrorCode(failure), authType); + } + }); + } + + private static TelemetryManager initializeOrDisableForFailedDataSource(DataSource ds) { + if (isSuppressed(ds, null)) { + TelemetryManager.disableGlobally("non-default universe or endpoint override"); + return null; + } + return TelemetryManager.initializeForConnection(ds.getEnableDiagnosticTelemetry()); + } + + private static TelemetryManager initializeOrDisableFromRawUri(String connectionUri) { + if (isSuppressedFromRawUri(connectionUri)) { + TelemetryManager.disableGlobally("non-default universe or endpoint override"); + return null; + } + String rawEnable; + try { + rawEnable = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME); + } catch (RuntimeException e) { + TelemetryManager.disableGlobally("malformed EnableDiagnosticTelemetry value"); + return null; + } + Boolean explicitEnabled = null; + if (rawEnable != null && !rawEnable.trim().isEmpty()) { + explicitEnabled = parseStrictBoolean(rawEnable); + if (explicitEnabled == null) { + TelemetryManager.disableGlobally("invalid EnableDiagnosticTelemetry value"); + return null; + } + } + return TelemetryManager.initializeForConnection(explicitEnabled); + } + + private static Boolean parseStrictBoolean(String rawValue) { + String trimmed = rawValue.trim(); + if ("true".equalsIgnoreCase(trimmed) || "1".equals(trimmed)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(trimmed) || "0".equals(trimmed)) { + return Boolean.FALSE; + } + return null; + } + + static boolean isSuppressed(DataSource ds, Credentials credentials) { + if (isNonBlank(ds.getEndpointOverrides()) || isNonBlank(ds.getPrivateServiceConnect())) { + return true; + } + if (isNonDefaultUniverse(ds.resolveUniverseDomain())) { + return true; + } + return isNonDefaultCredentialUniverse(credentials); + } + + private static boolean isSuppressedFromRawUri(String connectionUri) { + try { + String endpointOverrides = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME); + if (isNonBlank(endpointOverrides)) { + return true; + } + String privateServiceConnect = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME); + if (isNonBlank(privateServiceConnect)) { + return true; + } + String rawUniverse = + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + connectionUri, BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME); + String explicitUniverse = BigQueryJdbcUrlUtility.normalizeUniverseDomain(rawUniverse); + String resolvedUniverse = + explicitUniverse != null + ? explicitUniverse + : BigQueryJdbcUrlUtility.getEnvUniverseDomain(); + return isNonDefaultUniverse(resolvedUniverse); + } catch (RuntimeException e) { + return true; + } + } + + static boolean isNonDefaultCredentialUniverse(Credentials credentials) { + if (credentials == null || isComputeEngineBacked(credentials)) { + return false; + } + try { + return isNonDefaultUniverse(credentials.getUniverseDomain()); + } catch (IOException e) { + return true; + } + } + + private static boolean isComputeEngineBacked(Credentials credentials) { + Credentials current = credentials; + while (current instanceof ImpersonatedCredentials) { + current = ((ImpersonatedCredentials) current).getSourceCredentials(); + } + return current instanceof ComputeEngineCredentials; + } + + private static boolean isNonDefaultUniverse(String universeDomain) { + if (!isNonBlank(universeDomain)) { + return false; + } + return !BigQueryJdbcUrlUtility.DEFAULT_UNIVERSE_DOMAIN_VALUE.equalsIgnoreCase( + universeDomain.trim()); + } + + private static boolean isNonBlank(String value) { + return value != null && !value.trim().isEmpty(); + } +} diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryConfiguration.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryConfiguration.java index 6a58ec1d49c3..622be6a2de5d 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryConfiguration.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryConfiguration.java @@ -172,7 +172,17 @@ Builder resolveProperties(Properties connectionProperties) { String enableStr = connectionProperties.getProperty("EnableDiagnosticTelemetry"); this.enabled = TelemetryPropertyUtility.convertStringToBoolean(enableStr, this.enabled); } + return applyGlobalOverrides(); + } + + Builder resolveEnabled(Boolean explicitEnabled) { + if (explicitEnabled != null) { + this.enabled = explicitEnabled; + } + return applyGlobalOverrides(); + } + private Builder applyGlobalOverrides() { // 2. Environment Variables (overrides connection properties) try { String envEnabled = System.getenv("BIGQUERY_JDBC_TELEMETRY_ENABLED"); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java index 6c9999e2830d..af674acd856a 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java @@ -16,6 +16,7 @@ package com.google.cloud.bigquery.jdbc.telemetry.v1; +import com.google.api.core.InternalApi; import com.google.api.gax.rpc.ApiException; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.JobStatistics.QueryStatistics; @@ -60,9 +61,26 @@ public static TelemetryManager getInstance(Properties properties) { if (globallyDisabled) { return null; } - TelemetryConfiguration preliminaryConfig = TelemetryConfiguration.builder().resolveProperties(properties).build(); + return initializeWithConfig(preliminaryConfig); + } + + /** + * Initializes or returns the shared {@link TelemetryManager} instance using a typed connection + * opt-out flag, or permanently disables diagnostic telemetry for the JVM when disabled. + */ + @InternalApi + public static TelemetryManager initializeForConnection(Boolean enabledOverride) { + if (globallyDisabled) { + return null; + } + TelemetryConfiguration preliminaryConfig = + TelemetryConfiguration.builder().resolveEnabled(enabledOverride).build(); + return initializeWithConfig(preliminaryConfig); + } + + private static TelemetryManager initializeWithConfig(TelemetryConfiguration preliminaryConfig) { if (!preliminaryConfig.isEnabled()) { disableGlobally("opt-out configuration"); return null; @@ -103,7 +121,18 @@ public static TelemetryManager getInstance(Properties properties) { return active; } - static void disableGlobally(String reason) { + /** Returns {@code true} if diagnostic telemetry has been permanently disabled for this JVM. */ + @InternalApi + public static boolean isGloballyDisabled() { + return globallyDisabled; + } + + /** + * Permanently disables diagnostic telemetry for this JVM and closes any active instance without + * flushing buffered metrics. + */ + @InternalApi + public static void disableGlobally(String reason) { TelemetryManager localRef; boolean newlyDisabled; synchronized (TelemetryManager.class) { From af833f3f48828eb1b488cee57468a10bb5255ae3 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:07:21 +0000 Subject: [PATCH 04/13] test(bigquery-jdbc): reset diagnostic telemetry in BigQueryPooledConnectionTest tearDown --- .../cloud/bigquery/jdbc/BigQueryPooledConnectionTest.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnectionTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnectionTest.java index 42665be737f2..a49b5c83dfe9 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnectionTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnectionTest.java @@ -49,6 +49,7 @@ import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryTestUtils; import com.google.cloud.bigquery.jdbc.utils.URIBuilder; import java.io.IOException; import java.lang.reflect.Proxy; @@ -80,6 +81,7 @@ import java.util.concurrent.locks.LockSupport; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -102,6 +104,11 @@ public void setUp() throws IOException, SQLException { doReturn(LISTENER_POOL_SIZE).when(bigQueryConnection).getListenerPoolSize(); } + @AfterEach + public void resetDiagnosticTelemetry() { + TelemetryTestUtils.reset(); + } + @Test public void testGetPooledConnection() throws SQLException { BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); From b4ab71d468e94e189c7698a748368371b0d81110 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:08:37 +0000 Subject: [PATCH 05/13] test(bigquery-jdbc): reset diagnostic telemetry in PerConnectionFileHandlerTest tearDown --- .../cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java index df5184be419f..04bd079d8431 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java @@ -29,6 +29,7 @@ import com.google.cloud.bigquery.FieldList; import com.google.cloud.bigquery.Schema; import com.google.cloud.bigquery.StandardSQLTypeName; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryTestUtils; import com.google.cloud.bigquery.jdbc.utils.TestUtilities; import com.google.cloud.bigquery.jdbc.utils.URIBuilder; import java.io.IOException; @@ -90,6 +91,7 @@ public void tearDown() { } BigQueryJdbcMdc.clear(); BigQueryJdbcRootLogger.getRootLogger().setLevel(originalLevel); + TelemetryTestUtils.reset(); } private Optional findLogFile(String suffix) throws IOException { From 3bf1bfc94daaaf55bb05344ef44b0614ac2c22a5 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:09:16 +0000 Subject: [PATCH 06/13] test(bigquery-jdbc): reset diagnostic telemetry in PerConnectionFileHandlerTest tearDown From 1b6f91d11b828a128670f2c75f104dfd42aeab66 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:09:48 +0000 Subject: [PATCH 07/13] test(bigquery-jdbc): cover Clearcut suppression across universes, overrides, credentials, and failures --- .../bigquery/jdbc/BigQueryDriverTest.java | 199 ++++++++++++++++ .../bigquery/jdbc/BigQueryJdbcBaseTest.java | 23 ++ .../BigQueryJdbcDiagnosticTelemetryTest.java | 224 ++++++++++++++++++ 3 files changed, 446 insertions(+) create mode 100644 java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetryTest.java diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java index 34d25b7f0cda..783d077846c6 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java @@ -30,16 +30,21 @@ import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; import com.google.cloud.bigquery.jdbc.telemetry.v1.Status; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryPayload; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryTestUtils; import com.google.cloud.bigquery.jdbc.utils.BigQueryJdbcVersionUtility; import io.opentelemetry.api.OpenTelemetry; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverPropertyInfo; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; @@ -49,6 +54,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.MockedStatic; public class BigQueryDriverTest extends BigQueryJdbcLoggingBaseTest { @@ -429,4 +436,196 @@ public void testDataSource_urlOptOutNotClobberedByDefaultDataSource() throws SQL } assertThat(TelemetryManager.isInitialized()).isFalse(); } + + @ParameterizedTest + @CsvSource({ + "universeDomain, " + CUSTOM_UNIVERSE_DOMAIN, + "EndpointOverrides, BIGQUERY=https://override.example.com", + "PrivateServiceConnectUris, BIGQUERY=https://psc.example.com" + }) + public void testConnect_suppressesClearcutForUrlPropertyOnSuccessAndFailure( + String propertyName, String propertyValue) throws SQLException { + String successUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append(propertyName, propertyValue) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + try (Connection conn = bigQueryDriver.connect(successUrl, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + + TelemetryTestUtils.reset(); + String failedUrl = + getBaseUri() + .append("OAuthType", "invalid") + .append(propertyName, propertyValue) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + Assertions.assertThrows( + Exception.class, () -> bigQueryDriver.connect(failedUrl, new Properties())); + assertTelemetryDisabled(); + } + + @Test + public void testDataSource_suppressesClearcutForCustomUniverseSetter() throws SQLException { + DataSource ds = new DataSource(); + ds.setURL( + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("EnableDiagnosticTelemetry", 1) + .toString()); + ds.setUniverseDomain(CUSTOM_UNIVERSE_DOMAIN); + + try (Connection conn = ds.getConnection()) { + assertThat(conn.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + } + + @Test + public void testConnect_customUniverseServiceAccountKeySuppressesOnSuccessAndPostCredentialFail( + @TempDir Path tempDir) throws Exception { + Path keyFile = writeServiceAccountJson(tempDir, CUSTOM_UNIVERSE_DOMAIN); + String url = + getBaseUri(0, "test-project") + .append("OAuthPvtKeyPath", keyFile.toAbsolutePath().toString()) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + + try (Connection conn = bigQueryDriver.connect(url, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + + // Post-credential failure still suppresses before driver catch block runs + TelemetryTestUtils.reset(); + String failingPostCredUrl = + getBaseUri(0, "test-project") + .append("OAuthPvtKeyPath", keyFile.toAbsolutePath().toString()) + .append("EnableDiagnosticTelemetry", 1) + .append("DefaultDataset", "invalid:") + .toString(); + Assertions.assertThrows( + Exception.class, () -> bigQueryDriver.connect(failingPostCredUrl, new Properties())); + assertTelemetryDisabled(); + + // Direct BigQueryConnection disables an already-active commercial manager + TelemetryTestUtils.reset(); + try (Connection commercial = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + try (BigQueryConnection direct = new BigQueryConnection(url)) { + assertThat(direct.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + } + + @Test + public void testConnect_preCredentialFailureFollowedByCustomUniverseKeyDropsQueuedBatch( + @TempDir Path tempDir) throws Exception { + List captured = Collections.synchronizedList(new ArrayList<>()); + TelemetryTestUtils.initCapturingPayloads(captured); + + // Pre-credential failure queues a failed connection attempt on the active batcher + String missingKeyUrl = getBaseUri(0, "test-project").toString(); + try (MockedStatic telemetry = + mockStatic(TelemetryManager.class, CALLS_REAL_METHODS)) { + Assertions.assertThrows( + Exception.class, () -> bigQueryDriver.connect(missingKeyUrl, new Properties())); + telemetry.verify( + () -> + TelemetryManager.recordConnectionAttempt( + eq(Status.STATUS_ERROR), + anyInt(), + eq(AuthenticationType.AUTHENTICATION_TYPE_SERVICE_ACCOUNT))); + } + + // Subsequent connect with custom-universe key disables globally and drops buffered events + Path keyFile = writeServiceAccountJson(tempDir, CUSTOM_UNIVERSE_DOMAIN); + String customSaUrl = + getBaseUri(0, "test-project") + .append("OAuthPvtKeyPath", keyFile.toAbsolutePath().toString()) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + try (Connection conn = bigQueryDriver.connect(customSaUrl, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + assertThat(captured).isEmpty(); + } + + @Test + public void testConnect_activeCommercialTelemetryDisabledBySubsequentSuppressedConnection() + throws SQLException { + try (Connection commercial = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + + String suppressedUrl = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("universeDomain", CUSTOM_UNIVERSE_DOMAIN) + .append("EnableDiagnosticTelemetry", 1) + .toString(); + try (Connection nonDefault = bigQueryDriver.connect(suppressedUrl, new Properties())) { + assertThat(nonDefault.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + + // Global kill switch remains latched for subsequent commercial connections + try (Connection commercialAgain = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { + assertThat(commercialAgain.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + } + + @Test + public void testConnect_enableDiagnosticTelemetryPropertiesOverrideUrl() throws SQLException { + // URL=1 overridden by Properties=0 -> disabled + String urlEnabled = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + Properties disableProps = new Properties(); + disableProps.setProperty("EnableDiagnosticTelemetry", "0"); + try (Connection conn = bigQueryDriver.connect(urlEnabled, disableProps)) { + assertThat(conn.isClosed()).isFalse(); + } + assertTelemetryDisabled(); + + // URL=0 overridden by Properties=1 -> enabled (consistent with DataSource last-wins) + TelemetryTestUtils.reset(); + String urlDisabled = + getUriOAuthToken() + .append("ProjectId", "MyBigQueryProject") + .append("EnableDiagnosticTelemetry", 0) + .toString(); + Properties enableProps = new Properties(); + enableProps.setProperty("EnableDiagnosticTelemetry", "1"); + try (Connection conn = bigQueryDriver.connect(urlDisabled, enableProps)) { + assertThat(conn.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + + @Test + public void testConnect_nullUrlDoesNotInitializeTelemetry() { + Assertions.assertThrows(BigQueryJdbcException.class, () -> bigQueryDriver.connect(null, null)); + assertThat(TelemetryManager.isInitialized()).isFalse(); + } + + private static void assertTelemetryDisabled() { + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + private static Path writeServiceAccountJson(Path dir, String universeDomain) throws IOException { + Path file = dir.resolve("sa-" + universeDomain + ".json"); + Files.write( + file, serviceAccountJson(universeDomain).toString().getBytes(StandardCharsets.UTF_8)); + return file; + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java index 24a7f6afee83..66003e92b7f0 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java @@ -18,14 +18,24 @@ import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryTestUtils; import com.google.cloud.bigquery.jdbc.utils.TestUtilities; import com.google.cloud.bigquery.jdbc.utils.URIBuilder; +import com.google.gson.JsonObject; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; +import org.junit.jupiter.api.AfterEach; public class BigQueryJdbcBaseTest { + protected static final String CUSTOM_UNIVERSE_DOMAIN = "custom-universe.example.com"; + + @AfterEach + public void resetDiagnosticTelemetry() { + TelemetryTestUtils.reset(); + } + // This is a fake pkcs8 key generated specifically for unittests protected static final String fake_pkcs8_key = "-----BEGIN PRIVATE KEY-----\n" @@ -101,4 +111,17 @@ protected static URIBuilder getUriOAuthApplicationDefault() { protected static URIBuilder getUriOAuthExternal() { return getBaseUri().append("OAuthType", 4).append("OAuthPvtKey", fake_pkcs8_key); } + + protected static JsonObject serviceAccountJson(String universeDomain) { + JsonObject saJson = new JsonObject(); + saJson.addProperty("type", "service_account"); + saJson.addProperty("project_id", "test-project"); + saJson.addProperty("private_key_id", "test-key-id"); + saJson.addProperty("private_key", fake_pkcs8_key); + saJson.addProperty("client_email", "test-sa@test-project.iam.gserviceaccount.com"); + saJson.addProperty("client_id", "123456789"); + saJson.addProperty("token_uri", "https://oauth2." + universeDomain + "/token"); + saJson.addProperty("universe_domain", universeDomain); + return saJson; + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetryTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetryTest.java new file mode 100644 index 000000000000..24ed6429aadd --- /dev/null +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcDiagnosticTelemetryTest.java @@ -0,0 +1,224 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.bigquery.jdbc; + +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mockStatic; + +import com.google.auth.Credentials; +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.ComputeEngineCredentials; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.oauth2.ImpersonatedCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; +import com.google.cloud.bigquery.jdbc.telemetry.v1.AuthenticationType; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryTestUtils; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.MockedStatic; + +public class BigQueryJdbcDiagnosticTelemetryTest extends BigQueryJdbcBaseTest { + + private static final String DEFAULT_UNIVERSE = "googleapis.com"; + private static final String RAW_URI_PREFIX = + "bigquery://https://www.googleapis.com/bigquery/v2:443"; + + @BeforeEach + public void resetBeforeTest() { + TelemetryTestUtils.reset(); + } + + @Test + public void testIsSuppressed_nonDefaultUniverseAndOverridesAndPsc() { + DataSource defaultDs = new DataSource(); + defaultDs.setUniverseDomain(DEFAULT_UNIVERSE); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(defaultDs, null)).isFalse(); + + DataSource customUniverseDs = new DataSource(); + customUniverseDs.setUniverseDomain(CUSTOM_UNIVERSE_DOMAIN); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(customUniverseDs, null)).isTrue(); + + DataSource endpointOverrideDs = new DataSource(); + endpointOverrideDs.setEndpointOverrides("BIGQUERY=https://override.example.com"); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(endpointOverrideDs, null)).isTrue(); + + DataSource pscDs = new DataSource(); + pscDs.setPrivateServiceConnect("BIGQUERY=https://psc.example.com"); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(pscDs, null)).isTrue(); + + DataSource blankOverridesDs = new DataSource(); + blankOverridesDs.setUniverseDomain(" GOOGLEAPIS.COM "); + blankOverridesDs.setEndpointOverrides(" "); + blankOverridesDs.setPrivateServiceConnect(""); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(blankOverridesDs, null)).isFalse(); + } + + @Test + public void testIsSuppressed_envUniverseDomainPrecedence() { + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + urlUtil.when(BigQueryJdbcUrlUtility::getEnvUniverseDomain).thenReturn(CUSTOM_UNIVERSE_DOMAIN); + + // Omitted explicit universe inherits non-default env universe -> suppressed + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(new DataSource(), null)).isTrue(); + + // Explicit googleapis.com overrides non-default env universe -> not suppressed + DataSource explicitDefault = new DataSource(); + explicitDefault.setUniverseDomain(DEFAULT_UNIVERSE); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(explicitDefault, null)).isFalse(); + + // Blank/null env universe behaves as default -> not suppressed + urlUtil.when(BigQueryJdbcUrlUtility::getEnvUniverseDomain).thenReturn(null); + assertThat(BigQueryJdbcDiagnosticTelemetry.isSuppressed(new DataSource(), null)).isFalse(); + } + } + + @Test + public void testIsNonDefaultCredentialUniverse_allCredentialTypes() throws Exception { + assertThat(BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(null)).isFalse(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + GoogleCredentials.create(new AccessToken("token", null)))) + .isFalse(); + + ServiceAccountCredentials defaultSa = buildServiceAccountCredentials(DEFAULT_UNIVERSE); + assertThat(BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(defaultSa)).isFalse(); + + ServiceAccountCredentials customSa = buildServiceAccountCredentials(CUSTOM_UNIVERSE_DOMAIN); + assertThat(BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(customSa)).isTrue(); + + ComputeEngineCredentials computeCreds = ComputeEngineCredentials.create(); + assertThat(BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(computeCreds)) + .isFalse(); + + ImpersonatedCredentials impersonatedFromCompute = + ImpersonatedCredentials.newBuilder() + .setSourceCredentials(computeCreds) + .setTargetPrincipal("target@test-project.iam.gserviceaccount.com") + .setScopes(Collections.singletonList("https://www.googleapis.com/auth/bigquery")) + .build(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse(impersonatedFromCompute)) + .isFalse(); + + ImpersonatedCredentials impersonatedFromCustomSa = + ImpersonatedCredentials.newBuilder() + .setSourceCredentials(customSa) + .setTargetPrincipal("target@test-project.iam.gserviceaccount.com") + .setScopes(Collections.singletonList("https://www.googleapis.com/auth/bigquery")) + .build(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + impersonatedFromCustomSa)) + .isTrue(); + + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + stubCredentials(() -> null))) + .isFalse(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + stubCredentials(() -> " "))) + .isFalse(); + assertThat( + BigQueryJdbcDiagnosticTelemetry.isNonDefaultCredentialUniverse( + stubCredentials( + () -> { + throw new IOException("simulated lookup error"); + }))) + .isTrue(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "EnableDiagnosticTelemetry=0;", + "EnableDiagnosticTelemetry=no;", + "EnableDiagnosticTelemetry=bad%escape;", + "universeDomain=" + CUSTOM_UNIVERSE_DOMAIN + ";", + "universeDomain=bad%escape;", + "EndpointOverrides=https://bad%escape.example.com;", + "PrivateServiceConnectUris=https://bad%escape.example.com;" + }) + public void testRecordFailedConnection_rawUriSuppressionAndInvalidOptOutDisablesActiveManager( + String rawSuffix) { + assertThat(TelemetryManager.getInstance()).isNotNull(); + assertThat(TelemetryManager.isInitialized()).isTrue(); + + String rawUri = RAW_URI_PREFIX + ";" + rawSuffix; + BigQueryJdbcDiagnosticTelemetry.recordFailedConnection( + rawUri, null, AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED, new RuntimeException()); + + assertThat(TelemetryManager.isInitialized()).isFalse(); + assertThat(TelemetryManager.isGloballyDisabled()).isTrue(); + } + + private static ServiceAccountCredentials buildServiceAccountCredentials(String universeDomain) + throws IOException { + return ServiceAccountCredentials.fromStream( + new ByteArrayInputStream( + serviceAccountJson(universeDomain).toString().getBytes(StandardCharsets.UTF_8))); + } + + @FunctionalInterface + private interface UniverseSupplier { + String get() throws IOException; + } + + private static Credentials stubCredentials(UniverseSupplier universeSupplier) { + return new Credentials() { + @Override + public String getAuthenticationType() { + return "test"; + } + + @Override + public Map> getRequestMetadata(URI uri) { + return Collections.emptyMap(); + } + + @Override + public boolean hasRequestMetadata() { + return false; + } + + @Override + public boolean hasRequestMetadataOnly() { + return false; + } + + @Override + public void refresh() {} + + @Override + public String getUniverseDomain() throws IOException { + return universeSupplier.get(); + } + }; + } +} From f80ac974ded70c9f3fa002a941c682f0e70a8cce Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:10:48 +0000 Subject: [PATCH 08/13] test(bigquery-jdbc): verify Clearcut suppression across URL, DataSource, env, and credential universes From 3276fa00317c9ffdd884a88920eef4cf19630926 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:11:06 +0000 Subject: [PATCH 09/13] test(bigquery-jdbc): reset diagnostic telemetry in PerConnectionFileHandlerTest tearDown From 09939454375506685816717365ed05f600086d06 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:12:21 +0000 Subject: [PATCH 10/13] test(bigquery-jdbc): reset diagnostic telemetry in PerConnectionFileHandlerTest tearDown From fa6b0122b04beacbb67d75dd71b8250cf92e976f Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:12:28 +0000 Subject: [PATCH 11/13] test(bigquery-jdbc): verify Clearcut suppression for custom universes, endpoint overrides, and credential realms From 25fccad54204413940ce29c4caa3b61820382aef Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Wed, 2 Dec 2026 18:14:43 +0000 Subject: [PATCH 12/13] test(bigquery-jdbc): cover raw last-wins URI parser and typed TelemetryManager entry point --- .../jdbc/BigQueryJdbcUrlUtilityTest.java | 20 +++++++++++++++++++ .../telemetry/v1/TelemetryManagerTest.java | 14 +++++++++++++ 2 files changed, 34 insertions(+) diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java index 55548c302756..2e7e59839fc4 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java @@ -402,6 +402,26 @@ public void testParseDiagnosticTelemetryProperties() { .isEqualTo("true"); } + @Test + public void testParseLastUriPropertyWithoutValidation_returnsLastMatchingValue() { + String uri = + "bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "EnableDiagnosticTelemetry=1;universeDomain=googleapis.com;" + + "enablediagnostictelemetry=0;UNIVERSEDOMAIN=" + + CUSTOM_UNIVERSE_DOMAIN; + + assertThat( + BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation( + uri, "EnableDiagnosticTelemetry")) + .isEqualTo("0"); + assertThat(BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(uri, "universeDomain")) + .isEqualTo(CUSTOM_UNIVERSE_DOMAIN); + assertThat(BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(uri, "Absent")) + .isNull(); + assertThat(BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(null, "universeDomain")) + .isNull(); + } + @Test public void testEnableGraphMetadataProperties() { String url = diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManagerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManagerTest.java index 35da1c657e3a..de9d66b2251b 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManagerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManagerTest.java @@ -290,7 +290,21 @@ public LowLevelHttpRequest buildRequest(String method, String url) { assertNull(TelemetryManager.getInstance(optOut)); assertFalse(TelemetryManager.isInitialized()); + assertTrue(TelemetryManager.isGloballyDisabled()); assertEquals(0, requestCount.get()); assertNull(TelemetryManager.getInstance()); } + + @Test + public void testInitializeForConnection_respectsTypedBooleanAndDisableGlobally() { + TelemetryManager active = TelemetryManager.initializeForConnection(Boolean.TRUE); + assertNotNull(active); + assertSame(active, TelemetryManager.initializeForConnection(null)); + assertFalse(TelemetryManager.isGloballyDisabled()); + + assertNull(TelemetryManager.initializeForConnection(Boolean.FALSE)); + assertFalse(TelemetryManager.isInitialized()); + assertTrue(TelemetryManager.isGloballyDisabled()); + assertNull(TelemetryManager.initializeForConnection(Boolean.TRUE)); + } } From cec57b2ba83f5099f0b69ed5113050bd52f899f9 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Thu, 3 Dec 2026 12:52:31 +0000 Subject: [PATCH 13/13] docs(bigquery-jdbc): update precedence comments across TelemetryConfiguration builder methods --- .../jdbc/telemetry/v1/TelemetryConfiguration.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryConfiguration.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryConfiguration.java index 622be6a2de5d..5ba8db3f75bb 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryConfiguration.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryConfiguration.java @@ -166,8 +166,11 @@ Builder setDriverEnvironment(DriverEnvironment driverEnvironment) { return this; } + /** + * Resolves the enabled state with precedence: JVM system property > environment variable + * > connection property. + */ Builder resolveProperties(Properties connectionProperties) { - // 1. Connection Properties (lowest precedence) if (connectionProperties != null) { String enableStr = connectionProperties.getProperty("EnableDiagnosticTelemetry"); this.enabled = TelemetryPropertyUtility.convertStringToBoolean(enableStr, this.enabled); @@ -175,6 +178,10 @@ Builder resolveProperties(Properties connectionProperties) { return applyGlobalOverrides(); } + /** + * Resolves the enabled state with precedence: JVM system property > environment variable + * > explicit connection setting. + */ Builder resolveEnabled(Boolean explicitEnabled) { if (explicitEnabled != null) { this.enabled = explicitEnabled; @@ -183,7 +190,7 @@ Builder resolveEnabled(Boolean explicitEnabled) { } private Builder applyGlobalOverrides() { - // 2. Environment Variables (overrides connection properties) + // Environment variable overrides connection-level settings. try { String envEnabled = System.getenv("BIGQUERY_JDBC_TELEMETRY_ENABLED"); this.enabled = TelemetryPropertyUtility.convertStringToBoolean(envEnabled, enabled); @@ -191,7 +198,7 @@ private Builder applyGlobalOverrides() { // Ignore and proceed } - // 3. JVM System Properties (highest precedence) + // JVM system property takes highest precedence over both connection and environment settings. try { String sysEnabled = System.getProperty("BIGQUERY_JDBC_TELEMETRY_ENABLED"); this.enabled = TelemetryPropertyUtility.convertStringToBoolean(sysEnabled, enabled);