Skip to content

fix(telemetry): serialize lazy metric initialization - #1883

Merged
lizhengfeng101 merged 2 commits into
alibaba:mainfrom
divya0795:fix/telemetry-metrics-init-race
Nov 17, 2026
Merged

lizhengfeng101 merged 2 commits into
alibaba:mainfrom
divya0795:fix/telemetry-metrics-init-race

Conversation

@divya0795

Copy link
Copy Markdown
Contributor

Description

internal/telemetry/metrics.go initialises its metric handles lazily on first use, guarded by a plain bool:

// internal/telemetry/metrics.go:32-37
func ensureMetrics() {
	if initMetricsOnce {
		return
	}
	initMetricsOnce = true
	m := getMeter()
	...

RecordLLMRequest and RecordToolCall call ensureMetrics() and then read the metric.* 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 see initMetricsOnce == true and read handles that another goroutine is still assigning.

The new test, run under -race on main (the race detector is what CI uses):

$ go test -race -count=1 -run TestRecordMetrics_ConcurrentFirstUse ./internal/telemetry/
WARNING: DATA RACE
Read at 0x000103cff68d by goroutine 10:
  github.com/alibaba/open-code-review/internal/telemetry.ensureMetrics()
      .../internal/telemetry/metrics.go:33 +0x28
  ...
Previous write at 0x000103cff68d by goroutine 14:
  github.com/alibaba/open-code-review/internal/telemetry.ensureMetrics()
      .../internal/telemetry/metrics.go:36 +0x40
...
--- FAIL: TestRecordMetrics_ConcurrentFirstUse (0.00s)
    testing.go:1712: race detected during execution of test

It reports 6 races in total: on the flag (:33/:36), and between the handle writes (:52-68) and the reads in RecordLLMRequest/RecordToolCall (:115-142).

Fix: serialise ensureMetrics() with a sync.Mutex. The unlock happens before every later caller's lock, so any goroutine that returns from ensureMetrics() sees fully initialised handles. I kept initMetricsOnce as a guarded bool, not sync.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:

  • The first call initialises the handles.
  • Later calls are no-ops (TestEnsureMetrics_Idempotent).
  • Resetting the flag re-initialises (the events_test.go setup).
  • Disabled telemetry still returns before ensureMetrics() is called.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring (no functional changes)
  • Documentation update
  • CI / Build / Tooling

How Has This Been Tested?

All runs used Go 1.26.10, the version in go.mod and CI, on macOS arm64.

  • TestRecordMetrics_ConcurrentFirstUse (new) fails on main with the race report above. With the fix it passes, including -race -count=50 together with TestEnsureMetrics_Idempotent.

  • CI steps run locally:

    • gofmt -s -l . reports nothing.
    • go vet ./..., scripts/verify-license.sh and go run scripts/verify-english-only.go pass.
    • go mod tidy produces no diff.
    • go test -race -count=1 -coverprofile=… ./... reports 0 data races and 90.5% total coverage.
    • go build ./cmd/opencodereview succeeds.
  • One package fails locally both on main and with this change: internal/delegate TestDelegatePagerPTY, with "PTY regression uses util-linux script". It fails only because OCR_DELEGATE_REQUIRE_PTY=1 is set and macOS has no util-linux script. It is unrelated to this change.

  • make test passes 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

  • My code follows the project's coding style (go fmt, go vet)
  • I have performed a self-review of my code
  • I have added tests that prove my fix is effective or my feature works
  • New and existing unit tests pass locally with my changes
  • I have updated the documentation accordingly (if applicable)
  • I have signed the CLA
  • I did not use AI/LLM to create this PR, or I disclosed the tool/model below and reviewed its output; I did not attribute commits to AI and will answer maintainer questions and review comments myself without AI/LLM.

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.go or metrics_test.go.

🤖 Generated with Claude Code

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.
@CLAassistant

CLAassistant commented Nov 9, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 1 issue(s) in this PR.

  • ✅ Successfully posted inline: 1 comment(s)

Comment on lines +20 to +21
metricsMu sync.Mutex
initMetricsOnce bool // guarded by metricsMu; tests reset it to re-initialize

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.

performance · medium
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{}.

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.

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 NanaseInori 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.

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.

@chaojixinren chaojixinren 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.

LGTM

@lizhengfeng101 lizhengfeng101 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.

LGTM

@lizhengfeng101
lizhengfeng101 merged commit 9430c9c into alibaba:main Nov 17, 2026
12 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.

5 participants