Skip to content

fix: Prevent EXISTS from incrementing keyspace hit/miss stats - #3986

Open
yulazariy wants to merge 1 commit into
valkey-io:unstablefrom
yulazariy:fix/valkey-exists-cache-miss
Open

yulazariy wants to merge 1 commit into
valkey-io:unstablefrom
yulazariy:fix/valkey-exists-cache-miss

Conversation

@yulazariy

Copy link
Copy Markdown
Contributor

Add LOOKUP_NOSTATS flag to lookupKeyReadWithFlags in existsCommand so that EXISTS does not affect keyspace_hits or keyspace_misses counters. These stats are meant for cache hit/miss tracking and EXISTS is a key existence check, not a cache access.

Add LOOKUP_NOSTATS flag to lookupKeyReadWithFlags in existsCommand so
that EXISTS does not affect keyspace_hits or keyspace_misses counters.
These stats are meant for cache hit/miss tracking and EXISTS is a key
existence check, not a cache access.

Signed-off-by: Yehonatan Yulazari <yulazari@amazon.com>
@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

πŸ“ Walkthrough

Walkthrough

existsCommand in src/db.c adds LOOKUP_NOSTATS to its lookupKeyReadWithFlags call, preventing keyspace hit/miss counter increments. A new test in tests/unit/keyspace.tcl snapshots the counters, runs EXISTS on existing and missing keys, and asserts the counters are unchanged.

EXISTS keyspace stats suppression

Layer / File(s) Summary
Add LOOKUP_NOSTATS to existsCommand and verify with test
src/db.c, tests/unit/keyspace.tcl
existsCommand now passes LOOKUP_NOTOUCH | LOOKUP_NOSTATS so keyspace hit/miss counters are not updated. The new test snapshots keyspace_hits and keyspace_misses, calls EXISTS for both an existing and a non-existing key, and asserts both counters remain unchanged.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

πŸš₯ Pre-merge checks | βœ… 5
βœ… Passed checks (5 passed)
Check name Status Explanation
Title check βœ… Passed The title accurately and concisely describes the main change: preventing EXISTS from incrementing keyspace hit/miss stats.
Description check βœ… Passed The description clearly explains the change (adding LOOKUP_NOSTATS flag), the affected function, and the rationale for the change.
Docstring Coverage βœ… Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@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

πŸ€– 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 `@tests/unit/keyspace.tcl`:
- Line 76: The test at line 76 assumes that nonexistingkey is absent when
calling r exists nonexistingkey, but does not explicitly ensure this beforehand.
This can cause test failures if prior test state leaks and the key actually
exists, preventing the miss path from being exercised. Before the EXISTS call on
nonexistingkey, explicitly delete the key using r del nonexistingkey or assert
its absence to guarantee deterministic behavior and ensure the miss path is
always tested regardless of prior test state.
πŸͺ„ 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: 8212c92c-acf2-40a1-9bae-102e6dddc662

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 699c64e and 33b8aa6.

πŸ“’ Files selected for processing (2)
  • src/db.c
  • tests/unit/keyspace.tcl

Comment thread tests/unit/keyspace.tcl
set hits_before [getInfoProperty $info keyspace_hits]
set misses_before [getInfoProperty $info keyspace_misses]
r exists existskey
r exists nonexistingkey

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.

⚠️ Potential issue | 🟑 Minor | ⚑ Quick win

Make the miss-path assertion deterministic.

At Line 76, nonexistingkey is assumed absent; if prior test state leaks, this can become a hit and stop exercising the miss path. Explicitly delete/assert absence before the EXISTS call.

Suggested patch
     test {EXISTS does not update keyspace hits or misses} {
         r set existskey value
+        r del nonexistingkey
         set info [r info stats]
         set hits_before [getInfoProperty $info keyspace_hits]
         set misses_before [getInfoProperty $info keyspace_misses]
         r exists existskey
         r exists nonexistingkey
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
r exists nonexistingkey
test {EXISTS does not update keyspace hits or misses} {
r set existskey value
r del nonexistingkey
set info [r info stats]
set hits_before [getInfoProperty $info keyspace_hits]
set misses_before [getInfoProperty $info keyspace_misses]
r exists existskey
r exists nonexistingkey
πŸ€– 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/keyspace.tcl` at line 76, The test at line 76 assumes that
nonexistingkey is absent when calling r exists nonexistingkey, but does not
explicitly ensure this beforehand. This can cause test failures if prior test
state leaks and the key actually exists, preventing the miss path from being
exercised. Before the EXISTS call on nonexistingkey, explicitly delete the key
using r del nonexistingkey or assert its absence to guarantee deterministic
behavior and ensure the miss path is always tested regardless of prior test
state.

@ranshid

ranshid commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Thank you @yulazariy IMO this makes sense. I do think this is makes sense, but it is also a behavioral change (even if never documented)
I will flag it as "major-decision" and ask @valkey-io/core-team to +/-1.
(BTW - currently set major-decision-needed". once another TSC member approve, will make it major-decision-pending-auto-approve)

@ranshid ranshid added the major-decision-pending Major decision pending by TSC team label Jun 14, 2026
@yulazariy

Copy link
Copy Markdown
Contributor Author

cool thanks @ranshid

Also looks like there is a (not related) flakey test https://github.com/valkey-io/valkey/actions/runs/27496365556/job/81271055172?pr=3986

@zuiderkwast

Copy link
Copy Markdown
Contributor

@valkey-review-bot Is this a backward compatible change according to semantic versioning?

@valkey-review-bot

valkey-review-bot Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

On the backward-compatibility question (@zuiderkwast): this is a behavioral change to a public, observable interface, not an API-breaking one.

  • No command surface changes: EXISTS syntax, arity, and reply are untouched, so nothing a client parses breaks.
  • What changes is the semantics of the keyspace_hits / keyspace_misses fields in INFO stats (src/server.c:6517-6518), which monitoring and cache-efficiency tooling consume. After this PR, EXISTS no longer contributes to either counter, so any dashboard/alert that today includes EXISTS traffic in its hit/miss ratio will shift. The per-command contribution was never documented, but the counters themselves are a stable public metric.

So: API-compatible, but a metric-semantics change. Under semver this fits a minor release (or a patch with an explicit release note), not a silent patch β€” consistent with @ranshid flagging it as a major-decision. One thing worth settling before merge: the change leaves EXISTS inconsistent with its sibling read-introspection commands β€” TYPE (src/db.c:1420, LOOKUP_NOTOUCH only) and OBJECT (src/object.c:1687, LOOKUP_NOTOUCH | LOOKUP_NONOTIFY) both still increment hits/misses. If the rationale is "existence/introspection checks aren't cache accesses," it applies equally to those; if it's EXISTS-specific, that's worth stating.

One inline note on a side effect of the chosen flag.

Comment thread src/db.c

for (j = 1; j < c->argc; j++) {
if (lookupKeyReadWithFlags(c->db, c->argv[j], LOOKUP_NOTOUCH)) count++;
if (lookupKeyReadWithFlags(c->db, c->argv[j], LOOKUP_NOTOUCH | LOOKUP_NOSTATS)) count++;

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.

LOOKUP_NOSTATS suppresses the keyspace_misses counter, but the keymiss keyspace notification is gated separately on LOOKUP_NONOTIFY (src/db.c:120-121), which is not passed here. So after this change EXISTS on a missing key still fires a NOTIFY_KEY_MISS (keymiss) event while no longer incrementing keyspace_misses β€” the two were previously in lockstep for this command.

If the intent is "EXISTS is not a cache access," the notification arguably should be suppressed too, for consistency with the stats:

Suggested change
if (lookupKeyReadWithFlags(c->db, c->argv[j], LOOKUP_NOTOUCH | LOOKUP_NOSTATS)) count++;
if (lookupKeyReadWithFlags(c->db, c->argv[j], LOOKUP_NOTOUCH | LOOKUP_NOSTATS | LOOKUP_NONOTIFY)) count++;

If firing keymiss for EXISTS is intentional (some clients rely on it for key-tracking/invalidation), then leaving it as-is is fine β€” but worth confirming, since the divergence is easy to miss.

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.

@valkey-review-bot good catch about the LOOKUP_NONOTIFY. what other implications will there be if we add that one as well?

@zuiderkwast

Copy link
Copy Markdown
Contributor

@valkey-review-bot Whether the behavior change breaks the documented behavior depends on whether this behavior is publicly documented for this command and these stats, right? The public documentation is in the valkey-doc repo.

@valkey-review-bot

valkey-review-bot Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

On the documentation question (@zuiderkwast): I can't inspect the valkey-doc repo from here, so I can't confirm what it states about EXISTS or about keyspace_hits/keyspace_misses β€” that check has to happen against valkey-doc directly. What I can confirm from this repo:

  • The in-repo command metadata for EXISTS (src/commands/exists.json) documents only summary, complexity, and reply shape. It says nothing about keyspace hit/miss accounting, so there is no in-repo documented contract this change contradicts.
  • There is no test or code in the tree that asserts EXISTS contributes to keyspace_hits/keyspace_misses (no match for such a coupling), so there is no in-repo regression signal either.

So whether this "breaks documented behavior" reduces entirely to what valkey-doc says about these two INFO fields and whether per-command contribution is described there. If valkey-doc only describes the counters generically (cache hit/miss tracking) without enumerating which commands feed them, this is a semantics shift but not a contradiction of a written contract; if it explicitly lists EXISTS as a contributor, it would be.

One code-level note that bears on framing this purely as a "stats" change: with LOOKUP_NOSTATS alone, EXISTS on a missing key still fires the keymiss keyspace notification (gated separately on LOOKUP_NONOTIFY at src/db.c:120-121), so the counter and the notification β€” previously in lockstep for this command β€” now diverge. That is already noted inline at src/db.c:904, and the divergence from the TYPE/OBJECT introspection siblings was raised earlier in the thread; no new inline comment needed here.

@enjoy-binbin enjoy-binbin 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.

If it is a NOTOUCH, NOSTATS also make sense to me.

@enjoy-binbin enjoy-binbin added the release-notes This issue should get a line item in the release notes label Jun 15, 2026
@ranshid

ranshid commented Jun 15, 2026

Copy link
Copy Markdown
Member

On the backward-compatibility question (@zuiderkwast): this is a behavioral change to a public, observable interface, not an API-breaking one.

  • No command surface changes: EXISTS syntax, arity, and reply are untouched, so nothing a client parses breaks.
  • What changes is the semantics of the keyspace_hits / keyspace_misses fields in INFO stats (src/server.c:6517-6518), which monitoring and cache-efficiency tooling consume. After this PR, EXISTS no longer contributes to either counter, so any dashboard/alert that today includes EXISTS traffic in its hit/miss ratio will shift. The per-command contribution was never documented, but the counters themselves are a stable public metric.

So: API-compatible, but a metric-semantics change. Under semver this fits a minor release (or a patch with an explicit release note), not a silent patch β€” consistent with @ranshid flagging it as a major-decision. One thing worth settling before merge: the change leaves EXISTS inconsistent with its sibling read-introspection commands β€” TYPE (src/db.c:1420, LOOKUP_NOTOUCH only) and OBJECT (src/object.c:1687, LOOKUP_NOTOUCH | LOOKUP_NONOTIFY) both still increment hits/misses. If the rationale is "existence/introspection checks aren't cache accesses," it applies equally to those; if it's EXISTS-specific, that's worth stating.

One inline note on a side effect of the chosen flag.

@valkey-review-bot I think it makes sense that EXISTS behaves different than the OBJECT and TYPE keyspace commands. EXISTS is a way to query key existence so it will naturally experience cache misses, while the other commands are targeting existing keys, and thus IMO makes it expectable to have a reported hit/miss statistics.

@valkey-review-bot

valkey-review-bot Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

@ranshid β€” answering your follow-up about the implications of also passing LOOKUP_NONOTIFY here.

I agree with your reasoning that EXISTS can justifiably diverge from TYPE/OBJECT on the hit/miss counters (it is an existence probe that naturally encounters misses). The remaining decision is narrowly about the keymiss notification, which this PR leaves firing. Details inline on src/db.c:904.

Comment thread src/db.c

for (j = 1; j < c->argc; j++) {
if (lookupKeyReadWithFlags(c->db, c->argv[j], LOOKUP_NOTOUCH)) count++;
if (lookupKeyReadWithFlags(c->db, c->argv[j], LOOKUP_NOTOUCH | LOOKUP_NOSTATS)) count++;

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.

On what adding LOOKUP_NONOTIFY would change here β€” the keymiss event has exactly two consumers, and tracking is not one of them:

  • Keyspace pub/sub: subscribers of __keyevent@<db>__:keymiss (i.e. operators running with m in notify-keyspace-events) would stop seeing an event when EXISTS probes a missing key. This branch is config-gated at src/notify.c:131-157.
  • Modules: moduleNotifyKeyspaceEvent (src/notify.c:124) fires unconditionally, so any module subscribed via VALKEYMODULE_NOTIFY_KEY_MISS would stop getting the callback for EXISTS misses.
  • Client-side caching / invalidation is unaffected. Key tracking is driven by the CMD_READONLY flag in src/server.c:4083-4091 (trackingRememberKeys), independent of both keyspace_misses and the keymiss notification β€” so neither this PR nor adding LOOKUP_NONOTIFY changes what tracking-enabled clients get invalidated on.

So the only behavior at stake is the keymiss keyspace event / module notification, not invalidation. If the intent is "EXISTS is a pure existence probe that produces no observable side effects," the codebase already has a name for that exact combination:

Suggested change
if (lookupKeyReadWithFlags(c->db, c->argv[j], LOOKUP_NOTOUCH | LOOKUP_NOSTATS)) count++;
if (lookupKeyReadWithFlags(c->db, c->argv[j], LOOKUP_NOEFFECTS)) count++;

LOOKUP_NOEFFECTS is defined at src/server.h:3753 as LOOKUP_NONOTIFY | LOOKUP_NOSTATS | LOOKUP_NOTOUCH | LOOKUP_NOEXPIRE. Using it would keep stats and the notification in lockstep (both suppressed) and match the documented "avoid any effects from fetching the key" intent. If instead you want EXISTS to keep emitting keymiss (e.g. to preserve the module/pub-sub signal that a probe occurred) while only dropping the counter, the current LOOKUP_NOTOUCH | LOOKUP_NOSTATS is fine β€” but that intentional split is worth a one-line comment, since the next reader will see stats and notification diverge and assume it was an oversight.

@madolson

Copy link
Copy Markdown
Member

I don't think this is a real bug and I don't think we should change it unless someone is actually complaining about it. If we want to go do the effort to more comprehensively define what a cache hit/cache miss is, then I might be OK. But right now it's really just "You accessed a key and it was there". Which feels like exists.

@yulazariy

Copy link
Copy Markdown
Contributor Author

In AWS we got a feedback from several customers that are look into the cache hit/cache miss metrics and find it miss-leading as they use exists before actually retrieving keys from the cache.

@JimB123

JimB123 commented Jul 6, 2026

Copy link
Copy Markdown
Member

I don't think this is a real bug [...]. If we want to go do the effort to more comprehensively define what a cache hit/cache miss is, then I might be OK. But right now it's really just "You accessed a key and it was there". Which feels like exists.

I'm inclined to agree. The EXISTS command has a key, and the key either exists or not. This is currently the same as the definition for hit/miss. Changing this would be a "breaking change" and a deviation from the historical Redis behavior.

@ranshid

ranshid commented Jul 6, 2026

Copy link
Copy Markdown
Member

Alternative options we considered in the TSC meeting:

  1. add a configuration to control this behavior.
  2. can we consider adding a client no-stats command?
  3. consider having misses per command?
  4. add new command - EXISTSNOSTATS
  5. Add flags to multi/exec block (eg no-stats) so these are applied for the transaction lifetime (what if I mark the transaction like that and issue client no-touch in the transaction? :) )

@yulazariy - Seems like we are not-inclined for this specific option and will follow up with some of the alternatives.

@ranshid ranshid added the major-decision-deferred The core team doesn't accept this now, but might change their minds if new motivation is presented. label Jul 15, 2026
@madolson madolson added the breaking-change Indicates a possible backwards incompatible change label Sep 11, 2026
@madolson madolson removed this from Valkey 9.2 Sep 11, 2026
@madolson madolson removed the breaking-change Indicates a possible backwards incompatible change label Sep 11, 2026
@madolson madolson moved this to Todo in Valkey 9.2 Sep 11, 2026
@madolson madolson removed this from Valkey 10.0 Sep 11, 2026
@madolson madolson removed the status in Valkey 9.2 Sep 14, 2026
@yulazariy

Copy link
Copy Markdown
Contributor Author

@ranshid have we considered other alternatives? or there is a consensus this is the required behavior?

@zuiderkwast

zuiderkwast commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Trying to think of alternative ways to check key existence without touching keyspace hits/misses:

  • KEYS key – Works, but very inefficient and not cluster-slot-routed. SCAN 0 MATCH key similar.
  • OBJECT ENCODING key – Suppresses keymiss notifications and hot-key sampling, but still increments hits/misses. (That seem arbitrary though. Maybe we can change it?)
  • DEBUG OBJECT key – Not documented, not cluster-routed, not enabled by default, can return logically expired keys.
  • INCREX key BYINT 0 XX – Doesn't increment hits/misses, but:
    • It can't distinguish between non-existing key and a key with the value "0". Both are returned as [0, 0]
    • Replicated
    • Touches LRU
    • Signal modified key (invalidates WATCH)
    • Notify keyspace event "incrby"
    • Write command; not allowed on readonly replicas

If we want to introduce a new command and not announce it too loudly, we could do it as an OBJECT subcommand maybe: OBJECT EXISTS key?

@yulzabi

yulzabi commented Sep 17, 2026

Copy link
Copy Markdown

So in my opinion the above suggestions feels very hacky.
What about adding a flag option like NOSTATS or similar to the EXISTS command?

@zuiderkwast

Copy link
Copy Markdown
Contributor
EXISTS key [ key ... ] 

The existing syntax doesn't permit any options. All arguments are keys and key names can be anything including "nostats".

A new command like EXISTSNOSTATS key... or EXISTSX [options] key...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

major-decision-deferred The core team doesn't accept this now, but might change their minds if new motivation is presented. major-decision-pending Major decision pending by TSC team release-notes This issue should get a line item in the release notes

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

7 participants