Repository navigation
fix(telemetry): serialize lazy metric initialization - #1883
Conversation
RecordLLMRequest and RecordToolCall are called from concurrent review goroutines, but ensureMetrics guarded its one-time setup with a plain bool, so first use raced on the flag and on the metric handles.
|
🔍 OpenCodeReview found 1 issue(s) in this PR.
|
| metricsMu sync.Mutex | ||
| initMetricsOnce bool // guarded by metricsMu; tests reset it to re-initialize |
There was a problem hiding this comment.
Every call to a Record* function now acquires and releases metricsMu, even long after initialization is complete. Since these functions are called per-LLM-request, per-tool-call, and per-file from concurrent goroutines, this creates unnecessary lock contention on the hot path.
Consider using sync.Once instead, which internally uses atomics after the first call and avoids mutex contention entirely on subsequent calls. For test reset, you can replace the sync.Once value (it's unexported and safe to reassign in test helpers):
var metricsOnce sync.Once
func ensureMetrics() {
metricsOnce.Do(func() {
m := getMeter()
// ... initialize all metrics ...
})
}In tests, reset with metricsOnce = sync.Once{}.
There was a problem hiding this comment.
I'm keeping the mutex here. It's taken once per recorded LLM request or tool call, which costs very little next to the call being measured. The existing tests also reset initMetricsOnce directly (the two initMetricsOnce = false lines in internal/telemetry/events_test.go). Switching to sync.Once would mean editing that file, and three open PRs (#1781, #1720, #1284) touch it. NanaseInori's review also treated this as optional. I'm happy to switch if a maintainer prefers sync.Once.
AI disclosure: this reply was drafted with Claude Code (Claude Opus 5.5).
NanaseInori
left a comment
There was a problem hiding this comment.
Reviewed both changed files, all Record* call paths in metrics.go, and the telemetry test setup. The reported first-use race is supported by the code: the old unsynchronized flag could be observed before the handles were assigned. The mutex now serializes both the flag and handle initialization, and every recording path passes through that synchronization before reading a handle.
The concurrent-first-use regression waits for all workers before the test helper's cleanup resets telemetry, so this test does not introduce a reset-versus-record race. Disabled telemetry still returns early. I found no blocking defect.
The existing suggestion to replace the mutex with sync.Once is an optional optimization; no measured contention or user-visible regression is established here, so I would not block this focused correctness fix on it. The ensureMetrics duplicate search returned only this PR; no separate linked issue is claimed.
This is a source-and-test review. I did not independently run the repository's race suite or certify the reported full-suite results.
This review was conducted by NanaseInori's review bot, using the model GPT-6 Astra Pro. If you need a human review, please manually @NanaseInori.
Description
internal/telemetry/metrics.goinitialises its metric handles lazily on first use, guarded by a plainbool:RecordLLMRequestandRecordToolCallcallensureMetrics()and then read themetric.*package vars. Both are called from the LLM loop (internal/llmloop/loop.go:441-864, including the async tool path at:838), which runs once per file group in the review worker pool (--concurrency, default 8). With telemetry enabled, the first concurrent calls race. One goroutine can seeinitMetricsOnce == trueand read handles that another goroutine is still assigning.The new test, run under
-raceonmain(the race detector is what CI uses):It reports 6 races in total: on the flag (
:33/:36), and between the handle writes (:52-68) and the reads inRecordLLMRequest/RecordToolCall(:115-142).Fix: serialise
ensureMetrics()with async.Mutex. The unlock happens before every later caller's lock, so any goroutine that returns fromensureMetrics()sees fully initialised handles. I keptinitMetricsOnceas a guarded bool, notsync.Once, because the existing tests reset it (events_test.go:39,:47) to force re-initialisation against a fresh meter provider. A mutex lets those tests stay as they are. The lock is taken once per recorded LLM request or tool call, which is negligible next to the calls being measured.Behaviour is otherwise unchanged:
TestEnsureMetrics_Idempotent).events_test.gosetup).ensureMetrics()is called.Type of Change
How Has This Been Tested?
All runs used Go 1.26.10, the version in
go.modand CI, on macOS arm64.TestRecordMetrics_ConcurrentFirstUse(new) fails onmainwith the race report above. With the fix it passes, including-race -count=50together withTestEnsureMetrics_Idempotent.CI steps run locally:
gofmt -s -l .reports nothing.go vet ./...,scripts/verify-license.shandgo run scripts/verify-english-only.gopass.go mod tidyproduces no diff.go test -race -count=1 -coverprofile=… ./...reports 0 data races and 90.5% total coverage.go build ./cmd/opencodereviewsucceeds.One package fails locally both on
mainand with this change:internal/delegateTestDelegatePagerPTY, with "PTY regression uses util-linux script". It fails only becauseOCR_DELEGATE_REQUIRE_PTY=1is set and macOS has no util-linuxscript. It is unrelated to this change.make testpasses locally: I ran its equivalent,go test -race -count=1 ./.... The only failure is the environment-only delegate PTY test noted above.Manual testing (describe below)
Checklist
go fmt,go vet)AI disclosure: I found this issue and drafted the fix and test with Claude Code (Claude Opus 5.5). The commit has no AI attribution.
Related Issues
None. I searched issues and PRs for "ensureMetrics", "metrics race", "telemetry data race" and "sync.Once metrics" and found nothing. No open PR touches
metrics.goormetrics_test.go.🤖 Generated with Claude Code