Skip to content

docs(gax): fix broken URLs, invalid Javadoc tags, and raw Markdown syntax - #63

Closed
lqiu96 wants to merge 57 commits into
mainfrom
docs/gax-0b-urls-tags
Closed

lqiu96 wants to merge 57 commits into
mainfrom
docs/gax-0b-urls-tags

Conversation

@lqiu96

@lqiu96 lqiu96 commented Nov 22, 2026

Copy link
Copy Markdown
Owner

Replaces broken/legacy URLs and fixes invalid Javadoc tags, broken links, and raw Markdown/proto syntax across gax, gax-grpc, and api-common (Wave 1 item GAX-0b):

  • URLs:
    • GoogleCredentialsProvider: updates legacy developers.google.com ADC link to https://docs.cloud.google.com/docs/authentication/application-default-credentials.
    • ApiStreamObserver: removes dead http://www.ibm.com/developerworks/... link and defines thread-compatible concisely in prose.
    • StatusCode: replaces 404 grpc-java/blob/master/core/.../Status.java URL with https://grpc.io/docs/guides/status-codes/.
    • MtlsProvider: updates Java 7 Oracle Process#exitValue comment URL to Java 8.
    • ApiService: updates Wikipedia DAG link from http:// to https://.
    • InstantiatingGrpcChannelProvider: fixes malformed // {@link <a href=...>} comments to plain canonical https://docs.cloud.google.com/compute/docs/metadata/overview#https-mds-* URLs.
  • Javadoc tags, links & raw Markdown/proto syntax:
    • InstantiatingGrpcChannelProvider: replaces 4 invalid {@param ...} inline tags with {@code ...}, fixes broken {@link S2A} -> {@link SecureSessionAgent}, fills in empty @param useS2A, and fixes mtTLS / estbalish typos.
    • GrpcCallContext: fixes broken {@link #withTransportChannel()} -> {@link #withTransportChannel(TransportChannel)}.
    • EndpointContext, StubSettings, OpenTelemetryMetricsRecorder: converts raw Markdown backticks in Javadocs to {@code ...}.
    • com.google.longrunning/package-info.java: replaces raw proto link [Operation][google.longrunning.Operation] and backticks with {@link Operation} and {@code Operations}, and removes the false "along with usage samples" claim.

Verified all replacement URLs return HTTP 200. Verified with /usr/bin/google-java-format -i, mvn -Dlint checkstyle:check@checkstyle test javadoc:javadoc -Ddoclint=syntax,html,reference across api-common-java, gax, and gax-grpc (zero errors). Zero behavioral changes.

@lqiu96
lqiu96 force-pushed the docs/gax-0b-urls-tags branch from 1a13c04 to 707bae8 Compare November 22, 2026 21:06
lqiu96 and others added 29 commits November 24, 2026 09:45
…oggingHandler and LoggingLevel (googleapis#15156)

Fixes factual Javadoc errors and typos in `LoggingHandler`,
`LoggingLevel`, and `LoggingConfig` (documentation-only change with no
behavioral or API signature changes):

- `LoggingHandler.java`:
- Fixes the wrong `logging.properties` key
`com.google.cloud.logging.Synchronicity` to
`com.google.cloud.logging.LoggingHandler.synchronicity` (matching the
property actually read by `LoggingConfig`).
- Fixes copy-pasted `getSynchronicity()` Javadoc (`"Get the flush log
level."` -> returns write synchronicity).
- Removes broken `{@link LoggingConfig}` reference to a package-private
class and fixes missing spaces before `{@link LogEntry}`.
- Converts the single-star `/*` deprecation comment on
`getRedirectToStdout()` to Javadoc `/**` and documents `getLogTarget()`.
- Clarifies `addHandler(Logger, LoggingHandler)` accurately as a
convenience wrapper over `Logger#addHandler(Handler)`.
- `LoggingLevel.java`: fixes broken `{@code ALL < DEBUG < FINES}T` and
typo `levet`.
- `LoggingConfig.java`: fixes wrong package name
`com.google.cloud.logging.context.ContextHandler` to
`com.google.cloud.logging.ContextHandler`.

### Verification
- `fmt:check` (`google-java-format`): passed.
- JDK 25 `mvn -f java-logging/google-cloud-logging/pom.xml -Dlint
checkstyle:check@checkstyle test-compile javadoc:javadoc`: passed (0
Checkstyle violations, 0 Javadoc errors).
…y and timeout settings (googleapis#15128)

Documents the retry and timeout configuration entry points on
`BigQueryOptions` and `BigQueryRetryConfig`:

- Adds class Javadoc to `BigQueryOptions` distinguishing overall retry
bounds (`Builder.setRetrySettings`) from per-attempt HTTP connect and
read timeouts (`Builder.setTransportOptions(HttpTransportOptions)`,
60-second default read timeout via `getDefaultHttpTransportOptions()`).
- Documents `Builder.setTransportOptions`,
`Builder.setResultRetryAlgorithm` (including default retry behavior and
linking `BigQueryException#isRetryable()`), and
`getDefaultHttpTransportOptions()`.
- Documents `BigQueryRetryConfig` and its builder methods, explaining
why message-based retries exist (BigQuery returns transient failures
like rate limits with non-5xx codes such as 403 or 400 or in job error
payloads), clarifying its scope (job creation for all job types via
`JobOption.bigQueryRetryConfig(...)` and query job status polling via
`Job.waitFor(BigQueryRetryConfig, RetryOption...)`, ignored for
non-query jobs in `waitFor`), and clarifying case-insensitive substring
matching (`retryOnMessage`) vs. lowercased full-string regex matching
(`retryOnRegEx`).

Verified with `mvn fmt:check`, `checkstyle:check@checkstyle`,
`test-compile`, and `javadoc -Xdoclint:syntax,html,reference` (zero new
warnings).
…rse domain (googleapis#15191)

Overrides `getServiceName()` to return `"longrunning"` and removes
`builder.setEndpoint(getDefaultEndpoint())` from
`OperationsStubSettings.Builder.createDefault()` so `EndpointContext`
resolves the endpoint from the configured universe domain when no
explicit endpoint is set. Also annotates `getDefaultEndpoint()` with
`@ObsoleteApi` and builds default retry settings in
`HttpJsonOperationsStub.create(ClientContext, ...)` via
`OperationsStubSettings.newBuilder((ClientContext) null)`.
…nectionImpl (googleapis#15200)

Extracts `ConnectionImpl.createBigQueryReadSettings()` and forwards
`bigQueryOptions.getUniverseDomain()` when non-null to
`BigQueryReadSettings.newBuilder()`, matching
`BigQueryImpl.configureReadSettings`. Also uses
`NoCredentialsProvider.create()` when `bigQueryOptions.getCredentials()`
is `null`, and adds unit tests in `ConnectionImplTest` covering custom
universe domain, default universe domain, resolved endpoint, and null
credentials.
…tPath presubmits (googleapis#15181)

## Summary
- Adds a composable `bigtable-classic-it` Maven profile in
`java-bigtable/google-cloud-bigtable/pom.xml` mirroring
`bigtable-session-it`:
  - Sets `bigtable.internal.client-config-override-use-default=true`
- Sets `bigtable.internal.client-config-override` to
`session_configuration { session_diversion_configuration {
global_diversion { session_load: 0.0 } } }`
- Wires `bigtable-classic-it` into
`.kokoro/presubmit/bigtable-integration-cfe.cfg` and
`.kokoro/presubmit/bigtable-integration-dp.cfg`.

## Why
Previously, the CFE and DirectPath presubmit jobs only ran the classic
data path implicitly because the target prod instance has not ramped
server-driven session diversion yet. Composing `bigtable-classic-it`
ensures the `{CFE, DirectPath} x {Classic, Session}` matrix stays
explicit and resilient once environments enable sessions by default,
while `bigtable-integration.cfg` (`-P bigtable-prod-it`) continues
testing the un-overridden server-driven default.

Builds on googleapis#15171 (`AbstractTestEnv.isSessionsEnabled()`), so setting
`bigtable.internal.client-config-override` with `session_load: 0.0` is
properly recognized as classic (skipping `SessionIT` and running
classic-only tests like `LargeRowIT` and `DirectPathFallbackIT`).

## Verification
- Verified resolved Failsafe `systemPropertyVariables` via `mvn
help:effective-pom` for:
- `-P bigtable-cfe-it,bigtable-classic-it` (`session_load: 0.0`,
`override-use-default=true`)
- `-P bigtable-directpath-it,bigtable-classic-it` (`session_load: 0.0`,
`override-use-default=true`)
- `-P bigtable-prod-it` (override remains empty,
`override-use-default=false`)
- Ran `CloudEnvTest` and `ClientConfigurationManagerTest` (`23/23`
passed).
…igs (googleapis#15208)

Adds `@googleapis/bigtable-team` to `.github/CODEOWNERS` (alongside
`@googleapis/cloud-sdk-java-team`) for Bigtable-specific CI
configurations so the Bigtable client team can review and approve
changes to our own Kokoro configs, Kokoro scripts, and GitHub Actions
workflows:

- `/.kokoro/bigtable-*` (`.kokoro/bigtable-cleanup.sh`,
`.kokoro/bigtable-conformance.sh`)
- `/.kokoro/presubmit/bigtable-*` (Bigtable integration and GraalVM
native presubmit `.cfg` files)
- `/.kokoro/nightly/bigtable-*` (`.kokoro/nightly/bigtable-cleanup.cfg`)
- `/.github/workflows/java-bigtable-*`
(`.github/workflows/java-bigtable-emulator.yaml`,
`.github/workflows/java-bigtable-conformance.yaml`)

`@googleapis/cloud-sdk-java-team` remains a co-owner on all matched
paths, matching the existing `/java-bigtable/` rule.
… .mvn/maven.config (googleapis#15207)

Configure Maven Resolver HTTP transport retries and backoff for HTTP
429/5xx responses in `.mvn/maven.config` to mitigate transient Maven
Central rate-limit failures in CI.

b/590162583
Update the universeDomain connection property description, unit and
integration test identifiers and literals, JUnit @tag annotations
(disable_universe_domain), and testing skill documentation to use
universe domain terminology consistently and remove internal links.
…tocol (googleapis#15206)

## Summary

Fixes a bug where Maven Failsafe's empty
`-Dbigtable.internal.client-config-override=""` bypassed
`GetClientConfiguration` polling on default integration test runs, and
adds suite-wide protocol enforcement (`-Dbigtable.expected-protocol`)
for Bigtable integration tests.

### Changes
1. **Ignore blank `bigtable.internal.client-config-override`
(`ClientConfigurationManager`)**:
- Filter out blank strings (`.filter(str -> !str.trim().isEmpty())`) so
empty default `<properties>` in `pom.xml` are treated as unset and
default IT runs genuinely poll `GetClientConfiguration`.
- Added unit test `testBlankSysPropOverrideIsIgnoredAndPollsServer` in
`ClientConfigurationManagerTest`.
2. **Skip `GetClientConfiguration` in DirectPath remote-address check
(`CloudEnv`)**:
- Under `REQUIRE_DIRECT_PATH` / `REQUIRE_DIRECT_PATH_IPV4`, skip the
remote IP check for `GetClientConfiguration` since
`ClientConfigurationManager` always polls over CloudPath regardless of
data transport.
- Keep checking `GetClientConfiguration` under `REQUIRE_CFE` so
`ShimImpl`'s DirectAccess probe over DirectPath continues to be rejected
and forces CFE.
3. **Suite-wide protocol enforcement (`AbstractTestEnv`, `CloudEnv`,
`pom.xml`, `.kokoro/presubmit/bigtable-integration.cfg`)**:
- Added `-Dbigtable.expected-protocol` (`ANY` | `CLASSIC` | `SESSION`),
defaulting to `ANY` when unset/blank, set to `SESSION` in
`bigtable-session-it`, and passed as `CLASSIC` in
`.kokoro/presubmit/bigtable-integration.cfg` *(follow-up: add `CLASSIC`
to `bigtable-classic-it` once googleapis#15181 merges)*.
- Validate resolved session config in `CloudEnv.start()` via
`verifyExpectedProtocol(...)`.
- Attach a suite-wide protocol enforcement interceptor (including under
`ConnectionMode.DEFAULT`):
- `CLASSIC`: aborts any `Bigtable/Open*` RPC with
`Status.FAILED_PRECONDITION`.
- `SESSION`: aborts classic `MutateRow`, `CheckAndMutateRow`,
`ReadModifyWriteRow`, and single-point `ReadRows` (`rows_limit == 1`
with single key or equal closed-closed range) with
`Status.FAILED_PRECONDITION`, leaving bulk/range `ReadRows` and
`MutateRows` unblocked.
- Added unit tests in `CloudEnvTest` covering protocol parsing, startup
validation, remote-address skipping, and protocol enforcement.
4. **Gate `SessionIT` on `ExpectedProtocol.SESSION`**:
- Switch `SessionIT`'s `assume()` from `isSessionsEnabled()` to
`getExpectedProtocol() == ExpectedProtocol.SESSION` so environments
mid-ramp (e.g. 50% diversion) don't flake once `GetClientConfiguration`
polling is restored.

## Verification
- Formatted with `mvn com.spotify.fmt:fmt-maven-plugin:format`
- Verified `mvn help:effective-pom` for `bigtable-prod-it`,
`bigtable-prod-it -Dbigtable.expected-protocol=CLASSIC`, and
`bigtable-cfe-it,bigtable-session-it`
- Ran `mvn test -Dtest=CloudEnvTest,ClientConfigurationManagerTest`
(34/34 passed, 0 Checkstyle violations)
…gleapis#15214)

Remove three unused `testUniverseDomain()` methods in the BigQuery
Storage integration tests (`v1`, `v1beta1`, and `v1beta2`).

These methods were missing `@Test` annotations and had no callers, so
they were never executed. The neighboring `@Test` methods
(`testUniverseDomainWithInvalidUniverseDomain`,
`testInvalidUniverseDomainWithMismatchCredentials`, and
`testUniverseDomainWithMatchingDomain`) already cover universe domain
integration testing.
…count credentials (googleapis#15189)

Follow-up to googleapis#15176. `JwtCredentials` created by
`ServiceAccountCredentials` and `ServiceAccountJwtAccessCredentials` now
carry the source credential's universe domain.
`ServiceAccountJwtAccessCredentials` also includes `universeDomain` in
`equals()`, `hashCode()`, and `toString()`, and defaults it to
`googleapis.com` when deserializing older objects.
…ogs (googleapis#15213)

Update historical changelog entries in `java-spanner/CHANGELOG.md` and
`java-storage/CHANGELOG.md` to use universe domain terminology.
…ofile (googleapis#15215)

Follow-up to googleapis#15181 and googleapis#15206 (which were branched independently before
merging).

Sets `<bigtable.expected-protocol>CLASSIC</bigtable.expected-protocol>`
in the `bigtable-classic-it` Maven profile so `Classic CFE` and `Classic
DirectPath` integration test runs enforce the classic protocol via
`CloudEnv`'s startup check and `ProtocolEnforcementInterceptor`,
matching `bigtable-session-it` (`SESSION`) and prod `Default`
(`CLASSIC`).

## Verification
- Verified `mvn help:effective-pom -P
bigtable-cfe-it,bigtable-classic-it` resolves
`bigtable.expected-protocol=CLASSIC` in `maven-failsafe-plugin`'s
`cfe-it` execution.
…oogleapis#15164)

Skip checkstyle in `upper-bound-check/pom.xml` to avoid missing
`license-checks.xml` failures while keeping the enforcer checks active.

b/588715584
…ithFailuresGetAttempt (googleapis#15199)

Capture the first attempt future before submitting in
`ScheduledRetryingExecutorTest.testSuccessWithFailuresGetAttempt` so the
test deterministically observes at least one failed attempt when
`RecordingScheduler` runs retries with zero delay.

b/590115628
…tors (googleapis#15217)

Documents that `GoogleCredentials` access-token factory methods and
constructors without an explicit universe domain default to
`googleapis.com` (`Credentials.GOOGLE_DEFAULT_UNIVERSE`), and delegates
`GoogleCredentials.create(AccessToken)` to
`GoogleCredentials.create(@nullable String, AccessToken)` while
preserving `isExplicitUniverseDomain() == false`.
Applications and upstream libraries (such as JDBC drivers, ORMs, and
database proxies) sometimes accept Spanner connection URIs or query
parameters from untrusted callers. Previously, callers could pass
startup-level settings in the URI query string—such as custom endpoints,
credentials, channel counts, or session pool sizes—forcing the client to
open unauthorized connections or allocate separate shared Spanner client
pools. At the same time, many startup properties could only be set
through the URI string itself.

This change lets upstream libraries safely separate trusted
configuration from untrusted URI input:

- Programmatic startup configuration: Upstream libraries can set any
connection property programmatically on the options builder using
validated typed values, which take precedence over URI parameters.
- Opt-in rejection of startup properties in URIs: Upstream libraries
accepting untrusted connection URIs can configure the builder to reject
any startup property found in the URI, while continuing to allow safe
per-connection user settings (such as read-only mode, autocommit, or
query optimizer options).
- Stricter URI parsing and validation: Replaces per-property regex
matching with a single shared parser so validation and extraction cannot
disagree, and tightens the URI host and delimiter patterns so malformed
hosts, extra delimiters, or embedded paths in query parameters cannot
alter the target host or project.

Together, this gives upstream integrations a safe, auditable way to lock
down shared client and connection pool settings in code without
maintaining fragile allowlists or URI sanitizers.
…oogleapis#15180)

Adds `universeDomain` support to `OAuth2CredentialsWithRefresh`:

- Adds `universeDomain` field (defaulting null or blank values to
`googleapis.com`), overrides `getUniverseDomain()`, adds
`Builder.setUniverseDomain()` and `Builder.getUniverseDomain()`, and
includes `universeDomain` in `equals()` and `hashCode()`.
- Pins `serialVersionUID` to the prior computed value and normalizes
null or blank `universeDomain` in `readObject()` for deserialization
compatibility with older streams.
- Updates `OAuth2Credentials.create(AccessToken)` and
`OAuth2Credentials.newBuilder()` Javadocs to note the `googleapis.com`
default and point custom universe domain callers to `GoogleCredentials`.
- Adds unit tests in `OAuth2CredentialsWithRefreshTest` covering builder
and resolved universe domains, protected constructor default,
serialization round-trips and legacy null/blank deserialization, and
`equals()`/`hashCode()` (including default normalization and null
initial access tokens).
…oogleapis#15180)

Adds `universeDomain` support to `OAuth2CredentialsWithRefresh`:

- Adds `universeDomain` field (defaulting null or blank values to
`googleapis.com`), overrides `getUniverseDomain()`, adds
`Builder.setUniverseDomain()` and `Builder.getUniverseDomain()`, and
includes `universeDomain` in `equals()` and `hashCode()`.
- Pins `serialVersionUID` to the prior computed value and normalizes
null or blank `universeDomain` in `readObject()` for deserialization
compatibility with older streams.
- Updates `OAuth2Credentials.create(AccessToken)` and
`OAuth2Credentials.newBuilder()` Javadocs to note the `googleapis.com`
default and point custom universe domain callers to `GoogleCredentials`.
- Adds unit tests in `OAuth2CredentialsWithRefreshTest` covering builder
and resolved universe domains, protected constructor default,
serialization round-trips and legacy null/blank deserialization, and
`equals()`/`hashCode()` (including default normalization and null
initial access tokens).
…#15221)

Adds `access_boundary_session_key` to
`Slf4jLoggingHelpers.SENSITIVE_KEYS` so STS response payload values for
that field are SHA-256 masked when SLF4J debug logging is enabled.

Extends
`LoggingTest.stsRequestHandler_exchangeToken_masksSensitiveTokens()` to
verify that `access_boundary_session_key` is masked in STS response
payload logs.
googleapis#15174)

Propagate `universeDomain` and defer the default endpoint on
`InstantiatingGrpcChannelProvider` so GAX resolves
`firestore.<universeDomain>:443` from the configured universe domain
(`setUniverseDomain(...)` or `GOOGLE_CLOUD_UNIVERSE_DOMAIN`).

### Summary of Changes
- **`FirestoreOptions`**: Leave the default gRPC channel provider
endpoint unset unless a non-default custom host is configured; track
explicit `setChannelProvider(...)` so `toBuilder().setHost(...)` and
`toBuilder().setOpenTelemetryOptions(...)` rebuild synthesized providers
without discarding explicit ones; include `universeDomain` in `equals()`
/ `hashCode()`.
- **`GrpcFirestoreRpc`**: Extract `@VisibleForTesting`
`createFirestoreSettings(FirestoreOptions)` to propagate
`universeDomain` (when non-null) and custom `host` (when non-default) to
`FirestoreSettings`, avoid eagerly building `FirestoreSettings` prior to
overrides, and release `executor` / background resources on constructor
failure.
- **`ITBaseTest`**: Null-safe fallback to `firestoreOptions.getHost()`
when logging `getTransportChannelProvider().getEndpoint()`.
- **Tests**: Expand `FirestoreOptionsTest` and `GrpcFirestoreRpcTest`
covering default endpoint deferral, `toBuilder()` variants, custom
host/channel provider precedence, credential mismatch validation
(`UNAUTHENTICATED`), and constructor failure cleanup.
…#15221)

Adds `access_boundary_session_key` to
`Slf4jLoggingHelpers.SENSITIVE_KEYS` so STS response payload values for
that field are SHA-256 masked when SLF4J debug logging is enabled.

Extends
`LoggingTest.stsRequestHandler_exchangeToken_masksSensitiveTokens()` to
verify that `access_boundary_session_key` is masked in STS response
payload logs.
…t endpoint in StreamWriter (googleapis#15209)

b/589828843

Stops pinning `BigQueryWriteSettings.getDefaultEndpoint()` in
`StreamWriter` and `StreamWriterV2`, exposes `setUniverseDomain(String)`
on `StreamWriter`, `SchemaAwareStreamWriter`, `JsonStreamWriter`, and
`StreamWriterV2` builders, and includes endpoint and universe domain in
`StreamWriter.ConnectionPoolKey`.
…tedCredentials (googleapis#15201)

- Validates the optional top-level universe_domain field when loading
ImpersonatedCredentials from JSON, throwing an IOException if it
conflicts with the source credentials and storing it on the builder when
present.
- Updates sign() and idTokenWithAudience() to honor iamEndpointOverride
when configured, by replacing the :generateAccessToken suffix of the
override with :signBlob or :generateIdToken instead of always using the
source credentials' universe domain. This keeps whatever host the
override specifies. If the override does not end with
:generateAccessToken, both methods return an error rather than falling
back to the default endpoint.
- Changes the package-private IamUtils.sign() and IamUtils.getIdToken()
to take the endpoint URL instead of a service account email and universe
domain, and updates ComputeEngineCredentials to match.
- Adds unit tests covering universe_domain validation and signing/ID
token endpoint overrides.
… parsing (googleapis#15218)

Bug: b/584839496

### The Issue
`BigQueryTemporalUtility.parseEpochDecimalToInstant` and
`BigQueryTemporalUtility.formatTimestampStringFromEpochDecimal` called
`new BigDecimal(epochDecimal).setScale(..., RoundingMode.DOWN)` without
bounding input length or exponent magnitude. Coercing a `STRING` or
`JSON` column containing a large-exponent scientific-notation value
(such as `"1e100000000"`, `"1e2147483648"`, or
`"12345678901234567890e-100000000"`) via `ResultSet.getTimestamp` or
`ResultSet.getObject`, or formatting out-of-range epoch-decimal strings
in `TIMESTAMP(12)` / `RANGE<TIMESTAMP>`, triggered unbounded
`BigInteger.bigTenToThe` expansion, causing uninterruptible CPU stalls
and uncaught `OutOfMemoryError` (or unchecked `DateTimeException` on
17-digit out-of-range epoch seconds).

### The Fix
- Added `BigQueryTemporalUtility.parseScaledEpochDecimal` to reject
strings longer than 128 characters, short-circuit zero (`signum() == 0`)
and sub-unit magnitudes (`integerDigits <= -scale`) to
`BigDecimal.ZERO.setScale(scale)`, and reject integer magnitudes
exceeding 17 digits (`Instant.MIN..Instant.MAX` width, computed in
`long` arithmetic to prevent 32-bit `int` overflow) before calling
`BigDecimal.setScale`.
- Wrapped `LocalDateTime.ofEpochSecond` in
`formatTimestampStringFromEpochDecimal` to catch `DateTimeException` and
rethrow `BigQueryJdbcException`.
- Added unit regression tests in `BigQueryTemporalUtilityTest` covering
extreme positive exponents, extreme sub-unit/zero exponents, and
overlong inputs.
…oogleapis#15175)

Skips client-side universe domain validation for `ApiKeyCredentials` and
documents universe domain expectations for API keys:

- `gax`: updates `EndpointContext.validateUniverseDomain(...)` to skip
validation for `ApiKeyCredentials`, avoids wrapping `ApiKeyCredentials`
in `QuotaProjectIdHidingCredentials` inside `ClientContext`, and updates
`ClientSettings.Builder.setApiKey(...)` and
`StubSettings.Builder.setApiKey(...)` Javadocs.
- `google-cloud-core` and `google-cloud-core-http`: updates
`ServiceOptions.hasValidUniverseDomain()` (with null-credentials
handling) and `HttpTransportOptions` to skip validation for
`ApiKeyCredentials`.
- `google-cloud-datastore`: updates
`HttpDatastoreRpc.validateUniverseDomain()` to skip validation for
`ApiKeyCredentials`.
- `google-auth-library-credentials`: updates `ApiKeyCredentials` Javadoc
to warn that API keys do not carry universe domain metadata, requests
default to `googleapis.com` when no universe domain is configured on the
client, and callers are responsible for ensuring the API key belongs to
the configured universe domain.

BEGIN_COMMIT_OVERRIDE
doc(auth): update ApiKeyCredential support with universe domain
fix(gax): skip universe domain validation for ApiKeyCredentials
fix(core): skip universe domain validation for ApiKeyCredentials
END_COMMIT_OVERRIDE
…oto and fix list*ViewsTest (googleapis#15243)

`MaterializedView.equals()` and `LogicalView.equals()` delegate to
protobuf message equality, which compares every field including
server-populated read-only metadata and `UnknownFieldSet` entries.

When `ListMaterializedViews` or `ListLogicalViews` populates read-only
metadata fields that are not populated in the `CreateMaterializedView` /
`CreateLogicalView` LRO response, `assertThat(response).contains(view)`
fails even when the view is returned with the expected ID,
deletion-protection setting, and query.

- Delegate `MaterializedView#toString()` and `LogicalView#toString()` to
`proto.toString()` (with unit tests in `MaterializedViewTest` and
`LogicalViewTest`) so failure messages print readable protobuf contents
instead of default `Object#toString()` identity hashes.
- Update `BigtableMaterializedViewIT#listMaterializedViewsTest` and
`BigtableLogicalViewIT#listLogicalViewsTest` to compare elements via
Truth `Correspondence` (`comparingElementsUsing(...)`) on `getId()`,
`isDeletionProtected()`, and `getQuery()`.
alkatrivedi and others added 27 commits November 26, 2026 17:09
…pport, and retry prerequisites (googleapis#15194)

### Summary

Part 1 of 3 for adding client-side retry and stream resumption support
to batchWriteAtLeastOnce.

This PR introduces independent client/metrics prerequisites along with
the package-private resumption-state and retry-policy building blocks.
Stream resumption is not wired into GapicSpannerRpc yet in this PR, so
BatchWrite retry behavior remains unchanged until Part 3.

### Stack Overview
**Part 1 (this PR):** Client/metrics prerequisites,
BatchWriteResumptionState, and BatchWriteRetryPolicy
**Part 2:** BatchWriteResumingServerStreamingCallable coordinator and
stream-resumption unit tests
**Part 3:** GapicSpannerRpc / SpannerRpc wiring, empty-request
short-circuit, and end-to-end mock-server retry tests
… is unset (googleapis#15142)

## Problem Statement

- When no universe domain was set explicitly, the Spanner client coerced
it to `googleapis.com` for the data, instance admin, and database admin
stubs and for the default host, so `GOOGLE_CLOUD_UNIVERSE_DOMAIN` was
ignored.
- The `universeDomain` connection property defaulted to
`googleapis.com`, so `ConnectionOptions` and pooled Spanner clients also
ignored `GOOGLE_CLOUD_UNIVERSE_DOMAIN`.
- Built-in metrics received the unresolved universe domain rather than
the one used by the Spanner stubs.

## Solution

- Add `SpannerOptions.SpannerEnvironment#getUniverseDomain()`, backed by
`GOOGLE_CLOUD_UNIVERSE_DOMAIN`.
- Resolve the universe domain with the precedence: explicit setting,
then environment, then `googleapis.com`, and use that value for the
stubs, the default host, and built-in metrics.
- The `universeDomain` connection property is now unset by default, so
`ConnectionOptions#getUniverseDomain()` returns `null` when it is not
configured.
- An unset or empty `GOOGLE_CLOUD_UNIVERSE_DOMAIN` still falls back to
`googleapis.com`.
- An invalid `GOOGLE_CLOUD_UNIVERSE_DOMAIN` fails with
`IllegalArgumentException` at `SpannerOptions.Builder#build()`
(including when a host or emulator host is set) and with
`INVALID_ARGUMENT` in `ConnectionOptions#getChannelProvider()`.
… OPAQUE (googleapis#15146)

## Problem Statement
- During Spanner Omni OPAQUE authentication, `OpaqueUtil.finalize`,
`OpaqueUtil.diffieHellman`, and `OpaqueUtil.blind` accepted the
elliptic-curve point at infinity (`{0x00}`) and non-canonical point
encodings.
- If a rogue login server returned `{0x00}` as `evaluated_message`,
`OpaqueUtil.finalize` returned `{0x00}` regardless of the client's
password or blind scalar, making all derived OPAQUE envelope and AKE
keys password-independent and breaking mutual server authentication.

## Solution
- Enforce canonical 33-byte compressed `secp256r1` point encoding
(`0x02` or `0x03` prefix) and reject the point at infinity,
non-canonical encodings, and off-curve points before and after scalar
multiplication in `OpaqueUtil.finalize`, `OpaqueUtil.diffieHellman`, and
`OpaqueUtil.blind` (per RFC 9497 Section 3.3.1 / RFC 9807).
- Validate that scalar inputs (`blind`, `privateKey`, `blindScalar`) are
non-null, non-empty, and non-zero modulo the curve order.
- Behavior change: direct callers of `OpaqueUtil.finalize`,
`OpaqueUtil.diffieHellman`, or `OpaqueUtil.blind` now receive a checked
`GeneralSecurityException` on invalid points or zero/order-multiple
scalars rather than `{0x00}` or unchecked `IllegalArgumentException`,
`NullPointerException`, or `ArithmeticException`.
…ted clients (googleapis#15259)

## Problem Statement
- Creating a non-emulator Cloud Spanner client without Google
credentials (such as with `NoCredentials`, `usePlainText()`, or no
Application Default Credentials) before an authenticated client in the
same JVM could initialize the shared Cloud Monitoring built-in metrics
exporter without credentials.
- Because the Cloud Monitoring exporter is shared across the process,
subsequent authenticated Spanner clients in the same JVM could fail to
export built-in metrics to Cloud Monitoring.

## Solution
- Skip initializing the Cloud Monitoring built-in metrics exporter
during gRPC and fallback metrics setup when a Spanner client is
configured with `NoCredentials` or `null` credentials, matching existing
behavior for application-layer and channel-pool built-in metrics.
- Preserve caller-owned `CustomOpenTelemetryMetricsProvider` sinks so
clients without Google credentials can still export metrics to custom
OpenTelemetry destinations.
…n in user account OAuth flow (googleapis#15241)

b/584840384

### Summary
Aligns interactive user-account authentication (`OAuthType=1`) in
`BigQueryJdbcOAuthUtility` with RFC 8252 and RFC 7636, extracts the
local loopback HTTP callback listener into
`BigQueryJdbcOAuthCallbackServer`, and ensures `RequestGoogleDriveScope`
and explicit `universeDomain` settings apply to user-account
credentials.

### What Changed & Why
- **Desktop pre-check & deterministic socket cleanup:**
`getGoogleUserAccountCredentials` checks `isDesktopBrowseSupported()`
(`GraphicsEnvironment.isHeadless()`, `Desktop.isDesktopSupported()`, and
`Desktop.Action.BROWSE`) before opening a local socket, and wraps
`BigQueryJdbcOAuthCallbackServer` and accepted `Socket` instances in
`try-with-resources` so the listener closes prior to token exchange and
on any error or timeout.
- **RFC 8252 loopback redirect URI
(`BigQueryJdbcOAuthCallbackServer`):** `openLoopbackServerSocket()`
binds `127.0.0.1` (falling back to `::1` on IPv6-only hosts, `backlog =
8`) using `java.net.ServerSocket` (`java.base`, avoiding a
`jdk.httpserver` module dependency in custom `jlink` / OSGi runtimes)
and `buildLoopbackCallbackUri()` formats `http://127.0.0.1:<port>` or
`http://[::1]:<port>` for `getUserAuthorizer`. Matching the bound IP
family avoids `Connection Refused` errors when the browser and JVM
resolve `localhost` to different address families. (The 9-argument
`getGoogleUserAccountCredentials` and 1-argument
`openLoopbackServerSocket` package-private overloads are deterministic
test seams to which the production entry points delegate.)
- **RFC 7636 `S256` PKCE, OAuth `state`, & `RequestGoogleDriveScope`:**
Configured `UserAuthorizer` with `Rfc7636PkceProvider` (used instead of
`DefaultPKCEProvider`, which in `google-auth-library-oauth2-http`
`1.58.0` emits a 172-character `=`-padded `code_verifier` outside RFC
7636 Section 4.1's 43–128 unreserved-character range), added `state`
generation and callback verification, and wired
`RequestGoogleDriveScope` (`BIGQUERY_WITH_DRIVE_SCOPES` vs.
`DEFAULT_BIGQUERY_SCOPES`) at authorization consent time.
- **Explicit `universeDomain` propagation:** `getCredentialsFromCode`
propagates `UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME` from
`overrideProperties` onto `UserCredentials.Builder`, matching non-JSON
credential handling for custom universe domains.
- **Reliable HTTP/1.1 callback parsing & responses:**
- Enforces a `1000 ms` per-socket read timeout within the `120 s`
callback window, skipping empty browser TCP preconnects, returning `404
Not Found` for secondary requests such as `/favicon.ico`, and continuing
to listen after malformed or unverified HTTP requests (responding `400
Bad Request` and recording the last rejected request reason in case the
callback window times out).
- Parses the callback request target via `URI`, UTF-8 URL-decodes query
parameters while preserving literal `+` characters per RFC 3986 (`code`,
`state`, `error`), and immediately aborts when a `state`-verified
callback reports an OAuth `error=` or omits `code`.
- Drains up to `64 KiB` of request headers (accommodating `127.0.0.1`
cookies) and calls `socket.shutdownOutput()` after flushing
`\r\n`-formatted HTTP/1.1 responses (`200 OK`, `400 Bad Request`, `404
Not Found`) with `Cache-Control: no-store`, `X-Content-Type-Options:
nosniff`, `Content-Security-Policy: default-src 'none'`, `Connection:
close`, and exact UTF-8 byte `Content-Length`.
- **Documentation (`docs/USER_GUIDE.md`):** Documented that custom
`OAuthClientId` values used with `OAuthType=1` must be configured as a
**Desktop app** OAuth 2.0 client.

### Compatibility Notes
- Existing `OAuthType=1` flows already used ephemeral ports
(`ServerSocket(0)`), which require a Google **Desktop app** OAuth 2.0
client (default or custom `OAuthClientId`). Google Desktop OAuth clients
natively support `http://127.0.0.1:<port>` and `http://[::1]:<port>`
redirect URIs and `S256` PKCE without Cloud Console changes.

### Testing
- `BigQueryJdbcOAuthUtilityTest` covers `S256` PKCE challenge/verifier
exchange, `RequestGoogleDriveScope` consent scope selection, default vs.
explicit `universeDomain` propagation (including ignoring
`GOOGLE_CLOUD_UNIVERSE_DOMAIN` for non-JSON credentials), IPv4/IPv6
loopback binding without mocking JDK networking classes, RFC 3986 `+`
and `%2B` query decoding and malformed `%` handling, `state` and
`error=` callback validation, `> 16 KiB` and `> 64 KiB` header draining,
resilience to browser TCP preconnects / `/favicon.ico` / unverified
local HTTP probes, timeout diagnostics and socket cleanup paths, and
non-desktop environment fast-fail.
- Live interactive browser consent was not run in automated CI as
`OAuthType=1` requires desktop user interaction.
…reset, and physical isolation (googleapis#15202)

### Summary
Consolidates the 3-PR JDBC connection pooling stack (googleapis#15202, googleapis#15203,
googleapis#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 `RuntimeException`s, 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.
…non-positive values (googleapis#15074)

Sanitize server-supplied `RetryInfo` delays when resuming interrupted
Cloud Spanner streaming reads and queries so zero, negative, or
oversized retry trailers cannot trigger zero-delay retry spin loops or
stall consumer threads for hours.

- Fall back to exponential backoff (`>= 1 ms`) when a server retry delay
is zero, sub-millisecond, or negative instead of retrying immediately
without sleeping.
- Cap positive server retry delays at the configured maximum retry delay
on streaming retry settings (defaulting to `32s` when unset or
non-positive) before evaluating the remaining total timeout budget.
- Use the same `32s` ceiling for client-side exponential backoff when
maximum retry delay is unset on streaming retry settings.
…n-default hosts without an explicit target (googleapis#15252)

## Problem Statement

- When configuring a custom non-`*.googleapis.com` Spanner host via
`SpannerOptions.Builder.setHost(...)` or a JDBC/Connection URL host or
`endpoint` property without setting `universeDomain`,
`GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `monitoringHost`, or
`SPANNER_MONITORING_HOST`, default-on built-in Cloud Monitoring metrics
remained enabled and exported telemetry and credentials to
`monitoring.googleapis.com:443`.

## Solution

- Automatically disable built-in Cloud Monitoring metrics when a custom
non-`*.googleapis.com` host (including malformed or scheme-less hosts)
is configured without an explicit `universeDomain`,
`GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `monitoringHost`, or
`SPANNER_MONITORING_HOST`, logging a warning for non-plaintext,
non-emulator clients.
- Preserve `toBuilder()` re-evaluation when a caller later sets a
universe domain, sets a monitoring host, or clears the custom host, and
leave caller-owned `CustomOpenTelemetryMetricsProvider` sinks
unaffected.
…pis#15044)

### 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.
…ns and symlink checks (googleapis#15112)

Stack: PR 1 of 6 (base: `main`)
Bug: b/584840147

### Summary
Replaces `java.util.logging.FileHandler` in `PerConnectionFileHandler`
with a Java New I/O (NIO) `FileChannel` writer (`ChannelLogWriter`)
enforcing owner-only POSIX (`0700` directory / `0600` file) permissions,
component-by-component symbolic-link and hard-link checks, and graceful
error handling.

### Design Decisions
- **NIO `FileChannel` (`ChannelLogWriter`) over
`java.util.logging.FileHandler`:** Applies `0600` (`rw-------`)
atomically via `StandardOpenOption.CREATE_NEW`, avoids `.lck` sidecar
files and `%` pattern expansion, and keeps `flush()` as a no-op over
unbuffered OS channel writes.
- **Path traversal, symlink, UID & hard-link (`nlink == 1`) checks:**
Walks every path segment from root with `LinkOption.NOFOLLOW_LINKS`,
rejecting target symlinks, non-regular files, hard-linked files
(`unix:nlink > 1`), and foreign-owned paths (while allowing root-owned
OS ancestor symlinks), and re-verifies attributes post-open.
- **Graceful JDBC degradation:** Inaccessible `LogPath` targets report
via `java.util.logging` `ErrorManager` without throwing `SQLException`
from `DriverManager.getConnection(...)`.
…terrupt recovery (googleapis#15253)

Stack: PR 2 of 6 (base: `fix/bq-jdbc-log-file-hardening`)
Bug: b/584840147

### Summary
Adds in-JVM and cross-process sentinel locking on `BQ-JDBC-GLOBAL.log`
with collision-free fallback file allocation and
`ClosedByInterruptException` channel recovery in
`PerConnectionFileHandler`.

### Design Decisions
- **In-JVM + cross-process global log coordination:** Tracks active
canonical global paths in `ACTIVE_GLOBAL_PATHS` and acquires a
non-blocking 1-byte sentinel lock (`FileChannel.tryLock(Long.MAX_VALUE -
1, 1L, false)`), falling back to an exclusive
`BQ-JDBC-GLOBAL-<yyyyMMddHHmmss>-<4hex>.log` file on contention.
- **Interrupt-safe channel writes & recovery:** Preserves the calling
thread's interrupt status in `finally` around NIO channel opens and
writes and reopens validated channels after
`ClosedByInterruptException`.
…ck (googleapis#15165)

Stack: PR 3 of 6 (base: `fix/bq-jdbc-log-lock-and-interrupt`)
Bug: b/584840147

### Summary
Adds bounded 1 GiB log file size rotation onto a single `.1.log`
(`0600`) backup file with in-place truncation fallback in
`PerConnectionFileHandler`.

### Environment Variables & System Properties
- **Added System Property:**
`-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=<bytes>` (default:
`1073741824` / 1 GiB). Documented in `docs/USER_GUIDE.md`.

### Design Decisions
- **1 GiB cap + single `.1.log` (`0600`) backup rotation:** Validates
`.1.log` with `NOFOLLOW_LINKS` (deleting any symlink without following
it), atomically rotates active logs to `.1.log`, and opens a fresh
`0600` active channel while preserving global sentinel locks.
- **In-place truncation fallback:** Falls back to `channel.truncate(0)`
when backup rotation is blocked.
…onnectionLogContext (googleapis#15254)

Stack: PR 4 of 6 (base: `fix/bq-jdbc-log-rotation-and-context`)
Bug: b/584840147

### Summary
Replaces raw `String` `LogRecord.getParameters()[0]` connection-ID
stamping with a package-private typed `ConnectionLogContext` carrier
across `BigQueryJdbcResultSetLogger`, `BigQueryJdbcRootLogger`,
`PerConnectionFileHandler`, and `OpenTelemetryJulHandler`.

### Design Decisions
- **Collision-free parameter routing:** Arbitrary `String` parameters at
`params[0]` can no longer be misinterpreted as connection IDs or spawn
unintended `BQ-JDBC-*-<prefix>.log` files when MDC is empty.
- **OpenTelemetry `MessageFormat` compatibility:**
`OpenTelemetryJulHandler` strips `ConnectionLogContext` at `params[0]`
before positional message formatting.
…nd pre-connect routing (googleapis#15168)

Stack: PR 5 of 6 (base: `fix/bq-jdbc-connection-log-context`)
Bug: b/584840083

### Summary
Isolates per-connection `LogLevel` and `LogPath` configurations using
reference-counted per-directory `ManagedFileHandler` instances,
pre-connect global log scoping (`openPreConnectScope`), and
`ConnectionLogContext` propagation through `BigQueryJdbcMdc` and
`OpenTelemetryJulHandler`.

### Design Decisions
- **Reference-counted per-directory `ManagedFileHandler`s:** Concurrent
connections maintain independent thresholds and directories without
closing sibling handlers or detaching `OpenTelemetryJulHandler`.
- **Scoped pre-connect routing (`openPreConnectScope`):** Routes
pre-UUID connection diagnostics to the target `LogPath`s
`BQ-JDBC-GLOBAL.log` and releases handlers deterministically.
- **Thread-pool & OTel per-connection level isolation:** Propagates
`ConnectionLogContext` across `BigQueryJdbcMdc` executors and enforces
per-connection level thresholds in `OpenTelemetryJulHandler`.
…short-circuit Gate 1 (googleapis#15255)

Stack: PR 6 of 6 (base: `fix/bq-jdbc-per-conn-log-isolation`;
consolidates googleapis#15166, googleapis#15167, and googleapis#15169)
Bug: b/584840147, b/584840083

### Summary
Consolidates the final three diagnostic logging layers and incorporates
review feedback across the stack: synchronizes per-connection writer
slot close-vs-publish lifecycle and constructor failure rollback, masks
non-allowlisted URL/connection secrets with ASCII control-character
sanitization and fail-closed
`-Dcom.google.cloud.bigquery.jdbc.allowUrlLogPath`, and adds Gate-1
`isLoggable` short-circuiting with external JUL `Handler` preservation.

### Environment Variables & System Properties
- **Added System Property:**
`-Dcom.google.cloud.bigquery.jdbc.allowUrlLogPath=<true|false|1|0>`
(default: `true`; fail-closed allowing unset/blank, `true`, or `1`).
When disabled, URL/Properties `LogPath` values are ignored with both a
log `WARNING` and a JDBC `SQLWarning` on `Connection`. Documented in
`docs/USER_GUIDE.md`.

### Design Decisions & Review Feedback Addressed
- **Race-free `ConnectionWriterSlot` & `ReentrantLock` I/O locking:**
Guards writer lifecycle and handler coordination with `ReentrantLock`
(avoiding virtual-thread pinning across file I/O), disarms closed
`ConnectionLogContext`s to `OFF_VALUE`, and cleans up executors/OTel
resources on failed construction.
- **Secret masking & log-injection sanitization:** Removes
`BYOID_CredentialSource` from case-insensitive `SAFE_TO_LOG_PROPERTIES`
and replaces ASCII control characters (`< 0x20`, `0x7F`) with `?` in
logged property keys and allowlisted values.
- **Fast-path Gate-1 filtering:** Checks `super.isLoggable(level)` ahead
of thread-local MDC lookup (`~0.6 ns` disabled path) and preserves
externally attached JUL handlers via `RootDriverLogger`.
- **Channel & rotation refinements:** Opens exclusive channels with
`APPEND`, writes `ByteBuffer`s in 8 KiB slices, emits `[LOG TRUNCATED:
...]` markers on fallback truncation, removes redundant backup UID
checks before atomic `Files.move`, reports invalid `maxLogFileBytes`
once, and installs a bounded `DeduplicatingErrorManager`.
)

Asynchronous queries share a bounded background thread pool to read rows
from query streams and dispatch them to application callbacks.
Previously, each active query held onto a background thread for its
entire lifetime, parking that thread whenever the query was waiting for
more data from the server, waiting for a full row buffer to be drained,
or paused by the application callback. Running many concurrent or paused
queries could exhaust the shared thread pool and stall other queries
waiting for an available worker thread.

This change switches asynchronous query execution to an event-driven
model so background threads are only used while actively moving buffered
rows:

- Event-driven row production: Background tasks read rows only while
stream data is already buffered locally and space remains in the row
queue, releasing the worker thread immediately whenever a query is
waiting on the network, the row buffer is full, or consumption is
paused. Incoming stream data, buffer consumption, and resume calls
re-schedule row production as needed.
- Serialized stream startup and consumption: Completes stream
initialization before row production begins so underlying query
iterators are never accessed concurrently across threads, while
preserving startup error translation for queries that inline transaction
creation.
- Prompt cancellation and clean lifecycle termination: Delivers
cancellation directly to paused or in-flight callbacks without requiring
a separate resume call, closes underlying streams outside internal
locks, and waits for all active tasks to finish before completing the
result future and releasing executor resources.
- Strict callback thread scoping and interrupt handling: Restricts
cursor advancement and row reads in asynchronous mode to the active
callback invocation thread, and cancels the query while preserving the
thread interrupt status if a blocking list conversion is interrupted.
…dmin clients (googleapis#15246)

**PR Stack (Reduce Admin API usage in Bigtable Data ITs):**
1. **googleapis#15246 (This PR)** — Shared Data IT resource setup
(`scripts/setup-test-table.sh`) and lazy `CloudEnv` admin clients
2. googleapis#15247 — Mechanical swap to shared `AuthorizedView` across 7 Data ITs
3. googleapis#15248 — Shared `MaterializedView`, `ExecuteQueryIT` (`cf_history` +
`SchemaBundle`), and `LargeRowIT` bounded scans

---

Lay the non-behavioral foundation for moving Data integration tests
(`com.google.cloud.bigtable.data.v2.it.*`) onto pre-provisioned shared
resources:

- **`scripts/setup-test-table.sh`**: Document and idempotently provision
all shared Data IT resources for
`projects/<project>/instances/<instance>/tables/<table>`:
- Column families `cf` (`maxversions=1 || maxage=1h`) and `cf_history`
(`maxversions=10 || maxage=1h`, for multi-version SQL `with_history`
queries).
- `AuthorizedView` `test-authorized-view` (`SubsetView` over row prefix
`row#` and `cf` qualifier prefix `qualifier`).
- `MaterializedView` `<table>-mv` (`SELECT _key, MAX(cf['column']) AS
column FROM <table> GROUP BY _key`).
- `SchemaBundle` `test-schema-bundle` (protobuf `FileDescriptorSet`
compiled from `singer.proto` and `album.proto`).
- **`AbstractTestEnv` / `EmulatorEnv` / `CloudEnvTest`**: Expose
`getHistoryFamilyId()`, `getAuthorizedViewId()`,
`getMaterializedViewId()`, and `getSchemaBundleId()` matching
`scripts/setup-test-table.sh`.
- **`CloudEnv`**: Lazily initialize `tableAdminClient` and
`instanceAdminClient` so pure-data IT forks do not open unused Admin
gRPC channels.
- **`SampleRowsIT#testOnAuthorizedView`**: Use `PrefixGenerator` for the
temporary `AuthorizedView` ID and wrap resource cleanup in `try /
finally`.
Remove the unused and previously disabled `scorecard.yml` workflow.

Fixes googleapis#11792
b/587916525
…ge-nio-ci (googleapis#15196)

Cache Temurin JDK 8 and upgrade `actions/setup-java` to `v5.4.0` in
`java-storage-nio-ci.yaml` to avoid transient JDK 8 download failures.

b/588462105
…ActiveListener (googleapis#15284)

Disable flaky `ITQueryWatchTest.shutdownNowTerminatesActiveListener`
with `@Ignore` while tracked for a root-cause fix.

b/580634330
…edentials and UserCredentials (googleapis#15245)

Updates OAuth2 token refresh and JSON loading for non-default universe
domains:

- Rejects `ServiceAccountCredentials.refreshAccessToken()` when
`getUniverseDomain()` is not `googleapis.com`, since OAuth2 token
exchange is only supported in `googleapis.com`, and clarifies in Javadoc
that `refreshAccessToken()` only applies to the OAuth2 access token flow
(not self-signed JWT authentication).
- Rejects `authorized_user` JSON with a non-default `universe_domain` in
`UserCredentials.fromJson()`, and rejects `UserCredentials` refreshes
whenever `getUniverseDomain()` is not `googleapis.com`.
- Updates two pre-existing custom-universe CAB unit tests
(`ClientSideCredentialAccessBoundaryFactoryTest.fetchIntermediateCredentials_withCustomUniverseDomain`
and
`DownscopedCredentialsTest.refreshAccessToken_withCustomUniverseDomain`)
to use a custom-universe `GoogleCredentials` stub. Those two tests
previously constructed a non-default-universe
`ServiceAccountCredentials` and called `refreshAccessToken()` on it, so
updating them here keeps CI green. All CAB production changes and new
CAB tests live in the stacked follow-up PR googleapis#15172.
…lientSideCredentialAccessBoundaryFactoryTest (googleapis#15249)

Synchronize `refreshCredentialsIfRequired_asyncSingleThread` and
`refreshCredentialsIfRequired_asyncMultiThread` with `CountDownLatch`
and remove `Thread.sleep` to eliminate timing flakiness.

Fixes googleapis#12575
b/590334802
…#15247)

**PR Stack (Reduce Admin API usage in Bigtable Data ITs):**
1. googleapis#15246 — Shared Data IT resource setup
(`scripts/setup-test-table.sh`) and lazy `CloudEnv` admin clients
2. **googleapis#15247 (This PR)** — Mechanical swap to shared `AuthorizedView`
across 7 Data ITs
3. googleapis#15248 — Shared `MaterializedView`, `ExecuteQueryIT` (`cf_history` +
`SchemaBundle`), and `LargeRowIT` bounded scans

---

Replace per-test `createAuthorizedView` and `deleteAuthorizedView` calls
across the 7 Data integration test classes (11 test methods:
`BulkMutateIT`, `BulkReadIT`, `CheckAndMutateIT`, `MutateRowIT`,
`ReadIT`, `ReadModifyWriteIT`, and `RowMutationEntryBatcherIT`) with the
pre-provisioned `test-authorized-view` from
`AbstractTestEnv#getAuthorizedViewId()`.

- Eliminates 22 `TableAdmin` mutations per Data IT job run.
- Fixes an `AuthorizedView` leak when tests fail mid-execution
(previously view IDs used raw UUIDs without `finally`, which
`StaleResourceCleaner` could not identify).
…googleapis#15028)

## Summary

Converges the PR `lint` formatter (`fmt-maven-plugin`) with the
`librarian generate` formatter (`google-java-format` CLI) so long string
literals are reflowed consistently before PRs are merged to `main` (see
googleapis#14862, googleapis#14896). Passing `--skip-reflowing-long-strings` in Librarian
instead would lead to more generated code changes and use non-standard
behavior of `google-java-format`, so aligning `fmt-maven-plugin` in
`java-shared-config` with the standard `google-java-format` default is
preferred.

## Changes

- Bumps `com.spotify.fmt:fmt-maven-plugin` from `2.25` to `2.29` in
`java-shared-config/java-shared-config/pom.xml`.
- Sets `<skipReflowingLongStrings>false</skipReflowingLongStrings>` so
`StringWrapper.wrap` is executed, matching the default behavior of the
`google-java-format` CLI.
- Keeps `google-java-format` explicitly pinned to
`${google-java-format.version}` (`1.25.2`), so Librarian does not need
any version change.

## Follow-up Work

Formatting updates for pre-existing non-complying modules are separated
out into follow-up PRs so this `java-shared-config` update can land
cleanly without triggering unrelated downstream test suites:

- **11 handwritten modules (85 files):**
- `sdk-platform-java`: `gapic-generator-java` (10), `gax` (8),
`gax-grpc` (1), `google-cloud-core` (3), `google-cloud-core-http` (1)
  - `java-bigquery/google-cloud-bigquery` (13)
  - `java-bigquery-jdbc` (24)
  - `java-spanner-jdbc` (21)
  - `java-storage-nio/google-cloud-nio` (2)
  - `grpc-gcp-java` (1)
  - `java-logging-logback` (1)
- **3 `protoc`-generated modules (15 files, not to be formatted
directly):**
- `java-datamanager/proto-data-manager-v1` (11),
`java-marketingplatformadminapi/proto-admin-v1alpha` (2), `java-grafeas`
(2)
- `google-java-format` `1.25.2` is not idempotent on `protoc`'s
`descriptorData` strings (`librarian generate --all` runs a single pass
matching what is on `main`, while a second pass modifies them again).
`.kokoro/build.sh` currently excludes `proto-google-*` rather than
`proto-*`, so those exclusions may need a follow-up before
`java-shared-config` is bumped downstream.

Context: b/581031020
…oogleapis#15271)

## Problem Statement
- Streaming read/query resumption and `BatchWrite` retry policies
implemented server `RetryInfo` parsing, retry delay clamping,
exponential backoff, and retry-budget enforcement separately, leading to
inconsistent behavior across Cloud Spanner streaming RPCs.
- Oversized server `RetryInfo` delays were not clamped for `BatchWrite`,
zero `RetryInfo` delays did not fall back to exponential backoff,
malformed `RetryInfo` trailers could throw during `RESOURCE_EXHAUSTED`
translation, sub-millisecond total timeouts on streaming reads/queries
truncated to unlimited, and large `maxRpcTimeoutDuration` values could
overflow when computing `BatchWrite` attempt timeouts.

## Solution
- Unified retry delay extraction, sanitization, clamping, exponential
backoff, and attempt/timeout budget checks across streaming
reads/queries and `BatchWrite` while keeping per-RPC `RetrySettings`
configurations completely independent.
- Clamped positive server `RetryInfo` delays (`> 0`) to `[minDelay,
maxRetryDelayDuration]` (defaulting the cap to `32s` when unset,
preserving positive sub-millisecond delays for `BatchWrite`, and
flooring them at `1ms` for streaming reads/queries), while falling back
to exponential backoff on absent, malformed, zero, or negative server
retry delays.
- Hardened `RetryInfo` trailer and error-details parsing so malformed
payloads never crash exception translation or retry evaluation, while
preserving `SpannerException#getRetryDelayInMillis()` return values for
valid durations (malformed payloads now return `-1` instead of
throwing).
- Unified client-side exponential backoff on `[0.5x, 1.0x]` full-band
jitter (lowering mean default streaming read/query backoff from `1.0x`
to `0.75x` while ensuring backoff never exceeds `maxRetryDelayDuration`)
and enforced nanosecond-precision total timeouts and overflow-safe RPC
timeout saturation.
…oogleapis#15261)

## Problem Statement
- Built-in Cloud Monitoring metrics were previously backed by a single
process-wide provider shared across all Spanner clients in a JVM.
- Applications running multiple Spanner clients in the same JVM with
different credentials, monitoring endpoints, or universe domains could
not isolate built-in metrics export per client, causing all clients to
export through the first client's Cloud Monitoring exporter and fallback
project.
- Built-in metrics exporters were also not shut down when
`Spanner.close()` was called.

## Solution
- Add per-client built-in Cloud Monitoring metrics support by scoping
the metrics provider to each `SpannerOptions` / `Spanner` client so each
client exports using its own credentials, monitoring endpoint, universe
domain, fallback project, and unique `client_uid`.
- Close each client's built-in metrics exporter during `Spanner.close()`
with a bounded final flush (up to 10 seconds on `Spanner.close()`, or
within the caller's remaining timeout on bounded close), while resetting
state cleanly so reusing `SpannerOptions.getService()` after closing
creates a fresh exporter.
@lqiu96
lqiu96 force-pushed the docs/gax-0b-urls-tags branch from 707bae8 to 60ee626 Compare November 30, 2026 19:51
@lqiu96

lqiu96 commented Nov 30, 2026

Copy link
Copy Markdown
Owner Author

Moved upstream to googleapis#15286 (with com.google.longrunning/package-info.java branched out separately)

@lqiu96 lqiu96 closed this Nov 30, 2026
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.