Repository navigation
feat(grpc-gcp): add built-in channel_count metric for client library pools - #14947
Conversation
…pools
Adds an internal option that lets a Google Cloud client library report the
number of channels in each grpc-gcp pool to its built-in metrics pipeline, as
`channel_pool.channel_count`. Spanner will use it to report
`spanner.googleapis.com/internal/client/channel_pool/channel_count`.
Nothing changes unless the new option is set. No client library sets it yet;
the Spanner change that turns it on is a follow-up.
How it works:
- `GcpMetricsOptions.Builder#withBuiltInMetrics(Meter, Attributes)` sets the
meter of the built-in pipeline and the attributes of the pool (for example
the network path). It is separate from `withOpenTelemetryMeter`, which keeps
sending the existing pool metrics to the application's own OpenTelemetry.
- Every pool configured with the same meter joins one process-wide reader.
The reader registers a single asynchronous up-down counter and, at each
collection, reads the size of every live pool's active and draining channel
lists and adds them up by attributes (caller attributes plus `pool_mode` and
`state`). Several pools with the same attributes add up instead of
overwriting each other, and the value cannot drift because it is read from
the pools each time.
- A pool leaves the reader on shutdown. Pools are held weakly, so a pool that
is never shut down does not stay reachable because of the metric.
- Channels that are still being primed are not counted until they join the
pool.
- `GcpMetricsOptions.nextBuiltInMetricsPoolIndex()` returns a process-wide
pool index ("1" to "10", then "other", never reused). A client library calls
it once per client and passes the same value to all of that client's pools.
All new public methods are `@InternalApi`. Nothing is added to the request
path: the reader runs only at metric collection time.
Tests: 21 new tests in `GcpChannelPoolBuiltInMetricsTest`, covering static and
dynamic pools (scale-down, drain, scale-up after priming, on-demand growth),
adding up across pools, separate lanes, shutdown, one reader per meter
(including concurrent pool creation), no change when the option is not set,
the application's metrics and the built-in metric staying separate, the
DirectPath fallback channel's own metrics still being reported, the pool index
helper, 1,000 pools created and closed, and pools joining and leaving during
collection.
There was a problem hiding this comment.
Code Review
This pull request introduces process-wide built-in channel pool metrics for Google Cloud client libraries, allowing tracking of active and draining channel counts. It adds the GcpChannelPoolBuiltInMetrics class, integrates it with GcpManagedChannel, exposes configuration options in GcpManagedChannelOptions, and includes comprehensive unit tests. The review feedback highlights two important concurrency and visibility issues: first, addBuiltInChannelCounts accesses thread-unsafe collections without synchronization, which could lead to data races or ConcurrentModificationException; second, the builtInMetrics field should be marked volatile to guarantee proper visibility across threads during shutdown.
Sets the pool's built-in metrics reader and attributes once in the constructor and marks them final, so every thread that later shuts the pool down is guaranteed to see them.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces process-wide built-in metrics for GCP channel pools via the new GcpChannelPoolBuiltInMetrics class, integrating it with GcpManagedChannel and GcpManagedChannelOptions to track active and draining channel counts. Feedback on these changes suggests protecting the addBuiltInChannelCounts method in GcpManagedChannel with an explicit lock to ensure thread safety and memory visibility. Additionally, in the newly added test suite, the meterProvider should be properly closed during teardown to prevent resource leaks.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces process-wide built-in metrics for channel pools, tracking active and draining channel counts via a new GcpChannelPoolBuiltInMetrics class and integrating it with GcpManagedChannel and GcpManagedChannelOptions. A potential concurrency issue was identified in GcpManagedChannel.addBuiltInChannelCounts, where channelRefs.size() and removedChannelRefs.size() are accessed without synchronization. It is recommended to maintain these counts using atomic variables to ensure thread safety and avoid lock contention during metric collection.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces process-wide built-in metrics for Google Cloud client libraries to track active and draining channel counts in channel pools. It adds the GcpChannelPoolBuiltInMetrics class, integrates it with GcpManagedChannel and its options, and includes a comprehensive test suite. Feedback on the changes highlights a potential data race in addBuiltInChannelCounts when accessing channel lists without synchronization, suggesting the use of atomic variables to avoid lock contention on the critical path.
poolsCreatedConcurrentlyShareOneReader creates pools from 8 threads, and each pool is added to the shared pools list. A plain ArrayList can lose an entry or throw when several threads add at the same time, so a pool could be skipped by tearDown. Use a CopyOnWriteArrayList, as other grpc-gcp tests do.
The pool index was passed inside the pool attributes, so it would be added to every built-in channel pool metric. It belongs only on channel_count: a per-request metric keyed by pool index would keep re-sending a closed pool's frozen series. Add GcpMetricsOptions.Builder#withBuiltInMetricsPoolIndex. The pool adds the pool_index attribute to channel_count only, and the value overrides a pool_index the caller put in the pool attributes.
olavloite
left a comment
There was a problem hiding this comment.
The logic looks good to me, but I left a few comments on the comments/documentation and code structure.
| } | ||
| Map<Attributes, Long> totals = new HashMap<>(); | ||
| for (GcpManagedChannel pool : snapshot) { | ||
| pool.addBuiltInChannelCounts(totals); |
There was a problem hiding this comment.
I think that pool (theoretically) could be null here due to the use of WeakHashMap. When you create the snapshot, the constructor of ArrayList loops over the keys in the WeakHashMap and then gets the value from that key, and (relatively theoretically) the value could be GCed between the time that the key was gotten, and the time that the value was looked up using the key. So to be 100% sure, it would be better to add a null-check here for pool.
There was a problem hiding this comment.
Done, added the null check.
| builtInMetrics = GcpChannelPoolBuiltInMetrics.forMeter(builtInMeter); | ||
| // Joining happens under the reader's lock, which makes the attributes above visible to the | ||
| // metric collection thread. | ||
| builtInMetrics.add(this); |
There was a problem hiding this comment.
Strictly speaking, it would be better to move this line down to the last line of the constructor to ensure that the channel is only added to the collection if the constructor actually finishes successfully.
There was a problem hiding this comment.
Done, it is now the last step of the constructor.
|
|
||
| @Test | ||
| public void poolIndexCountsUpToTenThenReportsOther() { | ||
| GcpChannelPoolBuiltInMetrics.resetPoolIndexForTest(); |
There was a problem hiding this comment.
It would probably be better to move this call to the @After method for this test class to ensure that it is called for all tests. This then also ensures that there are no tests that 'by chance' pass because it is not reset.
There was a problem hiding this comment.
Done, moved it to tearDown.
| * <p>There is one instance per built-in metrics {@link Meter}. Every pool configured with that | ||
| * meter joins it, and a single callback, registered once, reads the active and draining channel | ||
| * counts of all live pools whenever metrics are collected. Counts of pools with the same attributes | ||
| * are added up, so several pools in one process are reported correctly. Reading the real pool sizes | ||
| * at collection time means the values cannot drift. |
There was a problem hiding this comment.
Can we make this comment a bit easier to read. Maybe something like this:
* <p>Process-wide singleton reader of built-in channel pool metrics for a {@link Meter}. All
* channel pools configured with that meter register with this shared instance (retrieved via
* {@link #forMeter(Meter)}).
*
* <p>Whenever metrics are collected, a single callback samples the current sizes of the active
* and draining channel lists across all registered pools. Channel counts from pools with identical
* attributes are summed together so they do not overwrite each other. Reading the live collections
* directly on each export—rather than maintaining an incremental running counter—guarantees that
* reported counts never desynchronize from the actual number of channels.| /** | ||
| * Returns the next pool index for this process: "1" to "10" in order, then "other". Indexes are | ||
| * never reused, so the data of a closed pool is never mixed with a newer pool. The cap keeps the | ||
| * number of time series bounded for applications that create many clients. | ||
| */ |
There was a problem hiding this comment.
| /** | |
| * Returns the next pool index for this process: "1" to "10" in order, then "other". Indexes are | |
| * never reused, so the data of a closed pool is never mixed with a newer pool. The cap keeps the | |
| * number of time series bounded for applications that create many clients. | |
| */ | |
| /** | |
| * Returns a process-unique pool index: sequentially from "1" to "10", and "other" thereafter. | |
| * | |
| * <p>Indices are never reused. Capping the index bounds metric cardinality in Cloud Monitoring | |
| * when applications create multiple channel pools. | |
| */ |
| // Channel pool metrics for the built-in metrics pipeline of a Google Cloud client library. Null | ||
| // when not configured. Set once in the constructor. |
| unresponsiveDropCount = 0; | ||
| } | ||
| initChannels(); | ||
| // The built-in metric fields are final, so every thread that later uses this pool (for |
There was a problem hiding this comment.
Can we split this constructor into smaller parts to make it a bit easier to read? Something like this:
In GcpManagedChannel.java, lines 452–483 currently inline ~32 lines of OpenTelemetry attribute construction in the middle of the constructor, and then call builtInMetrics.add(this) before channelPoolOptions (cleanup tasks, scale-down checker) are initialized.
If an unexpected exception occurs after add(this), a partially initialized channel remains registered in builtInMetrics and will report phantom active channels until GC runs, without the caller ever having received a reference to shut it down.
We can keep final semantics and clean up the constructor by bundling the three fields into a small private static holder class:
private static class BuiltInMetrics {
final GcpChannelPoolBuiltInMetrics reader;
final Attributes activeAttributes;
final Attributes drainingAttributes;
BuiltInMetrics(
GcpChannelPoolBuiltInMetrics reader,
Attributes activeAttributes,
Attributes drainingAttributes) {
this.reader = reader;
this.activeAttributes = activeAttributes;
this.drainingAttributes = drainingAttributes;
}
}Then in GcpManagedChannel:
- Replace the three fields with a single final field:
@Nullable private final BuiltInMetrics builtInMetrics;
- Extract the attribute-building logic into a static helper method:
@Nullable private static BuiltInMetrics initBuiltInMetrics( GcpManagedChannelOptions options, boolean isDynamicScalingEnabled) { GcpMetricsOptions metricsOptions = options.getMetricsOptions(); Meter builtInMeter = metricsOptions == null ? null : metricsOptions.getBuiltInMetricsMeter(); if (builtInMeter == null) { return null; } AttributesBuilder countAttributes = metricsOptions.getBuiltInMetricsAttributes().toBuilder() .put( GcpMetricsConstants.POOL_MODE_LABEL, isDynamicScalingEnabled ? GcpMetricsConstants.POOL_MODE_DYNAMIC : GcpMetricsConstants.POOL_MODE_STATIC); String poolIndex = metricsOptions.getBuiltInMetricsPoolIndex(); if (poolIndex != null) { countAttributes.put(GcpMetricsConstants.POOL_INDEX_LABEL, poolIndex); } Attributes poolAttributes = countAttributes.build(); Attributes activeAttributes = poolAttributes.toBuilder() .put(GcpMetricsConstants.STATE_LABEL, GcpMetricsConstants.STATE_ACTIVE) .build(); Attributes drainingAttributes = poolAttributes.toBuilder() .put(GcpMetricsConstants.STATE_LABEL, GcpMetricsConstants.STATE_DRAINING) .build(); return new BuiltInMetrics( GcpChannelPoolBuiltInMetrics.forMeter(builtInMeter), activeAttributes, drainingAttributes); }
- The constructor reduces to:
this.builtInMetrics = initBuiltInMetrics(options, isDynamicScalingEnabled); ... // At the very end of the constructor: if (this.builtInMetrics != null) { this.builtInMetrics.reader.add(this); }
This prevents this from escaping prior to full construction and cuts 30+ lines of clutter out of the channel pool constructor.
There was a problem hiding this comment.
Done, moved this into a small holder class and a static helper as you suggested. The pool now joins the reader as the last step of the constructor.
| @@ -2678,6 +2728,9 @@ private String keyFromOptsCtx(CallOptions callOptions) { | |||
|
|
|||
| private synchronized List<GcpChannelPrimeController.PendingPrime> cancelBackgroundTasks() { | |||
There was a problem hiding this comment.
nit: should we consider renaming this method to something like cleanupOnShutdown to better reflect what it does?
There was a problem hiding this comment.
Makes sense, renamed it to cleanupOnShutdown.
| /** | ||
| * Returns the next value for the pool index attribute of the built-in channel pool metrics: "1" | ||
| * to "10" in creation order, then "other". Values are unique within the process and never | ||
| * reused. A client library that creates several pools for one client (for example one per | ||
| * network path) should call this once per client and pass the same value to all of its pools. | ||
| */ |
There was a problem hiding this comment.
Hmm.... reading this comment makes me think that I might have misunderstood some of this implementation. If a client should assign the same pool index to all of its pools, then this is maybe technically speaking not a pool_index, but a client_index? And this might then also render one of my previous comments slightly wrong, as I assumed that a client that creates multiple pools, should assign them different pool indexes.
Should we then consider renaming this to client_index? And also make clear that if a client creates multiple pools and assigns them the same client_index (or pool_index), then they should normally assign them a different value for at least one other property (e.g. lane).
There was a problem hiding this comment.
Good point. Without DirectPath fallback a Spanner client has one pool, so the two are the same. With fallback the DirectPath and CloudPath pools act as one pool split by lane, so they share the index and lane tells them apart. I'm thinking of keeping pool_index, since client_index might be confused with the existing client_uid and client_name labels, and pool_index is already in the Monarch config that is live. I added your sentence that pools sharing an index must differ in another attribute such as lane.
| /** | ||
| * Sets the pool index that is added as the {@code pool_index} attribute to the built-in | ||
| * channel count metric of this pool. Use {@link | ||
| * GcpMetricsOptions#nextBuiltInMetricsPoolIndex()} to get a value. The pool index is not | ||
| * added to the other built-in channel pool metrics. | ||
| * | ||
| * <p>This is not intended for application use. | ||
| * | ||
| * @param poolIndex the pool index, or null to leave it out. | ||
| */ |
There was a problem hiding this comment.
Can you scrutinize this comment a bit: When would you want to 'leave it out'? What are the other built-in channel pool metrics?
There was a problem hiding this comment.
channel_count is the only built-in metric for now, so I removed the part about other metrics. Null is just the default when a library does not set an index, and channel_count is then reported without a pool_index attribute. I reworded the javadoc to say that.
Move the built-in metric state into a small holder built by a static helper, and join the reader as the last step of the constructor. Rename cancelBackgroundTasks to cleanupOnShutdown, reset the pool index in tearDown, and update the javadoc.
…ools (#14985) Adds the second built-in channel pool metric, `channel_pool.channel_load`. Spanner will report it as `spanner.googleapis.com/internal/client/channel_pool/channel_load`. Each time a call starts on a channel, the pool records the number of calls in flight on that channel, including the new call, in a histogram. Nothing changes unless built-in metrics are configured with `GcpMetricsOptions.Builder#withBuiltInMetrics` (added in #14947). No client library sets it yet. The Spanner change that turns it on is a follow-up. How it works: - Both call paths in `GcpClientCall` record the value right after the underlying call is created, so a call that cannot be created is not recorded. `ChannelRef#activeStreamsCountIncr()` now returns the channel's new count, which is the recorded value. Error penalties are not included. If recording throws, the error is logged at FINE and the call goes on as normal. - Attributes are the pool attributes passed to `withBuiltInMetrics` (for example `lane`) plus `pool_mode`. `state` is left out, and so is the value set with `withBuiltInMetricsPoolIndex`. A histogram series is never removed, so a series per pool index would keep being exported after its pool is closed. - A new `@InternalApi` call option, `GcpManagedChannel.BUILT_IN_METRICS_ATTRIBUTES_KEY`, lets a client library add attributes per call. Spanner will use it for `database`. The pool's own attributes take precedence over call attributes with the same key. Each pool caches the combined attributes for up to 100 different call attribute sets. Calls with other sets are still recorded, and their attributes are combined on each call. - Buckets: 1, 2, 3, 5, 8, 12, 16, 20, 25, 30, 40, 50, 75, 100, 150, 200. They are finer at the low end, where most pools run, and the step between boundaries never gets smaller. The value is always at least 1, because it includes the new call. - Pools that use the same meter record into the same series for the same attributes. Measured per call (JMH, 2 forks x 8 x 1s, -prof gc, n2-standard-8 GCE VM, JDK 17), fake channels, so client CPU only. Each channel_load row is the extra cost compared with the same run without built-in metrics: ``` 1 thread 8 threads channel_load, 10 databases +38 ns, 0 B +141 ns, 0 B channel_load, 1,000 databases +312 ns, +281 B +353 ns, +281 B channel_load, no database attribute +34 ns, 0 B +991 ns, 0 B existing Spanner built-in metrics 4,850 ns, 5,400 B 9,932 ns, 5,400 B ``` - 10 databases: all attribute sets are cached. - 1,000 databases: only 100 sets fit in the cache, so most calls combine the attributes again. - No database attribute: all 8 threads record into one series, and they wait for each other on the lock that every OpenTelemetry histogram series takes on each record. - The last row is what a successful unary Spanner RPC records today (attempt and operation latency and count, GFE latency) in the same setup. Tests: 25 new tests in `GcpChannelPoolChannelLoadTest`, covering the recorded value, buckets and unit, attributes (`pool_mode`, no `pool_index` or `state`, per-call attributes that cannot override pool attributes), the attribute cache limit (also under concurrency), every call path (least busy, sticky, affinity config, draining channel, on-demand channel, call that cannot be created), a failing record that must not fail the call or leave the channel's count raised, error penalties not included, the load going down after calls finish, 8 x 1,000 concurrent calls, DirectPath fallback moving the load to the cloudpath lane, and the application's metrics staying separate.
🤖 I have created a release *beep* *boop* --- <details><summary>1.97.0</summary> ## [1.97.0](v1.96.0...v1.97.0) (2026-11-12) ### ⚠ BREAKING CHANGES * **shopping-merchant:** remove discontinued Merchant API v1beta ([#14942](#14942)) ### Features * **bigquery-jdbc:** adds BigQuery graph integration to DatabaseMetadata methods ([#14930](#14930)) ([950b81b](950b81b)) * **gax:** implement resumable upload session resumption ([#14677](#14677)) ([24728d6](24728d6)) * **grpc-gcp:** add built-in channel_count metric for client library pools ([#14947](#14947)) ([712f043](712f043)) * **grpc-gcp:** add built-in channel_load metric for client library pools ([#14985](#14985)) ([9f87888](9f87888)) * **shopping-merchant:** remove discontinued Merchant API v1beta ([#14942](#14942)) ([2947dfd](2947dfd)) * **storage:** add StorageErrorTypeMapper for standard metrics ([#14694](#14694)) ([a9ac393](a9ac393)) * **storage:** add StorageMetricsContext for operation metrics state ([#14728](#14728)) ([edea395](edea395)) * **storage:** wire logical operation metrics in Retrying and StorageOptions ([#14695](#14695)) ([589c66c](589c66c)) * update API sources and regenerate ([#14958](#14958)) ([75944f3](75944f3)) ### Bug Fixes * **auth:** verify public/private key match with retries in mTLS keystore loading ([#14829](#14829)) ([096dbd6](096dbd6)) * **bigquery:** set QueryResultsFormat.ARROW in QueryArrow sample ([#14960](#14960)) ([c98e7c3](c98e7c3)) * **bigtable:** avoid triggering per-RPC credential session fallback on default call context ([#14961](#14961)) ([eb06d2c](eb06d2c)) * **bigtable:** copy Metadata per GetClientConfiguration call ([#14950](#14950)) ([278fe2f](278fe2f)) * **bigtable:** disable SwitchingChannelPool when ChannelPoolConfiguration is empty ([#14911](#14911)) ([fa24702](fa24702)) * **bigtable:** handle empty SessionPoolConfiguration in SessionPoolImpl and PoolSizer ([#14912](#14912)) ([cc7b235](cc7b235)) * **bigtable:** replace SessionPoolImpl Watchdog with per-session closeTimeout ([#14977](#14977)) ([a15acfb](a15acfb)) * **spanner-jdbc:** report database default isolation level ([#14929](#14929)) ([7e7595a](7e7595a)) * **spanner:** fix PG SHOW isolation level statements ([#14904](#14904)) ([bc917ed](bc917ed)) ### Dependencies * bump grpc to 1.85.1, opentelemetry to 1.67.0, and guava to 33.7.2-jre ([#14957](#14957)) ([1a27a00](1a27a00)) * bump guava to 33.7.1-jre and jspecify to 1.0.1 ([#14937](#14937)) ([1441527](1441527)) ### Documentation * **spanner:** update CHANGELOG.md for java spanner releases ([#14935](#14935)) ([956681e](956681e)) * **storage:** add Rapid Cache samples ([#14886](#14886)) ([e714f62](e714f62)) </details> --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --------- Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com>
This turns on the two channel pool metrics that grpc-gcp gained in #14947 and #14985 and sends them to Cloud Monitoring as Spanner built-in metrics. ## What is reported - `channel_pool/channel_count`: the number of channels in the data pool per state (`active`, `draining`), with the labels `lane`, `pool_mode` and `pool_index`. The instance is reported as `unknown` because one pool serves many databases and instances, the same as the existing eef metrics. The project is the built-in metrics fallback project. - `channel_pool/channel_load`: for each call, the number of calls that are open on the chosen channel, as a histogram with the boundaries 1, 2, 3, 5, 8, 12, 16, 20, 25, 30, 40, 50, 75, 100, 150, 200. `project_id`, `instance_id` and `database` come from the resource name of the request, `lane` and `pool_mode` come from the pool. ## Which pools report - Only the main data pool. The instance admin and database admin stubs now get their own channel provider with these metrics off. They already had their own pools, so this does not add channels. - With DirectPath fallback, the DirectPath pool and the CloudPath pool both report under one `pool_index` and are told apart by `lane`. - The experimental fallback recovery layout reports without `lane`, because its channels switch between the two paths. ## When nothing is reported - The application sets its own channel provider, grpc-gcp is disabled, built-in metrics are disabled, the client uses no credentials, the emulator is used, or `SPANNER_DISABLE_CHANNEL_POOL_BUILTIN_METRICS=true`. - Application settings cannot change these metrics. Spanner always overwrites the built-in metrics settings in the grpc-gcp options and adds the per-call labels after the `CallContextConfigurator`s of the application. ## Cost - `channel_count` adds nothing per call. - `channel_load` adds one cached lookup of the resource name per call and carries the labels in the call options. Recording the value was measured in #14985 at about 38 ns per call with one thread, and up to about 1 µs per call when 8 threads write the same series at the same time. ## Testing - `GapicSpannerRpcTest` and `SpannerMetadataProviderTest` for the options and the resource name parsing. `ChannelPoolBuiltInMetricsTest` runs a client against the mock server and checks that only the data pool reports, the lanes of the DirectPath fallback pools, the fallback recovery layout without `lane`, the switches that turn the metrics off, that application settings cannot change the metrics, and the labels and boundaries of `channel_load`. - End to end on a GCE VM against a real database, with the exported data checked afterwards: CloudPath and DirectPath clients, a static pool, a dynamic pool that scaled up from 4 to 8 channels and down from 8 to 6 (with 2 draining), two clients in one process (`pool_index` 1 and 2), two databases, and the long-term series.
…r the dynamic channel pool (#20923) ## Summary The dynamic channel pool now reports two metrics to Spanner's built-in Cloud Monitoring pipeline: how many channels it has, and how busy a channel is when a call starts on it. `channel_count` - Metric: `spanner.googleapis.com/internal/client/channel_pool/channel_count` (INT64, sent as a GAUGE) - Two points per pool: `state=active` (channels in the pool) and `state=draining` (channels being removed after a scale-down) - Labels: `pool_mode=dynamic` and `lane` `channel_load` - Metric: `spanner.googleapis.com/internal/client/channel_pool/channel_load` (DISTRIBUTION, cumulative) - One value per call attempt (a retry is recorded again): the number of calls in flight on the channel the call starts on, including that call - Buckets: 1, 2, 3, 5, 8, 12, 16, 20, 25, 30, 40, 50, 75, 100, 150, 200 - Labels: `pool_mode=dynamic` and `lane` `lane` is `directpath` when DirectPath is enabled, else `cloudpath`. With DirectPath fallback enabled (#20651), it changes to `cloudpath` once the pool has switched to CloudPath. For both metrics the exporter adds `client_uid`, `client_name` and `database` as it does for every built-in metric. The Monarch and Cloud Monitoring metric descriptors are already live. Java reports the same metrics (googleapis/google-cloud-java#14947, googleapis/google-cloud-java#14985). ## How it works - `channel_count`: an observable up-down counter on the built-in meter provider (meter `gax-go`). It is registered once the pool has been created. A callback reads the pool's active channel count and draining counter once per export (every 60 s). - `channel_load`: a histogram on the same meter. The pool core lives in `internal/transport` (#20919), so this PR adds an optional `OnCallStart` hook to `transport.DCPHooks`. The pool calls it right after it adds a call to a channel's in-flight count, in the four places where it does that (pool `Invoke` and `NewStream`, and the entry's unary and streaming starts), with that channel's in-flight count. The Spanner side sets the hook only when the histogram was created. Fixed-mode pools return before that point, so they never call it. - `lane`: both label sets are built once per pool. If the pool has a DirectPath fallback, each export and each recording checks the fallback state and uses the `cloudpath` set after the switch. This adds no allocations. - The two metrics are set up independently, so a failure to create one does not disable the other. - The callback is unregistered when the pool closes, in the pool's `OnClose` hook next to closing the fallback state. `Client.Close` flushes the built-in metrics before it closes the pool, so the final values are still sent. As for every built-in metric, this last flush is skipped if the previous export was 30 s ago or less. - The metrics are only sent to Cloud Monitoring. They are not recorded on `OpenTelemetryMeterProvider` or `ClientMetricsProvider`. - `pool_mode`, `state` and `lane` are added to the exporter's label allow-list. ## When it is not reported - Built-in metrics are off (emulator, `DisableNativeMetrics`, `SPANNER_DISABLE_BUILTIN_METRICS=true`, Omni, experimental host) - `SPANNER_DISABLE_CHANNEL_POOL_BUILTIN_METRICS=true` (same switch name as Java, turns off both metrics) - The dynamic channel pool is not turned on. Since #20669, these clients run on the same pool code in fixed mode (a fixed number of channels, no scaling up or down). Fixed-mode pools do not report these metrics yet. A follow-up will add them with `pool_mode=static`. ## Tests - `internal/transport/dcp_test.go`: `OnCallStart` is called with the right in-flight count on each of the four call paths, under concurrent calls, and never on a fixed-mode pool. - `channel_pool_metrics_test.go`: active and draining counts, scale-up, the DirectPath lane, `lane` switching to `cloudpath` after a DirectPath fallback switch, the off switch, built-in metrics being off, registration errors (each metric still works when the other fails), collecting while the pool scales, no allocations when recording `channel_load`, and the wiring through `newDynamicChannelPool` (both metrics reported, `channel_count` unregistered when the pool closes). - An end-to-end export through a fake Cloud Monitoring server checks the metric kind, value type, buckets and labels, that existing built-in metrics are still exported, that nothing is sent to the customer meter providers, and that a default (fixed-mode) client sends neither metric. - The full `spanner` and `internal/transport` packages pass with `-race`. ## End-to-end test Ran on a GCE VM (n2-standard-8, us-central1-a) against a real Spanner instance, with a test binary built from this branch (commit 001d996). Five clients ran at the same time for 13 minutes, each on its own database, then a sixth client ran on its own for 15 minutes. | Run | Pool | Result | |---|---|---| | default | fixed mode, 8 threads | No `channel_count` or `channel_load`, as expected | | dcp | dynamic, CloudPath, 150 threads for 3 min then 2 threads for 10 min | `lane=cloudpath`. `active` went 8 → 6 → 4 → 2, `draining=2` at each scale-down and 0 at the end. Mean load about 19 in the busy minutes, 1 to 3 in the quiet minutes | | dp | dynamic, DirectPath, 8 threads | `lane=directpath`. `active` 4, then 2 after the default scale-down | | dynamic, new metrics off | dynamic, CloudPath, 8 threads, `SPANNER_DISABLE_CHANNEL_POOL_BUILTIN_METRICS=true` | No `channel_count` or `channel_load`, as expected | | dynamic, new metrics on | dynamic, CloudPath, 8 threads | `lane=cloudpath`, `active` 4, then 2 after the default scale-down | | DirectPath fallback | dynamic, DirectPath, `GOOGLE_SPANNER_ENABLE_GCP_FALLBACK=true`, 8 threads | DirectPath addresses were blocked on the VM after 4 minutes. The pool switched to CloudPath 5 minutes later, as the fallback rule expects. Both metrics reported `lane=directpath` before the block and `lane=cloudpath` after the switch | - The number of `channel_load` values matched the number of call attempts each client made (within 0.23% per minute). - All existing built-in metrics arrived every minute for every database. For every client, the `operation_count` total matched the number of queries the client counted itself. - About 5.7 million queries. The only failures were the timeouts in the fallback run between the block and the switch. ## Performance Measured on the same VM after the end-to-end test: a full `SELECT 1` through a client with the dynamic pool, against an in-process mock server. | | 1 CPU | 8 CPUs | |---|---|---| | Time per query, new metrics off | 241.8 µs | 51.3 µs | | Time per query, new metrics on | 244.0 µs | 51.8 µs | | **Added by the new metrics** | **2.2 µs (+0.9%)** | **0.5 µs (+0.9%)** | | For scale: added by the existing built-in metrics | 25.9 µs | 3.8 µs | The new metrics add no memory allocations. In a worst-case test with no network at all, recording one `channel_load` value takes about 210 ns on 1 CPU and about 80 ns on 8 CPUs. The live `lane` check adds no measurable time.
Adds an internal option that lets a Google Cloud client library report the
number of channels in each grpc-gcp pool to its built-in metrics pipeline, as
channel_pool.channel_count. Spanner will use it to reportspanner.googleapis.com/internal/client/channel_pool/channel_count.Nothing changes unless the new option is set. No client library sets it yet.
The Spanner change that turns it on is a follow-up.
How it works:
GcpMetricsOptions.Builder#withBuiltInMetrics(Meter, Attributes)sets themeter of the built-in pipeline and the attributes of the pool (for example
the network path). It is separate from
withOpenTelemetryMeter, which keepssending the existing pool metrics to the application's own OpenTelemetry.
The reader registers a single asynchronous up-down counter and, at each
collection, reads the size of every live pool's active and draining channel
lists and adds them up by attributes (caller attributes plus
pool_modeandstate). Several pools with the same attributes add up instead ofoverwriting each other, and the value cannot drift because it is read from
the pools each time.
shutdown. Pools are held weakly, so a pool that is never shut down does not
stay reachable because of the metric.
pool.
GcpMetricsOptions.nextBuiltInMetricsPoolIndex()returns a process-widepool index ("1" to "10", then "other"). A client library calls it once per
client and passes the value with
GcpMetricsOptions.Builder#withBuiltInMetricsPoolIndex(String), which addsit as the
pool_indexattribute onchannel_count. Pools that share a poolindex must differ in at least one other attribute, for example
lane.All new public methods are
@InternalApi. Nothing is added to the requestpath: the reader runs only at metric collection time.
Tests: 24 new tests in
GcpChannelPoolBuiltInMetricsTest, covering static anddynamic pools (scale-down, drain, scale-up after priming, on-demand growth),
adding up across pools, separate lanes, shutdown, one reader per meter
(including concurrent pool creation), no change when the option is not set,
the application's metrics and the built-in metric staying separate, the
DirectPath fallback channel's own metrics still being reported, the pool index
helper and option, 1,000 pools created and closed, and pools joining and
leaving during collection.