Skip to content

fix(telemetry): export OTLP metrics on explicit shutdown - #2200

Merged
wolo-lab merged 8 commits into
google:mainfrom
gezerui888:fix/otlp-metric-shutdown
Nov 19, 2026
Merged

wolo-lab merged 8 commits into
google:mainfrom
gezerui888:fix/otlp-metric-shutdown

Conversation

@gezerui888

@gezerui888 gezerui888 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Closes: #2167

Problem:

Built-in OTLP metric readers discard the final collection on Providers.Shutdown, losing metrics recorded since the last periodic export.

Solution:

I select shutdown behavior per exporter. OTLP readers use the SDK’s final export with the existing empty-collection filter. Google Cloud readers retain their shutdown suppression. Two existing dependencies become direct test imports. Their versions do not change.

Behavior change

Explicit Providers.Shutdown now exports pending OTLP metrics. It can wait for the request and return an export error, including cancellation. Google Cloud’s minimum collection interval still requires suppression of its final export. Custom readers and providers keep their existing behavior.

Testing Plan

Unit Tests:

  • The branch has no new failures relative to main 012af4d9 (November 18).

I ran these checks with Go 1.26.10 and both modules in go.work:

go build -mod=readonly work                              PASS
go test -race -mod=readonly -count=1 -shuffle=1763431200 -json work
  candidate: 11,523 leaf cases passed, 7 skipped, 1 failed
  main:      11,514 leaf cases passed, 7 skipped, 1 failed
go mod tidy -diff                                       PASS, both modules
golangci-lint run (v2.15.0)                              0 issues, both modules

Both trees fail the same unchanged agentanalytics timing case: TestSanitizeRawText/pattern_words_with_long_backslash_runs_are_inspected_in_linear_time. The telemetry suite passes three repeated race runs. Formatting and git diff --check pass. The upstream ForceFlush regression is retained; shutdown now verifies a second export.

With your source change reverted and your tests kept, which test fails?

TestOtlpEnvMetricShutdown/{general,metrics,mixed_with_Google_Cloud}/record=true fails because no OTLP request arrives. TestOtlpEnvMetricShutdownReturnsExportCancellation also fails: shutdown returns nil without sending a request. With the fix, it returns an error matching context.Canceled after the collector receives the request.

The tests also fail when I restore OTLP suppression, enable GCP’s final export, remove empty-collection filtering, or invert exporter selection.

TestOtlpEnvMetricShutdownReturnsRejectedExport checks that an HTTP 400 from the collector reaches Providers.Shutdown with an uncancelled context. It fails when guardedExporter.Export discards the export error. The existing cancellation test still passes under that mutation.

Manual End-to-End (E2E) Tests:

I used an external Go module to call public telemetry.New, record 7 on a pending_count counter, and call Shutdown against local HTTP collectors. All ten cases pass. The collectors decode protobuf and check the counter value, scope and attribute. GCP credentials and metadata use local fixtures.

Case Observed result
General and metrics-specific endpoints One shutdown export, value 7
Mixed OTLP/GCP One OTLP export, zero GCP shutdown requests
GCP control One request after ForceFlush, still one after shutdown
Empty collections Zero requests
Custom reader/provider SDK final export and provider identity preserved

Run the HTTP/protobuf, rejected-export and cancellation regressions with:

go test -count=1 -run '^TestOtlpEnvMetricShutdown' -v ./telemetry

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests have no new failures relative to main.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules. No dependent changes are required.

Additional context

adk-python setup.py:107–115 disables automatic shutdown at exit, not explicit MeterProvider.shutdown(). Go has no automatic exit hook. This implements the OTLP follow-up requested in #2042. Google Cloud still suppresses its final export because of the minimum interval.

cc @wolo-lab

Let built-in OTLP readers perform the SDK's final export while retaining
Google Cloud shutdown suppression and empty-collection filtering.
Cover both endpoint forms and mixed exporters with decoded metric payloads,
and verify cancellation during the final export.

Fixes google#2167
@gezerui888
gezerui888 requested a review from a team as a code owner November 8, 2026 02:14
@google-cla

google-cla Bot commented Nov 8, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@wolo-lab wolo-lab left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Must change before merge: one test. The code does what the description says, so this is only about pinning it.

The description says Shutdown can now return an export error. No test in the package checks that for any error other than cancellation, and the cancellation test can't tell the two sources apart. After the request arrives it cancels ctx, and PeriodicReader.Shutdown then calls the exporter's Shutdown with that same context. The otlpmetrichttp client returns ctx.Err() from there, and the reader returns that error whenever the export itself returned nil. So if guardedExporter.Export called the exporter and dropped its error, every test in telemetry would still pass, TestOtlpEnvMetricShutdownReturnsExportCancellation included. I made exactly that change locally and the package stayed green.

On this head the behavior is right: a collector that answers 400 makes Shutdown return failed to upload metrics: ... 400 Bad Request. A test like the one below pins it. It passes on this head and fails with the error-dropping change above.

Test: a rejected export reaches the caller of Shutdown
func TestOtlpEnvMetricShutdownReturnsRejectedExport(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	}))
	t.Cleanup(srv.Close)
	t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
	t.Setenv("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", srv.URL+"/v1/metrics")
	t.Setenv("OTEL_METRIC_EXPORT_INTERVAL", "3600000")
	providers, err := New(t.Context())
	if err != nil {
		t.Fatalf("New() failed: %v", err)
	}
	counter, err := providers.MeterProvider.Meter("test-meter").Int64Counter("test-counter")
	if err != nil {
		t.Fatalf("creating counter failed: %v", err)
	}
	counter.Add(t.Context(), 1)
	if err := providers.Shutdown(t.Context()); err == nil {
		t.Error("Shutdown() = nil, want the rejected export's error")
	}
}

Run it with go test -count=1 -run TestOtlpEnvMetricShutdownReturnsRejectedExport ./telemetry.

The property to keep: every failure of the OTLP final export, not only a cancelled context, reaches whoever calls Providers.Shutdown.

The two notes on the lines below don't block.

Comment thread telemetry/setup_otel.go Resolved
Comment thread telemetry/setup_otel.go Resolved
Clarify the configured endpoint assumption and name the reader helper after its shutdown behavior.
@gezerui888

Copy link
Copy Markdown
Contributor Author

I added an HTTP 400 regression that checks the final export error reaches Providers.Shutdown with an uncancelled context. Discarding that export error makes the new test fail, while the cancellation test still passes. Both modules pass build, race/shuffle tests, tidy and lint. I also addressed both inline notes in aa8f059.

wolo-lab
wolo-lab previously approved these changes Nov 8, 2026

@wolo-lab wolo-lab left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All good, thanks!

@wolo-lab

wolo-lab commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

@gezerui888, Please sign the CLA.

@gezerui888

Copy link
Copy Markdown
Contributor Author

I merged current main and resolved the telemetry test conflict, keeping the upstream ForceFlush check and the shutdown regressions. Both modules pass build, lint and tidy checks. The full race suite has the same single timing-test failure as main; repeated telemetry tests and the public API checks pass.

@wolo-lab
wolo-lab merged commit bd7f179 into google:main Nov 19, 2026
15 checks passed
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.

telemetry: export pending metrics from the OTLP reader on an explicit Shutdown

3 participants