Skip to content

fix(otel): count connections that predate Init - #4089

Merged
ndyakov merged 14 commits into
redis:masterfrom
ninadsutrave:fix/otel-connection-count
Oct 19, 2026
Merged

ndyakov merged 14 commits into
redis:masterfrom
ninadsutrave:fix/otel-connection-count

Conversation

@ninadsutrave

@ninadsutrave ninadsutrave commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

Connections created before the metric callbacks are set never emit +1, but they still emit -1 when they leave idle or are closed. So if a client is created before redisotel-native's Init(), db.client.connection.count undercounts and goes negative (reported in #4083 with PoolSize: 24).

SetAllMetricCallbacks now records the connections that already exist in every live ConnPool and PubSubPool: +1 per connection when callbacks are set, and -1 when they are cleared, so the counter returns to zero on Shutdown().

  • Pools register in NewConnPool/NewPubSubPool through weak pointers and unregister in Close(), so an unclosed client can still be collected.
  • The snapshot holds each pool's connsMu (and a new trackMu on PubSubPool). Removal paths, Close and TrackConn/UntrackConn read the count callback under the same lock as their map change, so a concurrent callback change can't leave the counter off by one.
  • SetGlobalRecorder(nil) clears the pool callbacks before swapping in the noop recorder, so the final -1s reach the recorder being removed.

This is the second option from my comment on the issue. If you'd rather only document the Init() ordering, I can change it.

Testing

  • TestConnectionCountIncludesExistingConns: counts are correct after attaching to a pool with existing idle connections, and back to zero after detaching.
  • TestConnectionCountBalancedWhileCallbacksChange: toggles the callbacks while connections are taken, returned and removed; the count ends at 0. It drifts to -2/+1 without the locking change.
  • TestShutdownUncountsExistingConns: SetGlobalRecorder(nil) brings the count back to 0.
  • TestDrainIdleConnsReportsBorrowedConnectionStates now only looks at its own connection, and expects the +1 idle for the connection that existed before the callbacks were set.
  • With PoolSize: 24, MinIdleConns: 8 and NewClient before Init(), idle goes from 16 to 24, matching PoolStats().
  • go test -race ./internal/... and ./extra/redisotel-native/... pass, golangci-lint is clean.

The govulncheck failure is from new golang.org/x/net advisories in example/otel-metrics, not from this change.

Fixes #4083


Note

Medium Risk
Changes global pool metric callback registration, locking order, and hot-path removal accounting; behavior is heavily tested but mistakes could skew connection metrics or deadlock under contention.

Overview
Fixes db.client.connection.count drifting negative when Redis clients (and idle connections) are created before redisotel-native Init(): those connections never got a +1 but still emitted -1 on close.

SetAllMetricCallbacks now snapshots every live ConnPool and PubSubPool (weak-pointer registry, unregistered on Close() or GC) and applies a one-time +1 per existing connection when callbacks are installed and matching -1s when they are cleared, so attach/detach and Shutdown() leave the UpDownCounter balanced. Callback swaps take each pool’s connsMu / new PubSubPool.trackMu, and removal paths read the count callback under the same lock to avoid races during churn.

SetGlobalRecorder is serialized with setRecorderMu, clears pool callbacks before swapping in the noop recorder on shutdown, and pins the ConnectionCount callback to the recorder instance that counted a connection so late deltas aren’t dropped.

Smaller pool fixes: removeConn also drops unpooled connections from idleConns; stale-spare refresh uses the shared removal/metrics path. Init() docs note that pre-Init() clients are included.

Reviewed by Cursor Bugbot for commit 995d0ce. Bugbot is set up for automated code reviews on this repo. Configure here.

Connections created before the metric callbacks were set never emitted
+1, but still emitted -1 when they left idle or were closed, so
db.client.connection.count went negative when a client was created
before redisotel-native's Init.

Existing connections are now counted when the callbacks are set and
uncounted when they are cleared.

Closes redis#4083
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T07:30:45.597811Z 995d0ce New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1c3e0b4610

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/pool/pool.go Resolved
Comment thread internal/pool/pool.go Resolved
Comment thread internal/pool/pool.go Resolved
Comment thread internal/pool/pool.go Resolved

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

Stale Bugbot comment from a previous run.

Comment thread internal/pool/pool.go Resolved
Comment thread internal/pool/pool.go Resolved
Comment thread internal/pool/pool.go Resolved
Keep weak pointers to live pools so a client that is dropped without
Close can still be collected.

SetGlobalRecorder(nil) now clears the pool callbacks before swapping in
the noop recorder, so the -1 for existing connections reaches the
recorder being removed.
Removal paths, Close and PubSub tracking now read the connection count
callback under the same lock as the map change, so a concurrent
SetAllMetricCallbacks can't land between them and leave the counter off
by one.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 964c9f2302

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/otel/metrics.go Resolved
Comment thread internal/pool/pool.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d13f9d1685

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/pool/pool.go Resolved
ndyakov
ndyakov previously approved these changes Oct 16, 2026

@ndyakov ndyakov left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The approach is sound. Each removal path now reads the count callback under the same connsMu/trackMu as its map change, and SetAllMetricCallbacks takes a snapshot under all of those locks. So every connection gets exactly one +1 and one -1 per recorder, and repeated Init/Shutdown cycles stay balanced, because the old recorder gets its -1s before the new one gets its +1s. All Codex/Bugbot threads are addressed. The author's reply on pool.go:222 is correct: pools dropped without Close never emitted -1 before this PR either. No overlap with #4031, which changes Stats() and extra/redisotel only. None with #4086 either: it changes parsePoolName, but the +1 and the -1 both use it, so the series match in either merge order. The PR still merges cleanly after #4101; the changed removeConnWithLock/recordConnectionMetrics call sites are unchanged on master. CI is green. The inline comments are non-blocking; 1 and 3 are worth doing before merge.

Non-blocking:

  • extra/redisotel-native/redisotel.go:76 still says Init must run "BEFORE creating any Redis clients". Relax that sentence here.
  • Follow-up: PendingRequests is also an UpDownCounter and still goes through getRecorder(). A request in flight across Init emits -1 without a +1, and across Shutdown its -1 goes to the noop recorder.
  • Pre-existing, not this PR: removeConnInternal always emits -1 "used" (pool.go:1698), but the handoff worker's RemoveWithoutTurn (maintnotifications/handoff_worker.go:512) can remove an UNUSABLE connection that putConn parked in idleConns, where it was counted as idle.

Follow-up: #4128 is tracked separately. You can address it in this PR or in a new one, whichever you prefer. We will wait a few days for a response. If there is none, we will merge this PR as it is.

Comment thread internal/pool/pool.go Resolved
Comment thread internal/pool/pool_test.go Resolved
Comment thread internal/pool/pubsub.go Resolved
Comment thread internal/otel/metrics.go Resolved
Comment thread internal/otel/connection_count_test.go Resolved
Comment thread internal/pool/pool.go Resolved
@ndyakov

ndyakov commented Oct 16, 2026

Copy link
Copy Markdown
Member

Follow-up for the two non-blocking notes in my review: #4128 (PendingRequests drift across Init/Shutdown, and the handoff removal emitting used -1 for an idle-parked conn). Not blocking this PR.

@ninadsutrave

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Also relaxed the Init doc in ff07988.

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit ff07988. Configure here.

Comment thread internal/pool/pool.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cd631574a1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/pool/pool.go Resolved
ndyakov
ndyakov previously approved these changes Oct 17, 2026

@ndyakov ndyakov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

All six comments from the previous round are addressed. Master is merged in (cb45963), and each fix is in its own commit:

  • refreshStaleSpare (af4cc0e, cd63157) now calls removeConn and reads the count callback in the same connsMu section, then runs ProcessOnRemove, recordConnectionMetrics(..., MetricStateIdle, countCb) and closeConn, the same way RetireConns does. The snapshot sees the spare either as idle or as gone, so the per-state series no longer drift. cd63157 also handles the unpooled conn that putIdleConn parks in idleConns (the Bugbot finding), and TestRefreshStaleSpareDropsUnpooledConn covers it.
  • PubSubPool.Close (5cccb94) claims the connections and emits the -1s under trackMu, then closes them after it releases trackMu.
  • SetGlobalRecorder (8cd0de1) holds setRecorderMu across the recorder swap and SetAllMetricCallbacks.
  • The churn test (6da2c8a) checks each state separately. It also runs PubSub track/untrack and pool create/close goroutines during the toggle loop. The MinIdle wait check, the lock-order comment, and the relaxed Init doc are all in.

CI is green at cd63157. go test -race ./internal/pool/ ./internal/otel/ passes locally, and so do the count, refresh, and shutdown tests with -count=20.

Overlap with #4142 (approved at fd65990): merge this PR first, then rebase #4142 on it. These are the conflicts to expect:

  • internal/otel/metrics.go: both PRs add the same setRecorderMu, but the SetGlobalRecorder bodies differ (here, the r == nil branch calls SetAllMetricCallbacks(nil) before it takes recorderMu). On rebase, #4142 should drop its setRecorderMu hunk and keep only the PendingRequests change to r.. #4142's context lines still show getRecorder().RecordConnectionCount. If the conflict is resolved toward #4142, that silently reverts this PR's binding. After the rebase, both ConnectionCount and PendingRequests must call r..
  • internal/pool/pool.go: #4142 changes removeConn to return (removed, wasIdle). This PR adds a new caller in refreshStaleSpare and changes removeConnWithLock to return the count callback. The new caller fails to compile until it is updated. In removeConnInternal, #4142 must keep reading the count callback under connsMu (from removeConnWithLock), not after the unlock. #4142's wasIdle is set only inside if cn.pooled, so an unpooled conn parked in idleConns still gets used -1. Inline comment 1 fixes that for both PRs.

Non-blocking:

  • The Codex thread on pool.go:382 (recorder re-entering go-redis while SetAllMetricCallbacks holds every pool lock) is still open. The same-pool case already exists on master: newConn and putIdleConn call the count callback under connsMu. The snapshot extends it to every pool's lock and to livePoolsMu, so a recorder that creates a client or runs a command synchronously deadlocks Init or Shutdown. The OTel recorder only calls UpDownCounter.Add. Document on SetOTelRecorder that a recorder must not call go-redis synchronously, or emit the snapshot after the locks are released; both keep the counts balanced. Reply on the thread either way.
  • #4128 still tracks PendingRequests and the handoff-removal state. #4142 covers both.

Comment thread internal/pool/pool.go Resolved

@ndyakov ndyakov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re-approving at 995d0ce. The two commits since cd63157 address the inline comment and the open Codex thread:

  • f82a86e: removeConn (internal/pool/pool.go:1871) now scans idleConns for every conn, and only poolSize.Add(-1) stays under if cn.pooled. The refreshStaleSpare special case is gone. All callers hold connsMu (removeConnWithLock, refreshStaleSpare, RetireConns, Filter). idleConnsLen drops by one only when the conn is found, so a conn that was already popped is not counted twice. poolSize is unchanged for unpooled conns. The parked conn counts in idleConnsLen, which putConn checks against MaxIdleConns (pool.go:1626), so removing it now frees that slot as it should. The extra scan only runs when an unpooled conn is removed and is bounded by len(idleConns).
  • 995d0ce: MetricCallbacks.ConnectionCount (pool.go:195) and OTelConnectionCounter.RecordConnectionCount (otel.go:96) now say that the callback runs under pool locks and must not call back into go-redis. With the author's reply, this closes the Codex thread on pool.go:383; it can be resolved.

TestRemoveConnDropsUnpooledIdleConn fails on cd63157's pool.go (RetireConns and Filter both leave the conn in idleConns) and passes at head. go test -race ./internal/pool/ ./internal/otel/ passes. The new test and TestRefreshStaleSpareDropsUnpooledConn pass with -race -count=20. CI is green.

Update to the #4142 rebase notes: the wasIdle gap from round 2 is now closed here. On rebase, put #4142's wasIdle = true into the idleConns loop, which no longer sits inside if cn.pooled. The refreshStaleSpare caller is now just removed := p.removeConn(oldest) and becomes removed, _ :=. The other notes still apply: keep setRecorderMu from this PR, both count callbacks must use r., and the count callback is read under connsMu.

@ndyakov
ndyakov merged commit 04fc134 into redis:master Oct 19, 2026
38 checks passed
@ninadsutrave
ninadsutrave deleted the fix/otel-connection-count branch October 21, 2026 08:39
ndyakov added a commit that referenced this pull request Nov 23, 2026
* perf(otel): observe connection count at collection

db.client.connection.count was fed by +1/-1 deltas on every Get and
Put, inside connsMu. Init and Shutdown recounted every live connection
while holding every pool's lock.

Each recorder now observes its pools' Stats() through an asynchronous
UpDownCounter at collection time. The exported metric is the same
non-monotonic Sum with the same name, unit and attributes.

Refs #4083, #4089, #4128

* fix(pool): drop unused PubSubPool.metrics
ndyakov added a commit that referenced this pull request Nov 23, 2026
* perf(otel): observe connection count at collection (#4406)

* perf(otel): observe connection count at collection

db.client.connection.count was fed by +1/-1 deltas on every Get and
Put, inside connsMu. Init and Shutdown recounted every live connection
while holding every pool's lock.

Each recorder now observes its pools' Stats() through an asynchronous
UpDownCounter at collection time. The exported metric is the same
non-monotonic Sum with the same name, unit and attributes.

Refs #4083, #4089, #4128

* fix(pool): drop unused PubSubPool.metrics

* perf(otel): cache metric attribute options

pending_requests, wait_time and operation duration rebuilt their
attribute slices, parsed the pool name and built a new attribute set
on every call. Cache the measurement options per pool and command,
including custom attributes, and read the global recorder through an
atomic pointer.

Exported data is unchanged.
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.

negative db.client.connection.count using redisotel-native metrics

2 participants