Repository navigation
fix(otel): count connections that predate Init - #4089
Conversation
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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
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.
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
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:76still says Init must run "BEFORE creating any Redis clients". Relax that sentence here.- Follow-up:
PendingRequestsis also an UpDownCounter and still goes throughgetRecorder(). A request in flight acrossInitemits -1 without a +1, and acrossShutdownits -1 goes to the noop recorder. - Pre-existing, not this PR:
removeConnInternalalways emits -1 "used" (pool.go:1698), but the handoff worker'sRemoveWithoutTurn(maintnotifications/handoff_worker.go:512) can remove an UNUSABLE connection thatputConnparked inidleConns, 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.
|
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. |
|
Thanks for the review! Also relaxed the |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit ff07988. Configure here.
There was a problem hiding this comment.
💡 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".
ndyakov
left a comment
There was a problem hiding this comment.
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 callsremoveConnand reads the count callback in the sameconnsMusection, then runsProcessOnRemove,recordConnectionMetrics(..., MetricStateIdle, countCb)andcloseConn, the same wayRetireConnsdoes. 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 thatputIdleConnparks inidleConns(the Bugbot finding), andTestRefreshStaleSpareDropsUnpooledConncovers it.PubSubPool.Close(5cccb94) claims the connections and emits the -1s undertrackMu, then closes them after it releasestrackMu.SetGlobalRecorder(8cd0de1) holdssetRecorderMuacross the recorder swap andSetAllMetricCallbacks.- 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
Initdoc 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 samesetRecorderMu, but theSetGlobalRecorderbodies differ (here, ther == nilbranch callsSetAllMetricCallbacks(nil)before it takesrecorderMu). On rebase, #4142 should drop itssetRecorderMuhunk and keep only thePendingRequestschange tor.. #4142's context lines still showgetRecorder().RecordConnectionCount. If the conflict is resolved toward #4142, that silently reverts this PR's binding. After the rebase, bothConnectionCountandPendingRequestsmust callr..internal/pool/pool.go: #4142 changesremoveConnto return(removed, wasIdle). This PR adds a new caller inrefreshStaleSpareand changesremoveConnWithLockto return the count callback. The new caller fails to compile until it is updated. InremoveConnInternal, #4142 must keep reading the count callback underconnsMu(fromremoveConnWithLock), not after the unlock. #4142'swasIdleis set only insideif cn.pooled, so an unpooled conn parked inidleConnsstill 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 whileSetAllMetricCallbacksholds every pool lock) is still open. The same-pool case already exists on master:newConnandputIdleConncall the count callback underconnsMu. The snapshot extends it to every pool's lock and tolivePoolsMu, so a recorder that creates a client or runs a command synchronously deadlocksInitorShutdown. The OTel recorder only callsUpDownCounter.Add. Document onSetOTelRecorderthat 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
PendingRequestsand the handoff-removal state. #4142 covers both.
ndyakov
left a comment
There was a problem hiding this comment.
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 scansidleConnsfor every conn, and onlypoolSize.Add(-1)stays underif cn.pooled. TherefreshStaleSparespecial case is gone. All callers holdconnsMu(removeConnWithLock,refreshStaleSpare,RetireConns,Filter).idleConnsLendrops by one only when the conn is found, so a conn that was already popped is not counted twice.poolSizeis unchanged for unpooled conns. The parked conn counts inidleConnsLen, whichputConnchecks againstMaxIdleConns(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 bylen(idleConns). - 995d0ce:
MetricCallbacks.ConnectionCount(pool.go:195) andOTelConnectionCounter.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 onpool.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.
* 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): 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.

Description
Connections created before the metric callbacks are set never emit
+1, but they still emit-1when they leave idle or are closed. So if a client is created beforeredisotel-native'sInit(),db.client.connection.countundercounts and goes negative (reported in #4083 withPoolSize: 24).SetAllMetricCallbacksnow records the connections that already exist in every liveConnPoolandPubSubPool:+1per connection when callbacks are set, and-1when they are cleared, so the counter returns to zero onShutdown().NewConnPool/NewPubSubPoolthrough weak pointers and unregister inClose(), so an unclosed client can still be collected.connsMu(and a newtrackMuonPubSubPool). Removal paths,CloseandTrackConn/UntrackConnread 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.TestDrainIdleConnsReportsBorrowedConnectionStatesnow only looks at its own connection, and expects the+1 idlefor the connection that existed before the callbacks were set.PoolSize: 24, MinIdleConns: 8andNewClientbeforeInit(), idle goes from 16 to 24, matchingPoolStats().go test -race ./internal/...and./extra/redisotel-native/...pass, golangci-lint is clean.The
govulncheckfailure is from newgolang.org/x/netadvisories inexample/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.countdrifting negative when Redis clients (and idle connections) are created beforeredisotel-nativeInit(): those connections never got a+1but still emitted-1on close.SetAllMetricCallbacksnow snapshots every liveConnPoolandPubSubPool(weak-pointer registry, unregistered onClose()or GC) and applies a one-time+1per existing connection when callbacks are installed and matching-1s when they are cleared, so attach/detach andShutdown()leave the UpDownCounter balanced. Callback swaps take each pool’sconnsMu/ newPubSubPool.trackMu, and removal paths read the count callback under the same lock to avoid races during churn.SetGlobalRecorderis serialized withsetRecorderMu, clears pool callbacks before swapping in the noop recorder on shutdown, and pins theConnectionCountcallback to the recorder instance that counted a connection so late deltas aren’t dropped.Smaller pool fixes:
removeConnalso drops unpooled connections fromidleConns; 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.