Repository navigation
Include watched keys and pubsub channel/pattern memory in client memory overhead - #3362
Conversation
…ry overhead Previously, multiStateMemOverhead() and pubsubMemOverhead() only counted the structure overhead (listNode, watchedKey, hashtable) but not the actual watched_key/channel/pattern robj objects themselves. This led to under-reporting of client memory usage. This was problematic because: 1. If a client watches many keys or watches keys with very large names, this memory was invisible in CLIENT INFO tot-mem, making it hard to identify which client is consuming memory. 2. This memory was incorrectly attributed to used_memory_dataset instead of client memory, making memory analysis misleading. 3. The maxmemory-clients eviction mechanism could not account for this memory, potentially allowing clients to bypass memory limits. The same issues apply to SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE with large or numerous channel/pattern names. Since each client holds its own robj copy for watched keys and pubsub subscriptions (via incrRefCount on argv), this memory should be attributed to the client for accurate memory accounting. Changes: - Add watched_keys_mem field to multiState struct to track watched key robj memory with O(1) lookup - Add pubsub_object_mem field to ClientPubSubData struct to track channel/pattern robj memory with O(1) lookup The memory counters are updated on add/delete operations, making the overhead calculation O(1) instead of O(N). Signed-off-by: Binbin <binloveplay1314@qq.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## unstable #3362 +/- ##
============================================
- Coverage 76.74% 76.72% -0.03%
============================================
Files 162 162
Lines 81124 81140 +16
============================================
- Hits 62261 62251 -10
- Misses 18863 18889 +26
🚀 New features to boost your workflow:
|
Signed-off-by: Binbin <binloveplay1314@qq.com>
zuiderkwast
left a comment
There was a problem hiding this comment.
Memory overhead looks correct but you added some chinese notes. 😆
I usually save notes under misc/ locally because misc is in .gitignore.
Signed-off-by: Binbin <binloveplay1314@qq.com>
…pdate in pubsubShardUnsubscribeAllChannelsInSlot Add a helper function getStringObjectMemory() that returns the total memory of a string object (sizeof(robj) + getStringObjectSdsUsedMemory()), replacing the repeated inline expression across multi.c and pubsub.c. Fix a bug where pubsubShardUnsubscribeAllChannelsInSlot() did not decrement pubsub_object_mem when unsubscribing shard channels during cluster slot migration. This could cause tot-mem in CLIENT INFO to drift and potentially lead to size_t underflow if the counter later went negative. Signed-off-by: Binbin <binloveplay1314@qq.com>
Signed-off-by: Binbin <binloveplay1314@qq.com>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds per-client memory counters for watched keys and pubsub name objects, plus a shared string-object memory helper. The overhead calculations now include these counters, and new introspection tests validate the reported memory changes. ChangesPer-client memory tracking for watched keys and pubsub
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
tests/unit/introspection.tcl (1)
42-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftAdd coverage for the slot-migration shard unsubscribe path.
This loop only exercises explicit
sunsubscribe, but the PR also fixes memory accounting inpubsubShardUnsubscribeAllChannelsInSlot(). Without a cluster integration test that triggers that internal cleanup path, the regression this PR fixes can still slip through untested. Based on learnings from the PR objective, this change includes a specific shard-unsubscribe fix during slot migration. As per coding guidelines, "End-to-end behavior changes should be covered by integration tests."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/unit/introspection.tcl` around lines 42 - 65, Add an integration test that exercises the slot-migration shard unsubscribe cleanup path, since the current CLIENT INFO memory test only covers explicit sunsubscribe. Update the introspection test coverage to trigger pubsubShardUnsubscribeAllChannelsInSlot() through a cluster slot migration scenario and verify the client memory accounting changes accordingly, using the existing CLIENT INFO/get_client_mem_no_qbuf helpers and the pubsub subscription flow as the lookup points.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/pubsub.c`:
- Line 325: The pubsub memory accounting in pubsub_c is charging shared channel
names as if each subscriber owns a separate robj, which inflates client memory
stats; update the accounting around the subscription and unsubscribe paths in
the pubsub handling code so only distinct client-owned objects are billed, or
move the shared-channel memory attribution into the shared pubsub structure
instead. Check the calls that update pubsub_object_mem in the subscription flow
and related removal/cleanup paths so the same canonical channel object is not
counted once per subscriber.
---
Nitpick comments:
In `@tests/unit/introspection.tcl`:
- Around line 42-65: Add an integration test that exercises the slot-migration
shard unsubscribe cleanup path, since the current CLIENT INFO memory test only
covers explicit sunsubscribe. Update the introspection test coverage to trigger
pubsubShardUnsubscribeAllChannelsInSlot() through a cluster slot migration
scenario and verify the client memory accounting changes accordingly, using the
existing CLIENT INFO/get_client_mem_no_qbuf helpers and the pubsub subscription
flow as the lookup points.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 801a2394-307d-4ce9-aaf4-9182f565e490
📒 Files selected for processing (5)
src/multi.csrc/networking.csrc/pubsub.csrc/server.htests/unit/introspection.tcl
In pubsubUnsubscribeChannel and pubsubUnsubscribePattern, the pubsub_object_mem counter was previously decremented using the caller-supplied object, while the subscribe path incremented it using the object actually stored in the client's hashtable (which may be a different robj for shared channel names). This asymmetry could cause the size_t counter to drift and eventually underflow. Switch to hashtablePop to retrieve the stored object and account memory based on it, then manually decrRefCount it (hashtablePop does not invoke the entry destructor). Also fix a misleading comment in pubsubMemOverhead that claimed each client has its own copy of the channel name, and lower the test threshold from 50000 to 10000 to tolerate timing-dependent buffer fluctuations. Signed-off-by: Binbin <binloveplay1314@qq.com>
|
Note We couldn't fetch the incremental changes for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
Two changes to reduce memory usage when multiple clients subscribe to the same channel pattern or WATCH the same key: 1. pubsubSubscribePattern: switch from hashtableAdd (single-phase) to hashtableFindPositionForInsert + hashtableInsertAtPosition (two-phase insert), aligning with pubsubSubscribeChannel's pattern. When a pattern already exists in server.pubsub_patterns, reuse the canonical robj via dictGetKey() so all clients share a single robj. 2. watchForKey: replace dictFetchValue with dictFind + dictGetKey to retrieve the canonical key robj from c->db->watched_keys when the key is already watched by another client, so all clients share a single robj. Signed-off-by: Binbin <binloveplay1314@qq.com>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/multi.c (1)
384-403: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftShared watched keys are now over-counted per client.
Lines 389-391 deliberately reuse the DB-level canonical key object when another client already watches the same key, but Line 403 still adds a full
getStringObjectMemory(key)to every client'swatched_keys_mem. From the second watcher onward, no new string object is allocated, yetCLIENT INFO tot-memandmaxmemory-clientswill charge another full key object anyway. This makes the new accounting diverge from the actual allocation behavior for shared watched keys.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/multi.c` around lines 384 - 403, Shared watched keys are being double-counted in client memory accounting: in the watched-keys setup inside multi.c, the logic in the de/dictFind branch reuses the DB-level canonical key object, but the per-client accounting still adds a full key object size. Update the watched-keys handling around watchedKeyLinkToClients and c->mstate->watched_keys_mem so that only newly allocated key objects are charged, and shared watchers for an existing canonical key do not increment the client memory total again.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@src/multi.c`:
- Around line 384-403: Shared watched keys are being double-counted in client
memory accounting: in the watched-keys setup inside multi.c, the logic in the
de/dictFind branch reuses the DB-level canonical key object, but the per-client
accounting still adds a full key object size. Update the watched-keys handling
around watchedKeyLinkToClients and c->mstate->watched_keys_mem so that only
newly allocated key objects are charged, and shared watchers for an existing
canonical key do not increment the client memory total again.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 360f1a84-395c-480b-ba5a-158a026af030
📒 Files selected for processing (3)
src/multi.csrc/pubsub.ctests/unit/introspection.tcl
🚧 Files skipped from review as they are similar to previous changes (2)
- tests/unit/introspection.tcl
- src/pubsub.c
In ad12730, channel robj objects were changed to be shared between the pubsub kvstore and all subscribing clients, saving memory when many clients subscribe to the same channel. Apply the same idea to pubsub patterns and WATCH keys: - pubsubSubscribePattern: use hashtableFindPositionForInsert to check for duplicates before insertion, then retrieve the canonical robj from server.pubsub_patterns via dictGetKey so that all clients subscribing to the same pattern share a single robj. - watchForKey: use dictFind + dictGetKey to retrieve the canonical robj from db->watched_keys, so that multiple clients WATCHing the same key share a single robj instead of each holding an independent copy. This reduces server memory usage when multiple clients subscribe to the same pattern or WATCH the same key. Might related #3362. Signed-off-by: Binbin <binloveplay1314@qq.com>
This reverts commit 1b41a81. Signed-off-by: Binbin <binloveplay1314@qq.com>
Signed-off-by: Binbin <binloveplay1314@qq.com>
Signed-off-by: Binbin <binloveplay1314@qq.com>
In ad12730, channel robj objects were changed to be shared between the pubsub kvstore and all subscribing clients, saving memory when many clients subscribe to the same channel. Apply the same idea to pubsub patterns and WATCH keys: - pubsubSubscribePattern: use hashtableFindPositionForInsert to check for duplicates before insertion, then retrieve the canonical robj from server.pubsub_patterns via dictGetKey so that all clients subscribing to the same pattern share a single robj. - watchForKey: use dictFind + dictGetKey to retrieve the canonical robj from db->watched_keys, so that multiple clients WATCHing the same key share a single robj instead of each holding an independent copy. This reduces server memory usage when multiple clients subscribe to the same pattern or WATCH the same key. Might related valkey-io#3362. Signed-off-by: Binbin <binloveplay1314@qq.com> Signed-off-by: Vanshika <vanshikaturakhia@gmail.com>
In ad12730, channel robj objects were changed to be shared between the pubsub kvstore and all subscribing clients, saving memory when many clients subscribe to the same channel. Apply the same idea to pubsub patterns and WATCH keys: - pubsubSubscribePattern: use hashtableFindPositionForInsert to check for duplicates before insertion, then retrieve the canonical robj from server.pubsub_patterns via dictGetKey so that all clients subscribing to the same pattern share a single robj. - watchForKey: use dictFind + dictGetKey to retrieve the canonical robj from db->watched_keys, so that multiple clients WATCHing the same key share a single robj instead of each holding an independent copy. This reduces server memory usage when multiple clients subscribe to the same pattern or WATCH the same key. Might related valkey-io#3362. Signed-off-by: Binbin <binloveplay1314@qq.com> Signed-off-by: Alon Arenberg <alonare@amazon.com>
In ad12730, channel robj objects were changed to be shared between the pubsub kvstore and all subscribing clients, saving memory when many clients subscribe to the same channel. Apply the same idea to pubsub patterns and WATCH keys: - pubsubSubscribePattern: use hashtableFindPositionForInsert to check for duplicates before insertion, then retrieve the canonical robj from server.pubsub_patterns via dictGetKey so that all clients subscribing to the same pattern share a single robj. - watchForKey: use dictFind + dictGetKey to retrieve the canonical robj from db->watched_keys, so that multiple clients WATCHing the same key share a single robj instead of each holding an independent copy. This reduces server memory usage when multiple clients subscribe to the same pattern or WATCH the same key. Might related valkey-io#3362. Signed-off-by: Binbin <binloveplay1314@qq.com> Signed-off-by: Alon Arenberg <alonare@amazon.com>
…ry overhead (valkey-io#3362) Previously, multiStateMemOverhead() and pubsubMemOverhead() only counted the structure overhead (listNode, watchedKey, hashtable) but not the actual watched_key/channel/pattern robj objects themselves. This led to under-reporting of client memory usage. This was problematic because: 1. If a client watches many keys or watches keys with very large names, this memory was invisible in CLIENT INFO tot-mem, making it hard to identify which client is consuming memory. 2. This memory was incorrectly attributed to used_memory_dataset instead of client memory, making memory analysis misleading. 3. The maxmemory-clients eviction mechanism could not account for this memory, potentially allowing clients to bypass memory limits. The same issues apply to SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE with large or numerous channel/pattern names. Since valkey-io#4072, watched keys and pubsub patterns are now shared across clients via refcount, just like pubsub channels. We still attribute the memory to every subscribing/watching client, because each client holds a reference and this is what makes the memory visible to CLIENT INFO tot-mem and chargeable against maxmemory-clients. Note this means a shared object is counted once per subscriber/watcher, so the per-client sum can exceed the physical allocation. Changes: - Add watched_keys_mem field to multiState struct to track watched key robj memory with O(1) lookup - Add pubsub_object_mem field to ClientPubSubData struct to track channel/pattern robj memory with O(1) lookup - Introduce `getStringObjectMemory()` helper to avoid repeating the `sizeof(robj) + sdsAllocSize(objectGetVal(o))` pattern. - Use `hashtablePop` to get the stored object when unsubscribing, so the memory counter uses the same object that was originally counted. The memory counters are updated on add/delete operations, making the overhead calculation O(1) instead of O(N). Signed-off-by: Binbin <binloveplay1314@qq.com> Signed-off-by: Alon Arenberg <alonare@amazon.com>
### Problem Client memory counted the WATCH and Pub/Sub containers, not the key, channel, and pattern name objects. Large or numerous names under-reported tot-mem, showed up as dataset memory, and were invisible to maxmemory-clients. ### Solution Each client is charged for the name objects it holds. Counters stay O(1) and update on registration and removal. Removal uncharges the stored object. Watched keys and patterns now share one server object across clients, as channels already do. Every holder is charged, so tot-mem and eviction see a client with many or large names. The extra (N − 1) charges are subtracted from mem_clients_normal and from the maxmemory-clients check, so those totals match the allocated memory. A write to a watched key, a shard slot moving away, or an ACL change that disconnects a subscriber immediately updates the memory stats and eviction bucket of each client that loses the name. ### Behavior tot-mem, mem_clients_normal, and the dataset/overhead split include these names. Heavy watchers and subscribers can be evicted sooner. When a name is shared, the sum of tot-mem can exceed mem_clients_normal. Per-client values are what each client holds. The aggregate is what was allocated. No RESP, replication, persistence, or cluster-protocol changes. valkey-io/valkey#3362 charges each holder and uses that sum for aggregates and the eviction threshold, so shared names inflate mem_clients_normal and can trigger eviction that frees nothing. Redis subtracts the extra charges from both. ### Tests tot-mem for WATCH, SUBSCRIBE, PSUBSCRIBE, and SSUBSCRIBE: long names, repeat registration, unsubscribe, and UNWATCH, MULTI/EXEC, DISCARD, and RESET for watches. Eviction on accumulated large names. Shared names counted once in totals and in eviction. First holder leaving and last holder disconnecting, a write that drops a shared watch, eviction order after that drop, and shard slot migration. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes how client memory is computed and when maxmemory-clients evicts clients; logic is subtle around shared objects but is covered by new tests and only affects accounting/eviction, not command semantics. > > **Overview** > **Client `tot-mem` now includes the string objects for WATCH keys and Pub/Sub channel/pattern names**, not just list/dict overhead. Per-client counters (`watched_keys_mem`, `pubsub_names_mem`) update on add/remove, and **`multiStateMemOverhead` / `pubsubMemOverhead`** fold that into eviction sizing. > > **WATCH keys reuse the server’s canonical key object** when another client already watches the same key (matching existing Pub/Sub sharing). Every holder is charged the full name size, so **`stat_clients_watch_pubsub_shared_overcount`** tracks the extra (N−1) charges; **`subtractClientsWatchPubsubOvercount`** removes that from **`mem_clients_normal`** and the **`maxmemory-clients`** eviction threshold so aggregates match real allocation. > > **`updateClientWatchPubsubMemoryUsage`** refreshes per-client totals and eviction buckets when watch/pubsub name memory changes without a full **`updateClientMemoryUsage`** pass (e.g. UNWATCH, unsub, slot migration bulk unsub, pubsub teardown). > > Tests cover **`CLIENT LIST`/`INFO` `tot-mem`**, shared-name totals vs per-client sums, eviction on large names, watch invalidation after writes, and shard slot migration uncharging subscribers. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 77479a0. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
Previously, multiStateMemOverhead() and pubsubMemOverhead() only
counted the structure overhead (listNode, watchedKey, hashtable)
but not the actual watched_key/channel/pattern robj objects
themselves. This led to under-reporting of client memory usage.
This was problematic because:
this memory was invisible in CLIENT INFO tot-mem, making it hard to
identify which client is consuming memory.
of client memory, making memory analysis misleading.
memory, potentially allowing clients to bypass memory limits.
The same issues apply to SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE with large or
numerous channel/pattern names.
Since #4072, watched keys and pubsub patterns are now shared across clients
via refcount, just like pubsub channels. We still attribute the memory to
every subscribing/watching client, because each client holds a reference
and this is what makes the memory visible to CLIENT INFO tot-mem and chargeable
against maxmemory-clients. Note this means a shared object is counted once
per subscriber/watcher, so the per-client sum can exceed the physical allocation.
Changes:
robj memory with O(1) lookup
channel/pattern robj memory with O(1) lookup
getStringObjectMemory()helper to avoid repeating thesizeof(robj) + sdsAllocSize(objectGetVal(o))pattern.hashtablePopto get the stored object when unsubscribing, so thememory counter uses the same object that was originally counted.
The memory counters are updated on add/delete operations, making the
overhead calculation O(1) instead of O(N).