Skip to content

impl(storage): add operation-level OTel metrics recorder - #16685

Open
cpriti-os wants to merge 6 commits into
googleapis:mainfrom
cpriti-os:impl-storage-operation-metrics
Open

cpriti-os wants to merge 6 commits into
googleapis:mainfrom
cpriti-os:impl-storage-operation-metrics

Conversation

@cpriti-os

@cpriti-os cpriti-os commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Add storage_internal::OperationMetrics to record operation-scoped OpenTelemetry Storage metrics:

  • gcp.storage.client.operations ({operation} counter)
  • gcp.client.request.duration (s histogram, clamping negative std::chrono::steady_clock::duration values to zero)

Also extracts shared kStorageMeterName, kOperationsMetric, and kRequestDurationMetric constants into google/cloud/storage/internal/metrics_constants.h and references them from metrics_meter_provider.h and metrics_exporter_options.cc so view and Cloud Monitoring name registration stay in sync.

RecordOperation takes OperationLabels, std::chrono::steady_clock::duration, and an explicit opentelemetry::context::Context const& (for trace exemplars across sync, async, and streaming paths), and formats gcp.client.version as bare major.minor.patch. Follow-up PRs wire this recorder into the REST and gRPC connection layers.


Created by cpriti-o11y-agent

@cpriti-os
cpriti-os requested review from a team as code owners November 19, 2026 10:15
@cpriti-os
cpriti-os requested a review from kalragauri November 19, 2026 10:15
@product-auto-label product-auto-label Bot added the api: storage Issues related to the Cloud Storage API. label Nov 19, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request introduces the OperationMetrics class to record operation-scoped OpenTelemetry Storage metrics, along with its corresponding unit tests and build configuration updates. The review feedback suggests optimizing the hot path by caching the client version string and using explicit typing for the context variable instead of auto to align with the style guide. Additionally, it recommends replacing a fragile magic number slice with a dynamic size calculation to improve robustness.

Comment on lines +64 to +76
auto const ctx = opentelemetry::context::RuntimeContext::GetCurrent();
auto const ver = google::cloud::version_string();
std::array<Attr, 9> const attrs{{
{"gcp.client.version", ToNostd(ver)},
{"gcp.client.artifact", "google-cloud-cpp"},
{"gcp.client.service", "storage"},
{"server.address", ToNostd(server_address_)},
{"rpc.system.name", ToNostd(rpc_system_)},
{"gcp.storage.operation", ToNostd(operation)},
{"gcp.client.method", ToNostd(client_method)},
{"error.type", ToNostd(error_type)},
{"rpc.method", ToNostd(rpc_method)},
}};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

To avoid repeated calls to google::cloud::version_string() on the hot path of recording every operation, we should cache the result in a static variable. To prevent static destruction order issues with non-trivial destructors (such as std::string), we should use a function-local static pointer or reference. Also, use the explicit type opentelemetry::context::Context for ctx instead of auto to adhere to the style guide.

  static auto const& version = *new std::string(google::cloud::version_string());
  opentelemetry::context::Context const ctx =
      opentelemetry::context::RuntimeContext::GetCurrent();
  std::array<Attr, 9> const attrs{{
      {"gcp.client.version", ToNostd(version)},
      {"gcp.client.artifact", "google-cloud-cpp"},
      {"gcp.client.service", "storage"},
      {"server.address", ToNostd(server_address_)},
      {"rpc.system.name", ToNostd(rpc_system_)},
      {"gcp.storage.operation", ToNostd(operation)},
      {"gcp.client.method", ToNostd(client_method)},
      {"error.type", ToNostd(error_type)},
      {"rpc.method", ToNostd(rpc_method)},
  }};
References
  1. Reject Obscured Domain & Return Types: Flag and reject auto when it hides StatusOr, domain objects, protobuf messages/fields, or function return types. (link)
  2. To avoid re-computation on each function call, cache the result in a static variable. This one-time cost is often preferable to repeated computation, even for seemingly quick operations.
  3. Avoid using function-local static variables with non-trivial destructors (such as std::vector or std::string) to prevent static destruction order issues, in accordance with the Google C++ Style Guide.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Cached google::cloud::version_string() in a member initialized at construction and replaced auto with opentelemetry::context::Context.


Replied by cpriti-o11y-agent

{"rpc.method", ToNostd(rpc_method)},
}};
if (operations_) {
opentelemetry::nostd::span<Attr const> const op_attrs(attrs.data(), 8);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Using the magic number 8 to slice the attributes array is fragile and can easily break if attributes are reordered or added. Since rpc.method is the last element and is the only one excluded from the operations counter, we can use attrs.size() - 1 to make this more robust and self-documenting.

    opentelemetry::nostd::span<Attr const> const op_attrs(attrs.data(),
                                                          attrs.size() - 1);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Replaced magic 8 with attrs.size() - 1 and added a brief comment explaining that rpc.method is intentionally placed last.


Replied by cpriti-o11y-agent

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.20359% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.76%. Comparing base (6f1c3c3) to head (58c669f).

Files with missing lines Patch % Lines
...e/cloud/storage/internal/operation_metrics_test.cc 98.40% 2 Missing ⚠️
google/cloud/storage/internal/operation_metrics.cc 97.56% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16685      +/-   ##
==========================================
- Coverage   92.78%   92.76%   -0.02%     
==========================================
  Files        2271     2273       +2     
  Lines      227688   227854     +166     
==========================================
+ Hits       211255   211378     +123     
- Misses      16433    16476      +43     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

server_address_(std::move(server_address)),
rpc_system_(std::move(rpc_system)) {
if (!provider) return;
meter_ = provider->GetMeter("gl-cpp", version_);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hardcoding "gl-cpp" here (and "gcp.client.request.duration" below) repeats literals defined in metrics_meter_provider.h and metrics_exporter_options.cc. If either name drifts from the view or formatter registration, gcp.client.request.duration silently loses its explicit latency buckets or Cloud Monitoring name mapping.

Consider defining shared constexpr std::string_view constants under google/cloud/storage/internal/ (as discussed in #16638) and referencing them from both the recorder and the gRPC meter provider.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good call, extracted shared constexpr constants into metrics_constants.h and referenced them from operation_metrics.cc, metrics_meter_provider.h, and metrics_exporter_options.cc.


Replied by cpriti-o11y-agent

double duration_seconds) const {
if (!operations_ && !request_duration_) return;
opentelemetry::context::Context const ctx =
opentelemetry::context::RuntimeContext::GetCurrent();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reading RuntimeContext::GetCurrent() here assumes the operation's trace span is still active on the calling thread. In async continuations like AsyncConnectionTracing::Open and stream destructors like ~TracingObjectReadSource, that span is no longer current, so exemplars are dropped.

Consider accepting an explicit opentelemetry::context::Context const& parameter (or overload), similar to DirectAccessCompatibility::Record and StorageMetricsContext.recordOperation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Great catch for async and streaming paths, updated RecordOperation to accept an explicit opentelemetry::context::Context const& parameter instead of calling RuntimeContext::GetCurrent().


Replied by cpriti-o11y-agent

// `rpc.method` is placed last so `operations_` can exclude it via a prefix
// span of size `attrs.size() - 1`.
std::array<Attr, 9> const attrs{{
{"gcp.client.version", ToNostd(version_)},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Emitting version_ directly in gcp.client.version includes the leading v and optional +build_metadata added by google::cloud::version_string(). Peer SDKs like Go and Java emit bare semantic versions (x.y.z), and custom GOOGLE_CLOUD_CPP_BUILD_METADATA values can inflate label cardinality.

Should we format gcp.client.version without the v prefix or build metadata while keeping google::cloud::version_string() for GetMeter() so StorageMeterScope() still matches?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, formatted gcp.client.version as bare major.minor.patch (no v prefix or build metadata) while keeping google::cloud::version_string() for GetMeter() so StorageMeterScope() still matches.


Replied by cpriti-o11y-agent

ctx);
}
if (request_duration_) {
request_duration_->Record(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Passing a raw double to request_duration_->Record() leaves edge values unguarded. The OpenTelemetry SDK drops negative values (causing operations_ and request_duration_ counts to diverge), while NaN passes the < 0 check and poisons the cumulative histogram sum.

Consider taking std::chrono::steady_clock::duration like MakeChannelMetricsCallback (and clamping negative values to zero), or guarding std::isfinite(duration_seconds) before recording.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Switched RecordOperation to take std::chrono::steady_clock::duration and clamp negative durations to zero before converting to seconds, with a unit test covering negative durations.


Replied by cpriti-o11y-agent


auto dur = std::make_unique<MockHistogram<double>>();
EXPECT_CALL(*dur, Record(DoubleEq(0.5), _, _)).Times(1);
opentelemetry::nostd::shared_ptr<MockMeter> partial_meter =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

partial_meter only tests a null operations_ counter with a non-null request_duration_ histogram, leaving the reverse combination (non-null counter, null histogram) untested. Changing if (!operations_ && !request_duration_) to if (!request_duration_) or dropping the if (request_duration_) guard in operation_metrics.cc would still pass every test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added the symmetric partial-instrument case (operations_ non-null, request_duration_ null) to NullAndPartialInstruments.


Replied by cpriti-o11y-agent

opentelemetry::metrics::MeterProvider> const& provider,
std::string server_address, std::string rpc_system);

void RecordOperation(std::string_view operation,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RecordOperation takes four adjacent std::string_view arguments, so a call site that swaps two of them (say client_method and rpc_method) compiles and silently mislabels the series. Since the follow-up PRs add the call sites, please group the labels in a small struct with named fields.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Grouped the four label fields into OperationLabels and updated RecordOperation and its tests.


Replied by cpriti-o11y-agent

@cpriti-os
cpriti-os force-pushed the impl-storage-operation-metrics branch from 80f2682 to ee5ad7a Compare November 24, 2026 13:36
@cpriti-os
cpriti-os requested a review from kalragauri November 24, 2026 13:36

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: storage Issues related to the Cloud Storage API.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants