Skip to content

Include watched keys and pubsub channel/pattern memory in client memory overhead - #3362

Merged
enjoy-binbin merged 10 commits into
valkey-io:unstablefrom
enjoy-binbin:client_memory
Jul 21, 2026
Merged

enjoy-binbin merged 10 commits into
valkey-io:unstablefrom
enjoy-binbin:client_memory

Conversation

@enjoy-binbin

@enjoy-binbin enjoy-binbin commented Mar 13, 2026 •

Copy link
Copy Markdown
Member

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 #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).

…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>
Comment thread src/multi.c Resolved
@codecov

codecov Bot commented Mar 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.72%. Comparing base (debe5c5) to head (7e9e344).

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     
Files with missing lines Coverage Δ
src/multi.c 97.27% <100.00%> (-0.66%) ⬇️
src/networking.c 92.32% <100.00%> (+0.12%) ⬆️
src/pubsub.c 97.78% <100.00%> (+0.06%) ⬆️
src/server.h 100.00% <ø> (ø)

... and 18 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Signed-off-by: Binbin <binloveplay1314@qq.com>

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

Memory overhead looks correct but you added some chinese notes. 😆

I usually save notes under misc/ locally because misc is in .gitignore.

Comment thread .codebuddy/memory/2026-03-23.md Resolved
Signed-off-by: Binbin <binloveplay1314@qq.com>
Comment thread src/pubsub.c Resolved
@enjoy-binbin
enjoy-binbin requested a review from madolson April 1, 2026 08:10
@enjoy-binbin enjoy-binbin added the release-notes This issue should get a line item in the release notes label Apr 2, 2026
@madolson madolson moved this to Needs Review in Valkey 9.2 May 10, 2026
…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>
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d2333ecf-4be2-49c8-864b-43f47d3c0ea1

📥 Commits

Reviewing files that changed from the base of the PR and between 1b41a81 and 7e9e344.

📒 Files selected for processing (4)
  • src/multi.c
  • src/networking.c
  • src/server.h
  • tests/unit/introspection.tcl
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/networking.c
  • src/server.h

📝 Walkthrough

Walkthrough

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

Changes

Per-client memory tracking for watched keys and pubsub

Layer / File(s) Summary
Struct fields and function prototype
src/server.h
Adds watched_keys_mem to multiState, pubsub_object_mem to ClientPubSubData, and declares getStringObjectMemory(robj *o).
getStringObjectMemory helper and comment updates
src/networking.c
Implements getStringObjectMemory as sizeof(robj) plus getStringObjectSdsUsedMemory; updates getClientMemoryUsage comments.
Watched-key memory tracking
src/multi.c
Tracks watched-key object memory on watch/unwatch and includes the counter in multiStateMemOverhead.
Pubsub object memory tracking
src/pubsub.c
Initializes pubsub_object_mem, tracks channel/pattern object memory through subscribe/unsubscribe paths, and includes it in pubsubMemOverhead.
Tests
tests/unit/introspection.tcl
Adds get_client_mem_no_qbuf and tests for WATCH/UNWATCH plus pubsub subscribe/unsubscribe memory changes and shared-object cases.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • valkey-io/valkey#4072: Shares the same canonical-robj handling in watchForKey and pubsubSubscribePattern, with related changes to how those objects are reused.

Suggested reviewers: zuiderkwast, madolson

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding watched-key and pubsub object memory to client overhead.
Description check ✅ Passed The description directly matches the changeset and explains the client memory accounting update.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@enjoy-binbin enjoy-binbin added the run-extra-tests Run extra tests on this PR (Runs all tests from daily except valgrind and RESP) label Jun 30, 2026

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/unit/introspection.tcl (1)

42-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Add coverage for the slot-migration shard unsubscribe path.

This loop only exercises explicit sunsubscribe, but the PR also fixes memory accounting in pubsubShardUnsubscribeAllChannelsInSlot(). 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

📥 Commits

Reviewing files that changed from the base of the PR and between 091d5ca and 8c99ecc.

📒 Files selected for processing (5)
  • src/multi.c
  • src/networking.c
  • src/pubsub.c
  • src/server.h
  • tests/unit/introspection.tcl

Comment thread src/pubsub.c Resolved
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>
@coderabbitai

coderabbitai Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

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>
@enjoy-binbin
enjoy-binbin marked this pull request as draft June 30, 2026 15:38

@coderabbitai coderabbitai Bot 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.

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 lift

Shared 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's watched_keys_mem. From the second watcher onward, no new string object is allocated, yet CLIENT INFO tot-mem and maxmemory-clients will 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

📥 Commits

Reviewing files that changed from the base of the PR and between b86636a and 1b41a81.

📒 Files selected for processing (3)
  • src/multi.c
  • src/pubsub.c
  • tests/unit/introspection.tcl
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/unit/introspection.tcl
  • src/pubsub.c

enjoy-binbin added a commit that referenced this pull request Jul 3, 2026
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>
@enjoy-binbin
enjoy-binbin marked this pull request as ready for review July 3, 2026 07:42
vansvan17 pushed a commit to vansvan17/valkey that referenced this pull request Jul 9, 2026
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>
alon-arenberg pushed a commit to alon-arenberg/valkey that referenced this pull request Jul 15, 2026
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>
@enjoy-binbin
enjoy-binbin merged commit 0385d2f into valkey-io:unstable Jul 21, 2026
77 checks passed
@github-project-automation github-project-automation Bot moved this from Needs Review to Merged in Valkey 9.2 Jul 21, 2026
@enjoy-binbin
enjoy-binbin deleted the client_memory branch July 21, 2026 03:02
alon-arenberg pushed a commit to alon-arenberg/valkey that referenced this pull request Jul 30, 2026
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>
alon-arenberg pushed a commit to alon-arenberg/valkey that referenced this pull request Jul 30, 2026
…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>
StavRLevi added a commit to redis/redis that referenced this pull request Nov 6, 2026
### 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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-notes This issue should get a line item in the release notes run-extra-tests Run extra tests on this PR (Runs all tests from daily except valgrind and RESP)

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

[BUG] WATCH can consume large amounts of memory and bypasses OOM

2 participants